text:
//===================================================================
// Gunpow^H^H^H^HMagic powder used to fire the cannons for the piracy
// quest. It's also has some pretty nifty other uses, if LAW agrees.
// You get powder by pouring it from a barrel (magic_powder_barrel.c)
// found in lev1_gunpowder_room. The barrel has 10 charges. It can be
// a pk toy I guess but the one using it will take as much of a
// beating as the victim(s). A nonpk use for it can be dealing with
// troublesome blocking monsters. It can't be used in no_fight rooms
// and unkillable/no_flee monsters will not be blown away
//===================================================================
#pragma strict_types
#include "../def.h"
inherit STD_STDOBJ;
inherit STD_LORE;
inherit CHECK_FIRE_MODULE;
inherit "/std/modules/general/identity";
inherit "/std/modules/general/description";
inherit "/std/modules/general/weight";

int wet; // This is set by the barrel if you pour the powder out
         // in a sea/underwater room

void create_object(void);
void init(void);
int get(string str);
void set_wet(int is_wet);
int do_ignite(string str);
void explode(object igniter);
void throw_object(object thing);
string opposite_dest_dir(string str);

void create_object(void)
{
    set_name("powder");
    add_id("black powder");
    add_id("magic powder");
    add_id("pile");
    set_short("A small pile of black powder");
    set_long("A small pile of black powder. The powder looks dry and has " +
             "a funny smell.\n");
    set_weight(1);

    add_property("magic");

    add_lore("You've heard stories about pirates using magic black powder " +
             "in some way when they capture ships.\n",1);
    add_lore("You think the pirates use the powder to fire missiles at " +
             "other ships. You wonder what would happen if you ignited " +
             "the powder.\n",10);
    set_material("magic"); //Angelwings
}

void init(void)
{
   add_multi_action("do_ignite","ignite|light");
}

void set_wet(int is_wet)
{
    wet = is_wet;
    set_long("The powder is wet and doesn't look interesting at all.\n");
}

int get(string str)
{
    notify_fail("You try to take the powder but it slips through your " +
                "fingers and back into a pile on the floor.\n");
}

int do_ignite(string str)
{
    int i;
    object *inventory = all_inventory(TP);

    if(wet)
    {
        return notify_fail("The powder is wet and can't be ingnited.\n");
    }
    if(str == "powder")
    {
        if(query_can_light_powder(TP))
        {
            if(!ENV(TP)->query_property("no_fight"))
            {
                W("You bend down and ignite the black powder.\n");
                S(TP->QN + " bends down and ignites the black powder on the " +
                  "ground.\n");
                explode(TP);
                return 1;
            }
            else
            {
                W("This room is too peaceful for you to do that.\n");
                return 1;
            }
        }
        W("You need some sort of fire to ignite the powder.\n");
        S(TP->QN + " bends down to study the powder.\n");
        return 1;
    }
    else if(query_verb() == "ignite")
    {
        return notify_fail("Ignite what?\n");
    }
    // Don't want to stop lighting other things here
    return 0;
}

void explode(object igniter)
{
    int i,mass;
    string junk,*exits = ENV(TO)->query_dest_dir();
    object *things = all_inventory(ENV(TO));
    object *players = users();

    set_this_player(igniter);

    tell_room(ENV(TO),"\n" +
                      "K  K  AAA  BBB   OOO   OOO  M   M ! !\n" +
                      "K K  A   A B  B O   O O   O MM MM ! !\n" +
                      "KK   AAAAA BBB  O   O O   O M M M ! !\n" +
                      "K K  A   A B  B O   O O   O M   M    \n" +
                      "K  K A   A BBB   OOO   OOO  M   M ! !\n\n");

    for(i = 0; i < sizeof(exits); ++i)
    {
        tell_room(exits[i],"KABOOOOOOOOMMMMMMMM!!!!!!!!!!!!!\n" +
                  "A loud explosion is heard from " +
                  opposite_dest_dir(exits[++i]) + "!\n");
    }

    if(igniter)
    {
        write_file(POWDER_LOG,"\n" + ctime(time()) +": " + C(TP->QRN) +
                   " lit the powder in:\n                          " +
                   name_file(ENV(TP)) + "\n");
    }
    else
    {
        write_file(POWDER_LOG,"\n" + ctime(time()) +": Powder combusted " +
                   "spontaneously in:\n                          " +
                   name_file(ENV(TO)) + "\n");
    }
    // Let all players in the same area but not in adjacent room hear the
    // explosion from somewhere as well
    for(i = 0; i < sizeof(players); ++i)
    {
        if(!present(players[i],ENV(TO)) &&
           member_array(name_file(ENV(players[i])),exits) == -1 &&
           ENV(TO)->query_area_name() == ENV(players[i])->query_area_name())
        {
            tell_object(players[i],"KABOOM!!\n" +
                        "A loud explosion is heard from somewhere in the " +
                        "area.\n");
        }
    }

    for(i = 0; i < sizeof(things); ++i)
    {
        // Stat check vs con & siz for living things. The bigger and tougher
        // you are the less risk you have of being thrown out of the room
        // by the explosion. The playing setting it off will always be thrown
        if(living(things[i]))
        {
            write_file(POWDER_LOG,"\n                          " +
                       things[i]->short() + " (" + things[i]->QRN + ")\n" +
                       "                          " + name_file(things[i]) +
                       "\n                          Con: " +
                       things[i]->query_con() + " Siz: " +
                       things[i]->query_siz() + "\n");

            mass = things[i]->query_con() + things[i]->query_siz();
            if(things[i] == TP || mass < 25 + random(25))
            {
                // We'll be nice and not blow away unkillable and/or
                // no_flee monsters even if they are puny
                if(!things[i]->is_unkillable() &&
                   !things[i]->query_property("no_flee"))
                {
                    throw_object(things[i]);
                }
            }
            // Players not thrown will fall over or at least wobble, depending
            // on how big they are
            else if(query_interactive(things[i]))
            {
                if(mass < 50)
                {
                    tell_object(things[i],"The force of the explosion " +
                                "knocks you off your feet!\n");
                    things[i]->command("trip");
                    things[i]->add_temporary_penalty(5 + random(5));
                }
                else
                {
                    tell_object(things[i],"The force of the explosion " +
                                "almost knocks you off your feet!\n");
                    things[i]->command("wobble");
                }
            }
        }
        // If it is an object and fragile, it is destroyed instead of thrown
        else if(things[i]->query_property("fragile"))
        {
            tell_room(ENV(TO),C(things[i]->short()) + " shatters from the " +
                      "force of the explosion!!!\n");
            things[i]->destroy();
        }
        // We only want to blow things that aren't stuck out of the room, it
        // would be pretty silly to blow away boards and things like that
        else if(things[i]->get())
        {
            throw_object(things[i]);
        }
    }

    // Make smoke in this and all adjacent rooms (as long as they
    // are not water/under water rooms)
    make(PCOBJECT + "magic_powder_smoke",ENV(TO));
    for(i = 0; i < sizeof(exits); ++i)
    {
        if(!exits[i]->query_property("water") &&
           !exits[i]->query_property("under_water"))
        {
            make(PCOBJECT + "magic_powder_smoke",exits[i]);
        }
        ++i;
    }
    destroy();
}

/**
* Throws an object into a random adjacent room.
*/
void throw_object(object thing)
{
    string *exits = ENV(TO)->query_dest_dir();
    int rand;
    object room;

    // Skip the throwing thing if the room doesn't have any exits
    if(sizeof(exits) <= 0) return;

    rand = (random(sizeof(exits) / 2) * 2);
    room = find_object(exits[rand]);

    write_file(POWDER_LOG,"                          Was thrown " +
               exits[rand + 1] + " out of the room.\n");

    if(query_interactive(thing))
    {
        tell_object(thing,"The force of the explosion throws you " +
                    exits[rand + 1] + " out of the room!\n");
        thing->move_player("is thrown " + exits[rand + 1] + " out of the " +
                           "room by the force of the explosion!",
                           room,
                           "comes flying in from " +
                           opposite_dest_dir(exits[rand + 1]) + "!",1);
    }
    else if(!transfer(thing,room))
    {
        tell_room(ENV(TO),C(thing->short()) + " is thrown " +
                  exits[rand + 1] + " out of the room by the force of the " +
                  "explosion!\n");
        tell_room(room,C(thing->short()) + " comes flying in from " +
                  opposite_dest_dir(exits[rand + 1]) + "!\n");
    }
    // Monsters can't see the messages or get temps (yet) but we want
    // the land on the floor/ground/water things to be seen for both
    // players and monsters so we do living() instead of
    // query_interactive() here
    if(living(thing))
    {
        if(ENV(thing)->query_property("water") ||
           ENV(thing)->query_property("under_water"))
        {
            tell_object(thing,"You land in the water with a *SPLASH*!\n");
            tell_room(ENV(thing),thing->QN + " lands in " +
                      "the water with a *SPLASH*!\n",thing);
            thing->add_temporary_penalty(5 + random(10));
        }
        else
        {
            if(ENV(thing)->query_property("indoors"))
            {
                tell_object(thing,"You land on the floor with a *THUD*!\n");
                tell_room(ENV(thing),thing->QN + " lands on " +
                          "the floor with a *THUD*!\n",thing);
            }
            else
            {
                tell_object(thing,"You land on the ground with a *THUMP*!\n");
                tell_room(ENV(thing),thing->QN + " lands on " +
                          "the ground with a *THUMP*!\n",thing);
            }
            thing->add_temporary_penalty(25 + random(25));
        }
    }
}

/**
* Returns the opposite direction to the one given. This functionality
* might be available elsewhere but I don't know where if that's the
* case so here it is.
*/
string opposite_dest_dir(string str)
{
    switch(str)
    {
        case "north": return "the south";
        case "east": return "the west";
        case "south": return "the north";
        case "west": return "the east";

        case "northeast": return "the southwest";
        case "southeast": return "the northwest";
        case "southwest": return "the northeast";
        case "northwest": return "the southeast";

        case "up": return "below";
        case "down": return "above";
        // Other exits are rare enough that we can just use 'somewhere'
        default: return "somewhere";
    }
}


text:
using System;
using System.Net;
using System.Net.Sockets;

namespace System.Runtime.Remoting.Channels
{

    // This class provides a TcpListener that is capable of setting the ExclusiveAddressUse flag
    // on a socket, which will prevent another app from hijacking our port. This flag is not supported
    // on Win9x, so we just omit the call to SetSocketOption on non-NT platforms.
    internal class ExclusiveTcpListener : TcpListener
    {
        internal ExclusiveTcpListener(IPAddress localaddr, int port) : base(localaddr, port) {}

        // Start will attempt to start listening.  If exclusiveAddressUse is true, then
        // we will attempt to use the ExclusiveAddressUse flag, but if bind fails (which will
        // happen for a regular user on win2k and xp), we try again without the flag.
        internal void Start(bool exclusiveAddressUse)
        {
            // we only attempt to set the socket option if
            //   1. the exclusiveAddressUse param is true
            //   2. the platform is NT - this option is unavailable on other platforms
            //   3. Server is not null - if it IS null, base.Start will throw a nice error for us
            //   4. the listener is not already listening - it's too late in that case (base.Start will return immediately)
            bool attemptSetSocketOption = exclusiveAddressUse &&
#if !FEATURE_PAL
                                          Environment.OSVersion.Platform == PlatformID.Win32NT &&
#endif // !FEATURE_PAL
                                          base.Server != null &&
                                          !base.Active;

            if (attemptSetSocketOption)
            {
                // Attempt to set the option.  We won't actually find out if this fails until
                // we try to bind (which happens in base.Start()).
                base.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, 1);
            }

            try
            {
                base.Start();
            }
            catch (SocketException)
            {
                if (attemptSetSocketOption)
                {
                    // Turn off the option and try again - maybe this process doesn't have
                    // permission to use the option.
                    Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, 0);
                    base.Start();
                }
                else
                {
                    // It wasn't because we set the ExclusiveAddressUse option - let the
                    // exception bubble up
                    throw;
                }
            }
        }

        internal bool IsListening { get { return Active; } }

    }

} // namespace System.Runtime.Remoting.Channels

redpajama_set_name: RedPajamaGithub


text:
import { NodeType } from "../../../codeCharta.model"
import { _getHoveredNodePathPanelData } from "./hoveredNodePathPanelData.selector"

describe("hoveredNodePathPanelDataSelector", () => {
	it("should return undefined when there is no hovered node", () => {
		expect(_getHoveredNodePathPanelData()).toBe(undefined)
	})

	it("should return correct data for a file", () => {
		expect(
			_getHoveredNodePathPanelData({
				path: "/root/a.ts",
				type: NodeType.FILE
			})
		).toEqual({ path: ["root", "a.ts"], isFile: true })
	})

	it("should return correct data for a folder", () => {
		expect(
			_getHoveredNodePathPanelData({
				path: "/root",
				type: NodeType.FOLDER
			})
		).toEqual({ path: ["root"], isFile: false })
	})
})


text:
[azukiapp/erlang](http://images.azk.io/#/erlang)
==================

Base docker image to run **Erlang** applications in [`azk`](http://azk.io)

Versions (tags)
---

<versions>
- [`latest`, `1`, `1.0`](https://github.com/azukiapp/docker-erlang/blob/master/1.0/Dockerfile)
</versions>

Image content:
---

- Ubuntu 14.04
- Git
- VIM

Database:

- Erlang

### Usage with `azk`

Example of using this image with [azk](http://azk.io):

```js
/**
 * Documentation: http://docs.azk.io/Azkfile.js
 */

// Adds the systems that shape your system
systems({
  "my-app": {
    // Dependent systems
    depends: [], // postgres, mysql, mongodb ...
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/erlang"},
    // Steps to execute before running instances
    provision: [
    ],
    workdir: "/azk/#{manifest.dir}",
    shell: "/bin/bash",
    command: "# command to run app. i.g.: `./start`",
    wait: {"retry": 20, "timeout": 1000},
    mounts: {
      '/azk/#{manifest.dir}': path("."),
    },
    scalable: {"default": 1},
    http: {
      domains: [ "#{system.name}.#{azk.default_domain}" ]
    },
    ports: {
      // http: "8080"
    },
    envs: {
      // set instances variables
      EXAMPLE: "value",
    },
  },
});
```

### Usage with `docker`

To create the image `azukiapp/erlang`, execute the following command on the erlang folder:

```sh
$ docker build -t azukiapp/erlang .
```

Logs
---

```sh
# with azk
$ azk logs my-app

# with docker
$ docker logs <CONTAINER_ID>
```

## License

Azuki Dockerfiles distributed under the [Apache License][license].

[license]: ./LICENSE


text:
package io.quarkus.resteasy.test;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;

public class ConstructorInjectionResourceTestCase {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(ConstructorInjectionResource.class, SingletonConstructorInjectionResource.class,
                            Service.class));

    @Test
    public void testConstructorInjectionResource() {
        RestAssured.when().get("/ctor").then().body(Matchers.is("service"));
    }

    @Test
    public void testSingletonConstructorInjectionResource() {
        RestAssured.when().get("/ctor-single").then().body(Matchers.is("service"));
    }
}


text:
MindTouch DReAM
===============

Welcome to MindTouch DReAM.

Notes on Contributing to DReAM
------------------------------
If you have a new feature for DReAM, please work against master, however,
if you have a patch you'd like to see in the next point release, please
base your work on the release branch (currently 2.2).

If you submit a pull request for master, your changes will not make it
into an official releas until the next release branch is created
(current target, 2.3)

1. What is MindTouch DReAM?
---------------------------
MindTouch DReAM is a REST-based distributed application framework
developed in Mono/.NET. With DReAM, a Web service is similar to an
object, and features interact through standard HTTP verbs. This design
allows the developer to assume an "idealized" world where everything a
service comes into contact with is accessed through Web requests. The
DReAM service library addresses common problems, and the DReAM runtime
orchestrates all interactions without requiring a Web server to be
pre-installed on a target machine.

MindTouch DReAM manages all the complex aspects of interactive web
services, such as providing storage locations, database connections,
event notifications, automatic data conversion from XML to JSON and
short-circuit communication for co-hosted services. The platform enables
developers to create enterprise-ready service architectures with
exceptional speed and ease.

With DReAM, developers can create innovative services without worrying
about the underlying infrastructure. Moreover, developers can use his or
her programming language of choice and still leverage an open-source
platform for creating rich, interactive Web services that can generate
and combine data from multiple sources. With MindTouch DReAM, developers
can create interactive REST-based Web services for any platform,
including Linux, Mac OS and the entire Microsoft platform, as well as
virtually any device, from server to desktop to mobile device. MindTouch
DReAM is not new technology. What's new is the ease with which
developers can now develop and distribute compelling Web services,
because "behavior" is now mobile, not just data. MindTouch DReAM is
built on the premise that everything is remote.

2. System Requirements
----------------------
* To run
	* Microsoft Visual Studio 2008 with .Net 3.5 or later
	* Novell Mono v2.4 or later
* To build
	* Microsoft Visual Studio 2008 with .Net 3.5 or later
	* Novell Mono v2.8 or later

3. Additional Resources
-----------------------
* [Documentation](http://developer.mindtouch.com/DReAM)
* [Forums](http://forums.developer.mindtouch.com/forumdisplay.php?f=13)


text:
/**
 *
 */
sap.ui.define(function() {
	"use strict";
	// jQuery.sap.require("sap.ui.core.format.DateFormat");
	var formatter = {

			/**
			 * Get device name depending on Alias attribute
			 */
			getDeviceName: function (sDevAlias, sDevName) {
				return (sDevAlias ? sDevAlias : sDevName);
			},
	};

	return formatter;

}, /* bExport= */ true);


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>ch.securityvision.vidada</groupId>
	<artifactId>VidadaAggregate</artifactId>
    <packaging>pom</packaging>
    <name>Vidada Aggregate</name>
	<version>0.1.3-BETA</version>

	<modules>
   		<module>vidada</module>
		<module>vidada.client</module>
		<module>vidada.dal</module>
		<module>vidada.server</module>
		<module>vidada.core</module>
		<module>vidada.ffmpeg</module>
	</modules>

</project>


text:
module.exports = function pong (time, id) {
    console.log('Latency', Date.now() - time);
};


text:
package programmersguide.workingwithbarcodeimage.barcodeimagebasicfeatures.detectorientationofbarcode.java;

import com.aspose.barcode.*;

public class DetectOrientationOfBarCode
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/workingwithbarcodeimage/barcodeimagebasicfeatures/detectorientationofbarcode/data/";

    }
}


text:
//
//  SwapString.hpp
//  String
//
//  Created by 林涛 on 16/1/18.
//  Copyright © 2016年 limaofuyuanzhang. All rights reserved.
//

#include <stdio.h>
#include <string>
#include <vector>
#include <map>
using namespace std;

#ifndef SwapString_hpp
#define SwapString_hpp

class SwapString {

public:

    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    bool anagram(string s, string t);
    bool compareStrings(string A, string B);
    int strStr(const char *source, const char *target);
    vector<string> anagrams(vector<string> &strs);
    int longestCommonSubstring(string &A, string &B);
    string longestCommonPrefix(vector<string> &strs);
};
#endif /* SwapString_hpp */


text:
use get_input::get_input;

#[derive(Copy, Clone)]
enum Rotation {
    Left,
    Right,
}

impl Rotation {
    fn from_char(c: char) -> Option<Rotation> {
        match c {
            'L' => Some(Rotation::Left),
            'R' => Some(Rotation::Right),
            _ => None,
        }
    }
}

#[derive(Copy, Clone)]
enum Direction {
    North,
    East,
    South,
    West,
}

impl Direction {
    fn rotate(self, r: Rotation) -> Direction {
        match (r, self) {
            (Rotation::Left, Direction::North) => Direction::West,
            (Rotation::Left, Direction::East) => Direction::North,
            (Rotation::Left, Direction::South) => Direction::East,
            (Rotation::Left, Direction::West) => Direction::South,
            (Rotation::Right, Direction::North) => Direction::East,
            (Rotation::Right, Direction::East) => Direction::South,
            (Rotation::Right, Direction::South) => Direction::West,
            (Rotation::Right, Direction::West) => Direction::North,
        }
    }
}

struct Position {
    x: i32,
    y: i32,
}

impl Position {
    fn move_by(self, dir: Direction, dist: i32) -> Position {
        match dir {
            Direction::North => Position { x: self.x, y: self.y + dist },
            Direction::East => Position { x: self.x + dist, y: self.y },
            Direction::South => Position { x: self.x, y: self.y - dist },
            Direction::West => Position { x: self.x - dist, y: self.y },
        }
    }
}

fn parse_movement(m: &str) -> (Rotation, i32) {
    let mut m = m.trim().chars();
    let rotation = m.next().expect("Could not read input");
    let rotation = Rotation::from_char(rotation).unwrap();
    let distance = m.as_str().parse::<i32>().expect("Could not read integer in input");
    (rotation, distance)
}

pub fn solve() {
    let input = get_input("assets/day/1/input");
    //let input = "R8, R4, R4, R8";
    let mut position = Position { x: 0, y: 0 };
    let mut direction = Direction::North;

    for movement in input.split(',') {
        let (rotation, distance) = parse_movement(&movement);
        direction = direction.rotate(rotation);
        position = position.move_by(direction, distance);

        // Print Logo commands to draw the path,
        // turned out the first repeated position was easy to visually spot
        // 75, -4, for a distance of 79 for part 2
        println!("{} 90 fd {} -- {}, {}",
             match rotation {
                 Rotation::Left => "lt",
                 Rotation::Right => "rt",
             },
             distance,
             position.x,
             position.y
         );

        /*
        println!("{} x: {}, y: {}, facing {}",
            movement.trim(),
            position.x,
            position.y,
            pretty_orientation(orientation),
        );
        */
    }

    println!("Distance: {}", position.x.abs() + position.y.abs());
}


text:
(function () {
	"use strict";

	window.CommandsMgr = {
		startRecord: function (callback) {
			console.log("----------> startRecord()");
			if (!JobMgr.isJobReady()) {
				callback && callback({error: true, message: "Reconnect to the server" });
				return;
			}
			ConnectionMgr.sendToWS("startRecord", "mobile/record-started", true, null, true, callback);
		},
		performStartRecord: function (callback) {
			console.log("----------> performStartRecord()");
			CommandsMgr.updateRunTimeInfo();
			function onHandshakeComplete2(handshakeState) {
				console.log("----------> executed CB of serverHandshake");
				// Assumes that RTS contains deviceId and appId
				function onJobReady(response) {
					console.log("----------> executed CB of getJob");
					if (response.error) {
						console.error("----------> Error : " + response.message);
						callback(response);
					}
					else {
						if (!JobMgr.isJobReady()) {
							callback && callback({error: true, message: "Reconnect to the server" });
							return;
						}
						ConnectionMgr.sendToWS("startRecord", "mobile/record-started", true, null, true, callback);
					}
				}

				if (handshakeState.error) {
					console.error("----------> Error : " + handshakeState.message);
					callback && callback(handshakeState);
					return;
				}

				JobMgr.getJob(onJobReady);
			}

			ConnectionMgr.serverHandshake(false, onHandshakeComplete2);
		},
		stopRecord: function (callback) {
			console.log("----------> stopRecord()");
			ConnectionMgr.sendToWS("stopRecord", "mobile/record-stopped", true, null, true, callback);
		},
		performStopRecord: function (callback) {
			console.log("----------> performStopRecord()");
			this.stopRecord(callback);
		},
		performStartReplay: function (callback) {
			console.log("----------> performStartReplay()");
			CommandsMgr.updateRunTimeInfo();
			function onHandshakeComplete(handshakeState) {
				console.log("----------> executed CB of serverHandshake");
				// Assumes that RTS contains deviceId and appId
				function onJobReady(response) {
					console.log("----------> executed CB of getJob");
					if (response.error) {
						console.error("----------> Error : " + response.message);
						callback(response);
					}
					else {
						CommandsMgr.startReplay(true, callback);// In case of error the start replay will return object with error
					}
				}

				if (handshakeState.error) {
					console.error("----------> Error : " + handshakeState.message);
					callback && callback(handshakeState);
					return;
				}

				JobMgr.getJob(onJobReady);
			}

			ConnectionMgr.serverHandshake(false, onHandshakeComplete);
		},
		startReplay: function (keepAUTstate, callback) {
			AppMgr.launchApp(undefined, function (response) {
				console.log("----------> executed CB of launchApp");
				if (response.error) {
					console.error("----------> Error : " + response.message);
					callback && callback(response);
				} else {
					CommandsMgr._startReplay(true, callback);// In case of error the start replay will return object with error
				}
			});
		},
		_startReplay: function (keepAUTstate, callback) {
			console.log("----------> startReplay(keepAUTstate) - " + keepAUTstate);
			ConnectionMgr.sendToWS("startReplay", "mobile/replay-started", keepAUTstate, null, true, callback);
		},
		performStopReplay: function (callback) {
			console.log("----------> performStopReplay()");
			function onReplayStopped(replayStoppedArguments) {
				console.log("----------> executed CB of stopReplay");
				callback && callback(replayStoppedArguments);
			}

			CommandsMgr.stopReplay(onReplayStopped);
		},
		stopReplay: function (callback) {
			console.log("----------> stopReplay()");
			if (!CommonDetails.loggedIn) {
				callback && callback({error: true, message: CommonDetails.last.errorMessage});
				return;
			}
			var keepAUTState = true;
			ConnectionMgr.sendToWS("stopReplay", "mobile/replay-stopped", keepAUTState, null, true, callback);
		},
		executeStep: function (actionSection, testObj, targetTestObject, command, callback) {
			var contentExtension = {};
			if (actionSection) {
				console.log(actionSection);
				contentExtension.action = actionSection;
			}
			if (testObj && testObj.className != "Device") {
				console.log(testObj);
				contentExtension.application = {uuid: AppMgr.currApp.identifier};
			}
			if (testObj) {
				contentExtension.testObject = testObj;
			}
			if (targetTestObject) {
				contentExtension.targetTestObject = targetTestObject;
			}

			console.log("content: " + contentExtension);
			ConnectionMgr.sendToWS(command || "executeStep", "mobile/step-executed", false, contentExtension, false, callback);
		},
		findElementInPoint: function (point, callback) {
			var contentExt = {
				action: {
					"name": "findElement",
					"parameters": {
						"location": {
							"x": point.x,
							"y": point.y
						}
					}
				},
				application: {
					uuid: TC_NS.TCNMAppMgr.currApp.identifier
				}
			};
			ConnectionMgr.sendToWS("query", "mobile/find-element", true, contentExt, true, callback);
		},
		verifyElementExists: function (element, callback) {
			//create a copy with no boundsInScreen
			var obj = {};
			Object.extend(obj, element);
			delete obj.boundsInScreen;

			var contentExt = {
				action: {
					"name": "findElement",
					"parameters": obj
				},
				application: {
					uuid: AppMgr.currApp.identifier
				}
			};
			ConnectionMgr.sendToWS("query", "mobile/find-element", true, contentExt, true, callback);
		},
		updateRunTimeInfo: function () {
			// TC_NS.TCNMCommonDetails.metrics = {};
			// TC_NS.TCNMCommonDetails.metrics["cpu"] = TC_NS.RTS("memory");
			// TC_NS.TCNMCommonDetails.metrics["freeMemory"] = TC_NS.RTS("freeMemory");
			// TC_NS.TCNMCommonDetails.metrics["memory"] = TC_NS.RTS("memory");
		}
	};

})();


text:
using namespace Tizen::Base;
using namespace Tizen::Ui::Controls;
using namespace Tizen::Ui::Scenes;
using namespace Tizen::Graphics;
using namespace Tizen::Base::Collection;
using namespace consts;
using namespace bookmark;

BMCategoriesForm::BMCategoriesForm()
{
}

BMCategoriesForm::~BMCategoriesForm(void)
{
}

bool BMCategoriesForm::Initialize(void)
{
  Construct(IDF_BMCATEGORIES_FORM);
  return true;
}

result BMCategoriesForm::OnInitializing(void)
{
  m_bEditState = false;
  m_categoryToDelete = -1;

  ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW, true));
  pList->SetItemProvider(*this);
  pList->AddListViewItemEventListener(*this);

  GetHeader()->AddActionEventListener(*this);

  SetFormBackEventListener(this);
  UpdateState();
  return E_SUCCESS;
}

void BMCategoriesForm::OnActionPerformed(Tizen::Ui::Control const & source, int actionId)
{
  switch(actionId)
  {
    case ID_EDIT:
    {
      m_bEditState = !m_bEditState;
      m_categoryToDelete = -1;
      UpdateState();
      break;
    }
  }
  Invalidate(true);
}

void BMCategoriesForm::OnFormBackRequested(Tizen::Ui::Controls::Form & source)
{
  SceneManager * pSceneManager = SceneManager::GetInstance();
  pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));
}

ListItemBase * BMCategoriesForm::CreateItem (int index, float itemWidth)
{
  CustomItem * pItem = new CustomItem();

  BookMarkManager & mngr = GetBMManager();
  pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);

  int addWdth = 0;
  bool bShowDelete = index == m_categoryToDelete;
  if (m_bEditState)
  {
    FloatRectangle imgRect(btwWdth, topHght, imgWdth, imgHght);
    pItem->AddElement(imgRect, ID_DELETE, *GetBitmap(bShowDelete ? IDB_BOOKMARK_DELETE_CUR : IDB_BOOKMARK_DELETE), null, null);
    addWdth = btwWdth + imgWdth;
  }

  FloatRectangle imgRect(addWdth + btwWdth, topHght, imgWdth, imgHght);
  pItem->AddElement(imgRect, ID_EYE, *GetBitmap(mngr.IsCategoryVisible(index) ? IDB_EYE : IDB_EMPTY), null, null);
  int beg = addWdth + btwWdth + imgWdth + btwWdth;
  int end = 2 * btwWdth + (bShowDelete ? deleteWidth : imgWdth);
  String itemText = mngr.GetCategoryName(index);
  pItem->AddElement(FloatRectangle(beg, topHght, itemWidth - beg - end, imgHght), ID_NAME, itemText, mainFontSz, gray, gray, gray);
  if (bShowDelete)
  {
    pItem->AddElement(FloatRectangle(itemWidth - end + btwWdth, topHght, deleteWidth, imgHght), ID_DELETE_TXT, "Delete", mainFontSz, red, red, red);
  }
  else
  {
    int count = mngr.GetCategorySize(index);
    String sz;
    sz.Append(count);
    pItem->AddElement(FloatRectangle(itemWidth - btwWdth - imgWdth, topHght, imgWdth, imgHght), ID_SIZE, sz, mainFontSz, gray, gray, gray);
  }

  return pItem;
}

void BMCategoriesForm::OnListViewItemStateChanged(Tizen::Ui::Controls::ListView & listView, int index, int elementId, Tizen::Ui::Controls::ListItemStatus status)
{
  BookMarkManager & mngr = GetBMManager();
  if (elementId == ID_EYE)
  {
    bool bVisible = mngr.IsCategoryVisible(index);
    mngr.SetCategoryVisible(index, !bVisible);
  }
  if (elementId == ID_DELETE)
  {
    if (m_categoryToDelete == index)
      m_categoryToDelete = -1;
    else
      m_categoryToDelete = index;
  }
  if (elementId == ID_DELETE_TXT)
  {
    mngr.DeleteCategory(index);
    m_categoryToDelete = -1;
  }

  if (elementId == ID_NAME || elementId == ID_SIZE)
  {
    ArrayList * pList = new ArrayList;
    pList->Construct();
    pList->Add(new Integer(index));
    SceneManager * pSceneManager = SceneManager::GetInstance();
    pSceneManager->GoForward(ForwardSceneTransition(SCENE_CATEGORY,
        SCENE_TRANSITION_ANIMATION_TYPE_LEFT, SCENE_HISTORY_OPTION_ADD_HISTORY, SCENE_DESTROY_OPTION_DESTROY), pList);
    return;
  }
  UpdateState();
}

void BMCategoriesForm::UpdateState()
{
  ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW, true));
  pList->UpdateList();

  Header* pHeader = GetHeader();

  ButtonItem buttonItem;
  buttonItem.Construct(BUTTON_ITEM_STYLE_TEXT, ID_EDIT);
  buttonItem.SetText(m_bEditState ? GetString(IDS_DONE): GetString(IDS_EDIT));

  pHeader->SetButton(BUTTON_POSITION_RIGHT, buttonItem);
  Invalidate(true);
}

bool BMCategoriesForm::DeleteItem (int index, Tizen::Ui::Controls::ListItemBase * pItem, float itemWidth)
{
  delete pItem;
  return true;
}

int BMCategoriesForm::GetItemCount(void)
{
  return GetBMManager().GetCategoriesCount();
}


text:
module.exports.copyPairs = function(grunt, files, media) {
  media = media || ''
  var allSpecs = grunt.file.expand({cwd: media}, files)
  return allSpecs.map(function(relpath) {
    return {relpath: relpath, abspath: media + relpath}
  })
}

module.exports.specFiles = function(grunt, filename_regexp, media) {
  media = media || ''
  var allSpecs = grunt.file.expand({cwd: media}, [
    'pa/ammo/**/*.json',
    'pa/tools/**/*.json',
    'pa/units/**/*.json'
  ])
  var filter = new RegExp(filename_regexp, '')
  var specs = []
  allSpecs.forEach(function(relpath) {
    if (filter.test(relpath)) {
      specs.push({relpath: relpath, abspath: media + relpath})
    }
  })
  return specs
}

module.exports.copyUnitFiles = function(grunt, specs, processSpec) {
  processSpec = processSpec || function(x) {return x}
  specs.forEach(function(file) {
    var spec = grunt.file.readJSON(file.abspath)
    processSpec(spec)
    grunt.file.write(file.relpath, JSON.stringify(spec, null, 2))
  })
}


text:
'use strict'
let logger = require('@arve.knudsen/js-logger').get('client.ajax')
let S = require('underscore.string.fp')
let R = require('ramda')
let {notFoundError,} = require('../errors')

let {resolveWithResponse,} = require('../ajaxUtils')

module.exports = (absPath, method, payloadJson, options, resolve, reject) => {
  logger.debug(`Getting ${absPath}`)
  let request = new XMLHttpRequest()
  request.onreadystatechange = () => {
    if (request.readyState === XMLHttpRequest.DONE) {
      logger.debug('Received response from server:', request)
      if (request.status >= 200 && request.status < 300) {
        let headersStr = request.getAllResponseHeaders()
        let headers = R.fromPairs(
          R.map((headerStr) => {
            let matches = R.match(/(.+): (.+)/, headerStr)
            return [matches[1], matches[2],]
          }, S.wordsDelim('\n', headersStr))
        )
        let response = {
          headers,
        }
        resolveWithResponse(request.responseText, response, resolve, reject)
      } else {
        logger.debug(`Response was not successful: ${request.status}`)
        if (request.status === 404) {
          reject(notFoundError())
        } else {
          let result = new Error(!S.isBlank(request.responseText) ?
            JSON.parse(request.responseText).message : '')
          logger.debug(`Rejecting with:`, result)
          reject(result)
        }
      }
    }
  }

  request.open(method.toUpperCase(), absPath)
  let extendedHeaders = R.merge({
    'Content-Type': 'application/json;charset=UTF-8',
  }, options.headers || {})
  R.forEach(([key, value,]) => {
    request.setRequestHeader(key, value)
  }, R.toPairs(extendedHeaders))
  if (payloadJson != null) {
    logger.debug(`Sending JSON`)
  } else {
    logger.debug(`Not sending JSON`)
  }
  request.send(payloadJson)
}


text:
//
//  SkyS3ManagerSpec.m
//  S3SyncTests
//
//  Created by Eugene Dorfman on 1/3/15.
//
//

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <Kiwi/Kiwi.h>
#import <SkyS3Sync/SkyS3Sync.h>
#import <Nocilla/Nocilla.h>
#import "Functions.h"
#import <Ono/Ono.h>
#import <SkyS3Sync/SkyS3ResourceData.h>
#import <FileMD5Hash/FileHash.h>

void(*hit)(NSString *,void(^)(void)) = it;
//#define it(x,y)

@interface SkyS3SyncManager()
@property (nonatomic,assign) BOOL originalResourcesCopied;
@property (atomic,assign) BOOL syncInProgress;

- (void) doSync;
- (void) doOriginalResourcesCopying;
+ (NSDate *) modificationDateForURL:(NSURL *)URL;
- (NSArray *) remoteResourcesFromBucketListXML:(ONOXMLDocument *)document;
- (void) postDidRemoveNotificationWithResourceFileName:(NSString *)resourceFileName andURL:(NSURL *)resourceURL;
- (void) postDidUpdateNotificationWithResourceFileName:(NSString *)resourceFileName  andURL:(NSURL *)resourceURL;
- (void) postDidCopyOriginalNotificationWithResourceFileName:(NSString *)resource andURL:(NSURL *)resourceURL;
@end

SPEC_BEGIN(SkyS3SyncManagerSpec)
describe(@"SkyS3ManagerSpec", ^{

    //common variables:
    NSURL *documentsDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *originalResourcesDir = [documentsDir URLByAppendingPathComponent:@"test_dir"];
    NSURL *defaultSyncDir = [documentsDir URLByAppendingPathComponent:@"SkyS3Sync/"];

    __block SkyS3SyncManager *manager;

    beforeAll(^{
        [[LSNocilla sharedInstance] start];
    });

    afterAll(^{
        [[LSNocilla sharedInstance] stop];
    });

    void(^clearStubs)(void) = ^{
        [[LSNocilla sharedInstance] clearStubs];
    };

    afterEach(^{
        clearStubs();
        delete(defaultSyncDir);
        delete(originalResourcesDir);
    });

    void(^stub404)(void) = ^{
        stubRequest(@"GET", @".*".regex).
        andFailWithError([NSError errorWithDomain:@"'This is OK - deliberately done for tests'" code:404 userInfo:@{}]);
    };

    beforeEach(^{
        manager = [[SkyS3SyncManager alloc]initWithS3AccessKey:@"test_access_key" secretKey:@"test_secret_key" bucketName:@"test_bucket_name" originalResourcesDirectory:originalResourcesDir];

        delete(defaultSyncDir);
        delete(originalResourcesDir);

        createDir(originalResourcesDir);

        writeFile(@"test1",[originalResourcesDir URLByAppendingPathComponent:@"test1.txt"]);
        writeFile(@"test2",[originalResourcesDir URLByAppendingPathComponent:@"test2.txt"]);
        writeFile(@"test3",[originalResourcesDir URLByAppendingPathComponent:@"test3.txt"]);

        clearStubs();
    });

    it (@"should create the sync directory at default location", (^{
        stub404();

        [[theValue(manager.originalResourcesCopied) should] beNo];

        [manager sync];
        [NSThread sleepForTimeInterval:1];
        [[theValue(manager.originalResourcesCopied) shouldEventually] beYes];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        [[theValue([[NSFileManager defaultManager] fileExistsAtPath:[defaultSyncDir path]]) should] beYes];
    }));

    it (@"should create the sync directory at specified location", (^{
        stub404();

        NSString *different = @"DifferentSyncDir";
        NSURL *differentSyncDir = [documentsDir URLByAppendingPathComponent:different];
        [[theValue([[NSFileManager defaultManager] fileExistsAtPath:[differentSyncDir path]]) should] beNo];

        manager.syncDirectoryName = different;
        [[@(manager.originalResourcesCopied) should] beNo];
        [manager doSync];
        [[@(manager.originalResourcesCopied) should] beYes];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        [[@([[NSFileManager defaultManager] fileExistsAtPath:[differentSyncDir path]]) should] beYes];

        delete(differentSyncDir);
    }));

    it (@"should copy the resources into the sync directory at specified location", (^{
        stub404();
        NSArray *syncResources = contentsOfDirectory(defaultSyncDir);
        [syncResources shouldBeNil];

        [manager doSync];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        syncResources = contentsOfDirectory(defaultSyncDir);
        [syncResources shouldNotBeNil];
        NSArray *originalResources = contentsOfDirectory(originalResourcesDir);
        [[syncResources should] haveCountOf:[originalResources count]];
    }));

    it (@"should not copy the same resources if the sync resources content is the same as original, even if original ones are newer", (^{
        stub404();
        [manager doSync];//copy the resources ones
        [[expectFutureValue(theValue(manager.originalResourcesCopied)) shouldEventually] beYes];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSURL *test1URL = [originalResourcesDir URLByAppendingPathComponent:@"test1.txt"];
        NSDate *dateOriginal1 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [NSThread sleepForTimeInterval:1]; //needed spot that the dates are different

        writeFile(@"test1",test1URL);
        NSDate *dateOriginal2 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[dateOriginal2 shouldNot] equal:dateOriginal1];
        [[theValue([dateOriginal2 timeIntervalSinceDate:dateOriginal1]) should] beGreaterThan:theValue(0)];

        manager.originalResourcesCopied = NO;

        [[[NSNotificationCenter defaultCenter] should] receive:@selector(postNotificationName:object:) withArguments:SkyS3SyncDidFinishSyncNotification,manager,nil];
        [manager doSync];//copy the resources again
        [[expectFutureValue(theValue(manager.originalResourcesCopied)) shouldEventually] beYes];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSDate *dateSynced = [SkyS3SyncManager modificationDateForURL:[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]];

        [[dateOriginal1 should] equal:dateSynced];
    }));

    it (@"should copy the resources if the content has been modified and the modification date is either same or newer", (^{
        stub404();
        [manager doSync];

        NSURL *originalURL = [originalResourcesDir URLByAppendingPathComponent:@"test1.txt"];
        NSURL *syncedURL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];

        NSString *modifiedContent = @"test1_modified";
        NSString *syncedContent1 = readFile(syncedURL);
        NSString *originalContent = readFile(originalURL);
        [[syncedContent1 shouldNot] equal:modifiedContent];
        [[syncedContent1 should] equal:originalContent];

        writeFile(modifiedContent,originalURL);

        NSDate *dateOriginal2 = [SkyS3SyncManager modificationDateForURL:originalURL];

        manager.originalResourcesCopied = NO;
        [manager doSync];//copy the resources again
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSDate *dateSynced = [SkyS3SyncManager modificationDateForURL:syncedURL];
        [[dateSynced should] equal:dateOriginal2];

        NSString *syncedContent2 = readFile(syncedURL);
        [[syncedContent2 should] equal:modifiedContent];
    }));

    it (@"should not copy the resources if the content differs, but the modification date of the synced is newer than original", (^{
        stub404();
        [manager doSync];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];
        NSURL *originalURL = [originalResourcesDir URLByAppendingPathComponent:@"test1.txt"];
        NSURL *syncedURL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];

        NSDate *dateSynced1 = [SkyS3SyncManager modificationDateForURL:syncedURL];
        NSString *modifiedContent = @"test1_modified";

        NSString *originalContent = readFile(originalURL);
        NSString *syncedContent1 = readFile(syncedURL);

        [[originalContent should] equal:syncedContent1];
        [NSThread sleepForTimeInterval:1];

        writeFile(modifiedContent,syncedURL);
        manager.originalResourcesCopied = NO;
        [manager doSync];

        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSDate *dateSynced2 = [SkyS3SyncManager modificationDateForURL:syncedURL];
        NSString *syncedContent2 = readFile(syncedURL);

        [[theValue([dateSynced2 timeIntervalSinceDate:dateSynced1]) should] beGreaterThan:theValue(0)];
        [[syncedContent2 should] equal:modifiedContent];
    }));

    it (@"should copy the file from resources if it did not exist before in the sync directory", (^{
        stub404();
        [manager doSync];
        NSString *test4 = @"test4.txt";
        NSURL *test4URLOriginal = [originalResourcesDir URLByAppendingPathComponent:test4];
        writeFile(@"test4",test4URLOriginal);

        manager.originalResourcesCopied = NO;
        [manager doSync];

        NSURL *test4URLSync = [defaultSyncDir URLByAppendingPathComponent:test4];
        [[theValue([[NSFileManager defaultManager] fileExistsAtPath:[test4URLSync path]]) should] beYes];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        delete(test4URLOriginal);
        delete(test4URLSync);
    }));

    it (@"should get the remote resources from the Amazon S3 List Bucket xml", (^{
        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket" withExtension:@"xml"]
        ;
        NSError *error = nil;
        ONOXMLDocument *document = [ONOXMLDocument XMLDocumentWithString:readFile(xmlURL) encoding:NSUTF8StringEncoding error:&error];
        if (!document || error) {
            fail(@"failed to create XML document: %@",error);
        }

        NSArray *remoteResources = [manager remoteResourcesFromBucketListXML:document];
        [[remoteResources should] beNonNil];
        [[remoteResources should] haveCountOfAtLeast:1];

        SkyS3ResourceData *resource = [remoteResources firstObject];
        [[resource.etag should] beNonNil];
        [[resource.lastModifiedDate should] beNonNil];
        [[theValue([resource.lastModifiedDate timeIntervalSinceNow]) should] beGreaterThan:theValue(0)];
        [[resource.name should] equal:@"test1.txt"];
    }));

    it (@"should update the local resource if Amazon offers a newer resource with a different md5", (^{
        stub404();
        [[manager shouldEventually] receive:@selector(postDidCopyOriginalNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test1.txt",[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]];
        [[manager shouldEventually] receive:@selector(postDidUpdateNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test1.txt",[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]];

        [manager doSync]; //to copy test1
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];
        NSURL *test1URL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];
        NSDate *date1 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[date1 should] beNonNil];

        //stubbing requests:

        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket" withExtension:@"xml"]
        ;

        clearStubs();

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/test1.txt").
        andReturn(200).
        withHeader(@"Content-Type",@"text/plain").
        withBody(@"test1_amazon");

        [NSThread sleepForTimeInterval:1];//so that the updated resource is 1 second newer

        [[[NSNotificationCenter defaultCenter] should] receive:@selector(postNotificationName:object:) withArguments:SkyS3SyncDidFinishSyncNotification,manager,nil];
        [manager doSync];
        [[[FileHash md5HashOfFileAtPath:[test1URL path]] should] equal:@"5a105e8b9d40e1329780d62ea2265d8a"];
        [[expectFutureValue([FileHash md5HashOfFileAtPath:[test1URL path]]) shouldEventually] equal:@"d6df2932f01bdc0485ea502f86d10968"];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSDate *date2 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[theValue([date2 timeIntervalSinceDate:date1]) should] beGreaterThan:theValue(0)];
    }));

    it (@"should not update the local resource if Amazon offers a newer resource but with the same md5", (^{
        stub404();
        [manager doSync]; //to copy test1
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSURL *test1URL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];
        NSDate *date1 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[date1 should] beNonNil];

        //stubbing requests:
        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket-same-md5" withExtension:@"xml"]
        ;
        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        [NSThread sleepForTimeInterval:1]; //so that in case the resource updates it is 1 second newer

        [[[NSNotificationCenter defaultCenter] should] receive:@selector(postNotificationName:object:) withArguments:SkyS3SyncDidFinishSyncNotification,manager,nil];
        [manager doSync];
        [[[FileHash md5HashOfFileAtPath:[test1URL path]] should] equal:@"5a105e8b9d40e1329780d62ea2265d8a"];
        [[expectFutureValue([FileHash md5HashOfFileAtPath:[test1URL path]]) shouldEventually] equal:@"5a105e8b9d40e1329780d62ea2265d8a"];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];
        NSDate *date2 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[date2 should] equal:date1];
    }));

    it (@"should update the local resource if Amazon offers an older resource but with a different md5", (^{
        stub404();
        [manager doSync]; //to copy test1
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        NSURL *test1URL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];
        NSDate *date1 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[date1 should] beNonNil];

        //stubbing requests:
        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket-older-different-md5" withExtension:@"xml"]
        ;
        clearStubs();
        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/test1.txt").
        andReturn(200).
        withHeader(@"Content-Type",@"text/plain").
        withBody(@"test1_amazon");

        [NSThread sleepForTimeInterval:1]; //so that in case the resource updates it is 1 second newer

        [[[NSNotificationCenter defaultCenter] should] receive:@selector(postNotificationName:object:) withArguments:SkyS3SyncDidFinishSyncNotification,manager,nil];
        [manager doSync];
        [[[FileHash md5HashOfFileAtPath:[test1URL path]] should] equal:@"5a105e8b9d40e1329780d62ea2265d8a"];
        [[expectFutureValue([FileHash md5HashOfFileAtPath:[test1URL path]]) shouldEventually] equal:@"d6df2932f01bdc0485ea502f86d10968"];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];
        NSDate *date2 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[theValue([date2 timeIntervalSinceDate:date1]) should] beGreaterThan:theValue(0)];
    }));

    it (@"should download the resource from Amazon if it did not exist locally", (^{
        [[manager should] receive:@selector(postDidCopyOriginalNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test1.txt",[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]];
        [[manager should] receive:@selector(postDidUpdateNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test1.txt",[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]];
        [[manager should] receive:@selector(postDidUpdateNotificationWithResourceFileName:andURL:) withArguments:@"test4.txt",[defaultSyncDir URLByAppendingPathComponent:@"test4.txt"]];

        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket-test4" withExtension:@"xml"]
        ;

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/test1.txt").
        andReturn(200).
        withHeader(@"Content-Type",@"text/plain").
        withBody(@"test1_amazon");

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/test4.txt").
        andReturn(200).
        withHeader(@"Content-Type",@"text/plain").
        withBody(@"test4_amazon");

        NSURL *test1URL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];
        NSURL *test4URL = [defaultSyncDir URLByAppendingPathComponent:@"test4.txt"];

        NSURL *test1SyncURL = [[manager syncDirectory] URLForResource:@"test1" withExtension:@"txt"];
        [[test1SyncURL should] beNil];

        [[[NSNotificationCenter defaultCenter] should] receive:@selector(postNotificationName:object:) withArguments:SkyS3SyncDidFinishSyncNotification,manager,nil];
        manager.syncInProgress = YES;
        [manager doSync];
        [[[FileHash md5HashOfFileAtPath:[test1URL path]] should] equal:@"5a105e8b9d40e1329780d62ea2265d8a"];
        //first there is no test4:
        [[theValue([[NSFileManager defaultManager] fileExistsAtPath:[test4URL path]]) should] beNo];

        //downloading test1 update:
        [[expectFutureValue([FileHash md5HashOfFileAtPath:[test1URL path]]) shouldEventually] equal:@"d6df2932f01bdc0485ea502f86d10968"];

        //downloading test4 update:
        [[expectFutureValue(theValue([[NSFileManager defaultManager] fileExistsAtPath:[test4URL path]])) shouldEventually] beYes];
        [[expectFutureValue([FileHash md5HashOfFileAtPath:[test4URL path]]) shouldEventually] equal:@"919e96498e0dcc4eba488ee97cdd753b"];
        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];

        test1SyncURL = [[manager syncDirectory] URLForResource:@"test1" withExtension:@"txt"];
        [[test1SyncURL should] beNonNil];
        delete(test4URL);
    }));

    it(@"should not sync with Amazon if remoteSyncEnabled is set to NO", (^{
        [[[LSNocilla sharedInstance] shouldNot] receive:@selector(responseForRequest:)];
        manager.remoteSyncEnabled = NO;
        [manager doSync]; //to copy test1
        [[theValue(manager.syncInProgress) should] beYes];
        [NSThread sleepForTimeInterval:1]; //so that in case the resource updates it is 1 second newer

        [[expectFutureValue(theValue(manager.syncInProgress)) shouldEventually] beNo];
        NSURL *test1URL = [defaultSyncDir URLByAppendingPathComponent:@"test1.txt"];
        NSDate *date1 = [SkyS3SyncManager modificationDateForURL:test1URL];
        [[date1 should] beNonNil];
    }));

    it (@"should remove legacy local resources if it was removed from Amazon", (^{
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:)
                                                           withArguments:SkyS3SyncDidCopyOriginalResourceNotification,manager,@{SkyS3ResourceFileName:@"test1.txt",SkyS3ResourceURL:[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]},nil];
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:)
                                                           withArguments:SkyS3SyncDidUpdateResourceNotification,manager,@{SkyS3ResourceFileName:@"test1.txt",SkyS3ResourceURL:[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]},nil];
        [[manager should] receive:@selector(postDidCopyOriginalNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test2.txt",[defaultSyncDir URLByAppendingPathComponent:@"test2.txt"]]; // update only from original
        [[manager should] receive:@selector(postDidCopyOriginalNotificationWithResourceFileName:andURL:) withCount:1 arguments:@"test3.txt",[defaultSyncDir URLByAppendingPathComponent:@"test3.txt"]]; // update only from original
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:)
                                                               withArguments:SkyS3SyncDidRemoveResourceNotification,manager,@{SkyS3ResourceFileName:@"test2.txt",SkyS3ResourceURL:[defaultSyncDir URLByAppendingPathComponent:@"test2.txt"]},nil];
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:)
                                                               withArguments:SkyS3SyncDidRemoveResourceNotification,manager,@{SkyS3ResourceFileName:@"test3.txt",SkyS3ResourceURL:[defaultSyncDir URLByAppendingPathComponent:@"test3.txt"]},nil];

        manager.remoteSyncEnabled = NO;
        [manager doOriginalResourcesCopying];

        NSArray *syncResources = contentsOfDirectory(defaultSyncDir);
        [[syncResources should] haveCountOf:3];

        // stubbing requests:
        // whould be great to have response delay for this stubs,
        // so we could also test updates from original notifications with their userInfo dicts for deleted resources ('test2.txt' & 'test3.txt') the same way as we do for 'test1.txt'
        clearStubs();

        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket" withExtension:@"xml"];
        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/test1.txt").
        andReturn(200).
        withHeader(@"Content-Type",@"text/plain").
        withBody(@"test1_amazon");

        manager.remoteSyncEnabled = YES;
        [manager doSync];

        [NSThread sleepForTimeInterval:1];//so that the updated resource is 1 second newer

        syncResources = contentsOfDirectory(defaultSyncDir);
        [[syncResources should] haveCountOf:1];
        NSString* recoucePath = [(NSURL*)[syncResources firstObject] path];
        [[recoucePath should] endWithString:@"test1.txt"];

        // this files can still be accessed from the original resource directory
        NSURL* test2URL = [manager URLForResource:@"test2" withExtension:@"txt"];
        [[test2URL shouldNotAfterWait] beNil];
        NSURL* test3URL = [manager URLForResource:@"test3" withExtension:@"txt"];
        [[test3URL shouldNotAfterWait] beNil];

        //but should not be present in the syncDirectory
        test2URL = [[manager syncDirectory] URLForResource:@"test2" withExtension:@"txt"];
        [[test2URL shouldAfterWait] beNil];
        test3URL = [[manager syncDirectory] URLForResource:@"test3" withExtension:@"txt"];
        [[test3URL shouldAfterWait] beNil];
    }));

    it(@"should copy original resources just once, after that only update", (^{
        stub404();

        NSDictionary* userInfo = @{SkyS3ResourceFileName:@"test1.txt", SkyS3ResourceURL:[defaultSyncDir URLByAppendingPathComponent:@"test1.txt"]};
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:) withArguments:SkyS3SyncDidCopyOriginalResourceNotification,manager,userInfo,nil];
        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:) withArguments:SkyS3SyncDidUpdateResourceNotification,manager,userInfo,nil];
        [manager sync];//copy the resources once
        [NSThread sleepForTimeInterval:1];//needed spot that the dates are different
        writeFile(@"test1 updated",[originalResourcesDir URLByAppendingPathComponent:@"test1.txt"]);
        manager.originalResourcesCopied = NO;
        [manager doSync];//try to copy resources again, it would update already copied resources
    }));

    it(@"should return URLs within sync directory after original resource copying is finished", (^{
        //original resources copying should be on background thread, and should not happen faster
        //than the execution continues on the main thread
        manager.remoteSyncEnabled = NO;//do not sync with Amazon
        [manager sync];
        [NSThread sleepForTimeInterval:1];

        NSURL *test1URL = [manager URLForResource:@"test1" withExtension:@"txt"];
        [[theValue(manager.originalResourcesCopied) shouldEventually] beTrue]; //the resources should have not yet been copied

        NSURL *originalTest1URL = [defaultSyncDir  URLByAppendingPathComponent:@"test1.txt"];

        [[[test1URL absoluteString] should] equal:[originalTest1URL absoluteString]];
    }));

    it(@"should not crash when requesting URL for nil filename or ext", (^{
        NSURL *fileURL = [manager URLForResource:nil withExtension:nil];
        [[fileURL should] beNil];

        fileURL = [manager URLForResource:@"asdf" withExtension:nil];
        [[fileURL should] beNil];

        fileURL = [[manager syncDirectory] URLForResource:nil withExtension:nil];
        [[fileURL should] beNil];

        fileURL = [[manager syncDirectory] URLForResource:@"asdf" withExtension:nil];
        [[fileURL should] beNil];
    }));

    /** after updating to AFN v3 the error object becomes nested by NSURLSessionTask, so it's really hard to write a test case for it

    it(@"should send SkyS3SyncDidFailToListBucket when bucket list request fails", (^{
        NSString *URLString = @"https://test_bucket_name.s3.amazonaws.com/";
        NSURL *URL = [NSURL URLWithString:URLString];

        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:@{NSURLErrorFailingURLErrorKey:URL, NSURLErrorFailingURLStringErrorKey:URLString}];

        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:) withArguments:SkyS3SyncDidFailToListBucket,manager, @{SkyS3BucketName:@"test_bucket_name", SkyS3Error:error},nil];

        stubRequest(@"GET", URLString)
        .andFailWithError(error);
        [manager sync];
    }));

    it(@"should send SkyS3SyncDidFailToDownloadResource when resource download fails", (^{
        NSString *URLString = @"https://test_bucket_name.s3.amazonaws.com/test1.txt";
        NSURL *URL = [NSURL URLWithString:URLString];

        [[[NSNotificationCenter defaultCenter] shouldEventually] receive:@selector(postNotificationName:object:userInfo:) withArguments:SkyS3SyncDidFailToDownloadResource, manager, @{SkyS3ResourceFileName:@"test1.txt", SkyS3BucketName:@"test_bucket_name", SkyS3Error: [NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:@{NSURLErrorFailingURLStringErrorKey: URLString, NSURLErrorFailingURLErrorKey: URL}]},nil];

        NSURL *xmlURL = [[NSBundle bundleForClass:self.class] URLForResource:@"list-bucket" withExtension:@"xml"];

        stubRequest(@"GET", @"https://test_bucket_name.s3.amazonaws.com/").
        andReturn(200).
        withHeader(@"Content-Type",@"application/xml").
        withBody(readFile(xmlURL));

        stubRequest(@"GET", URLString).
        andFailWithError([NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:nil]);

        [manager sync];
    }));

     */
});

SPEC_END


text:
import React from 'react';
import links from '../constants/links';

const AboutUs = (props) => (

About Us Page

    Check us out on Github!

      This is a photo/bio pic container placeholder

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
      do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
      ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
      do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
      ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
      do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
      ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

);

export default AboutUs;


text:
(function() {
  var computedStore = new WeakMap();

  define('ember-macro-helpers/-computed-store', function() {
    return {
      'default': computedStore,
      __esModule: true
    };
  });

  var _computed = Ember.computed;

  // attempt to monkey patch before anything else runs
  Ember.computed = function computed() {
    var args = Array.prototype.slice.call(arguments);
    var cp = _computed.apply(this, args);
    var dependentKeys = args.slice(0, args.length - 1);
    var getter = args[args.length - 1];
    computedStore.set(cp, {
      dependentKeys: dependentKeys,
      getter: getter
    });
    return cp;
  };

  // support built-in macros
  Object.keys(_computed).forEach(function(_macro) {
    Ember.computed[_macro] = function macro() {
      var args = Array.prototype.slice.call(arguments);
      var cp = _computed[_macro].apply(this, args);
      var dependentKeys = args;
      var getter = cp._getter; // unfortunate private access (is there a better way?)
      computedStore.set(cp, {
        dependentKeys: dependentKeys,
        getter: getter
      });
      return cp;
    };
  });
})();


text:
var vows = require('vows');
var assert = require('assert');
var xmpp = require('node-xmpp');
var util = require('util');
var StanzaError = require('junction/stanzaerror');
var serviceDiscovery = require('junction/middleware/serviceDiscovery');

vows.describe('serviceDiscovery').addBatch({

  'with identities and features': {
    topic: function() {
      return serviceDiscovery([ { category: 'conference', type: 'text', name: 'Play-Specific Chatrooms' },
                                { category: 'directory', type: 'chatroom' } ],
                              [ 'http://jabber.org/protocol/disco#info',
                                'http://jabber.org/protocol/muc' ]);
    },

    'when handling a service discovery request': {
      topic: function(serviceDiscovery) {
        var self = this;
        var req = new xmpp.Stanza('iq', { type: 'get', to: 'plays.shakespeare.lit', from: 'romeo@montague.net/orchard', id: 'info1' });
        req.c('query', { xmlns: 'http://jabber.org/protocol/disco#info' }).up();
        var res = new xmpp.Stanza('iq', { id: req.attrs.id,
                                           to: req.attrs.from,
                                           type: 'result' });

        res.send = function() {
          self.callback(null, res);
        }
        function next(err) {
          self.callback(new Error('should not call next'));
        }
        process.nextTick(function () {
          serviceDiscovery(req, res, next)
        });
      },

      'should not call next' : function(err, stanza) {
        assert.isNull(err);
      },
      'should call send' : function(err, stanza) {
        assert.isNotNull(stanza);
      },
      'should send correct result' : function(err, stanza) {
        assert.equal(stanza.toString(), '<iq id="info1" to="romeo@montague.net/orchard" type="result"><query xmlns="http://jabber.org/protocol/disco#info"><identity category="conference" type="text" name="Play-Specific Chatrooms"/><identity category="directory" type="chatroom"/><feature var="http://jabber.org/protocol/disco#info"/><feature var="http://jabber.org/protocol/muc"/></query></iq>');
      },
    },

    'when handling a service discovery request to a node': {
      topic: function(serviceDiscovery) {
        var self = this;
        var req = new xmpp.Stanza('iq', { type: 'get', to: 'plays.shakespeare.lit', from: 'romeo@montague.net/orchard', id: 'info1' });
        req.c('query', { xmlns: 'http://jabber.org/protocol/disco#info', node: 'books' }).up();
        var res = new xmpp.Stanza('iq', { id: req.attrs.id,
                                           to: req.attrs.from,
                                           type: 'result' });

        res.send = function() {
          self.callback(new Error('should not call send'));
        }
        function next(err) {
          self.callback(err, req);
        }
        process.nextTick(function () {
          serviceDiscovery(req, res, next)
        });
      },

      'should indicate an error' : function(err, stanza) {
        assert.instanceOf(err, StanzaError);
        assert.equal(err.type, 'cancel');
        assert.equal(err.condition, 'item-not-found');
      },
    },

    'when handling a non-IQ-get service discovery request': {
      topic: function(serviceDiscovery) {
        var self = this;
        var req = new xmpp.Stanza('iq', { type: 'set', to: 'plays.shakespeare.lit', from: 'romeo@montague.net/orchard', id: 'info1' });
        req.c('query', { xmlns: 'http://jabber.org/protocol/disco#info' }).up();
        var res = new xmpp.Stanza('iq', { id: req.attrs.id,
                                           to: req.attrs.from,
                                           type: 'result' });

        res.send = function() {
          self.callback(new Error('should not call send'));
        }
        function next(err) {
          self.callback(err, req);
        }
        process.nextTick(function () {
          serviceDiscovery(req, res, next)
        });
      },

      'should indicate an error' : function(err, stanza) {
        assert.instanceOf(err, StanzaError);
        assert.equal(err.type, 'modify');
        assert.equal(err.condition, 'bad-request');
      },
    },

    'when handling an IQ stanza that is not a service discovery request': {
      topic: function(softwareVersion) {
        var self = this;
        var iq = new xmpp.Stanza('iq', { type: 'get', to: 'romeo@example.net', from: 'juliet@example.com' });
        var res = new xmpp.Stanza('iq', { id: iq.attrs.id,
                                           to: iq.attrs.from,
                                           type: 'result' });

        res.send = function() {
          self.callback(new Error('should not call send'));
        }
        function next(err) {
          self.callback(err, iq);
        }
        process.nextTick(function () {
          softwareVersion(iq, res, next)
        });
      },

      'should not call send' : function(err, stanza) {
        assert.isNull(err);
      },
      'should call next' : function(err, stanza) {
        assert.isNotNull(stanza);
      },
    },
  },

  'with identity and feature': {
    topic: function() {
      return serviceDiscovery({ category: 'client', type: 'pc' },
                              'http://jabber.org/protocol/disco#info');
    },

    'when handling a service discovery request': {
      topic: function(serviceDiscovery) {
        var self = this;
        var req = new xmpp.Stanza('iq', { type: 'get', to: 'plays.shakespeare.lit', from: 'romeo@montague.net/orchard', id: 'info1' });
        req.c('query', { xmlns: 'http://jabber.org/protocol/disco#info' }).up();
        var res = new xmpp.Stanza('iq', { id: req.attrs.id,
                                           to: req.attrs.from,
                                           type: 'result' });

        res.send = function() {
          self.callback(null, res);
        }
        function next(err) {
          self.callback(new Error('should not call next'));
        }
        process.nextTick(function () {
          serviceDiscovery(req, res, next)
        });
      },

      'should not call next' : function(err, stanza) {
        assert.isNull(err);
      },
      'should call send' : function(err, stanza) {
        assert.isNotNull(stanza);
      },
      'should send correct result' : function(err, stanza) {
        assert.equal(stanza.toString(), '<iq id="info1" to="romeo@montague.net/orchard" type="result"><query xmlns="http://jabber.org/protocol/disco#info"><identity category="client" type="pc"/><feature var="http://jabber.org/protocol/disco#info"/></query></iq>');
      },
    },
  },

}).export(module);


text:
This provides a Common Lisp implementation of SPNEGO authentication protocol, also known as Negotiate.
Essentially this is a wrapper around the NTLM and Kerberos protocols,
with an initial negotiation phase between client and server to decide which method can be used.

## 1. Introduction
The SPNEGO authentication system provides a pseduo-authentication system which resolves to either NTLM or Kerberos as
dictated by an initial negotiation phase between client and server. As a result, it can require multiple exhanges
before authentication completes. See rfc4178 for more information.

## 2. Usage
Use the various generic functions from [glass](https://github.com/fjames86/glass).

### 2.1 Client
The client calls are implemented and have been shown to work.

```
;; get a credential handle
(glass:acquire-credentials :spnego "service/host@DOMAIN.COM")

;; generate the initial buffer
(glass:initialize-security-context *creds*)

;; possibly feed the buffer back into the initial context (if several negotiation steps required)
(glass:initialize-security-context context :buffer buffer)
```

### 2.2 Server
The equivalent to the client calls, but with ACCEPT-SECURITY-CONTEXT.

```
;; get a credential handle
(glass:acquire-credentials :spnego nil)

;; accept an input buffer
(glass:accept-security-context creds buffer)

;; possibly generate another buffer if multiple steps required (mutual authentication)
(glass:accept-security-context context buffer)
```

## 3. Notes
The underlying NTLM and Kerberos implementations are [ntlm](https://github.com/fjames86/ntlm) and [cerberus](https://github.com/fjames86/cerberus). See those for more information in the relevant details.

## 4. License
Licensed under the terms of the MIT license.

Frank James
June 2015.


text:
package io.reactivex.internal.disposables;

import static org.junit.Assert.*;

import org.junit.Test;

import io.reactivex.TestHelper;
import io.reactivex.disposables.*;

public class ArrayCompositeDisposableTest {

    @Test
    public void normal() {
        ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2);

        Disposable d1 = Disposables.empty();
        Disposable d2 = Disposables.empty();

        assertTrue(acd.setResource(0, d1));
        assertTrue(acd.setResource(1, d2));

        Disposable d3 = Disposables.empty();
        Disposable d4 = Disposables.empty();

        acd.replaceResource(0, d3);
        acd.replaceResource(1, d4);

        assertFalse(d1.isDisposed());
        assertFalse(d2.isDisposed());

        acd.setResource(0, d1);
        acd.setResource(1, d2);

        assertTrue(d3.isDisposed());
        assertTrue(d4.isDisposed());

        assertFalse(acd.isDisposed());

        acd.dispose();
        acd.dispose();

        assertTrue(acd.isDisposed());

        assertTrue(d1.isDisposed());
        assertTrue(d2.isDisposed());

        Disposable d5 = Disposables.empty();
        Disposable d6 = Disposables.empty();

        assertFalse(acd.setResource(0, d5));
        acd.replaceResource(1, d6);

        assertTrue(d5.isDisposed());
        assertTrue(d6.isDisposed());
    }

    @Test
    public void disposeRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2);

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    acd.dispose();
                }
            };

            TestHelper.race(r, r);
        }
    }

    @Test
    public void replaceRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2);

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    acd.replaceResource(0, Disposables.empty());
                }
            };

            TestHelper.race(r, r);
        }
    }

    @Test
    public void setRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            final ArrayCompositeDisposable acd = new ArrayCompositeDisposable(2);

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    acd.setResource(0, Disposables.empty());
                }
            };

            TestHelper.race(r, r);
        }
    }

}


text:
using System;
using System.Drawing;
using System.Drawing.Imaging;

using OpenTK.Graphics.OpenGL;

namespace jam.source.gfx
{

    enum TextureWrapMode
    {
        Repeat = OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat,
        MirroredRepeat = OpenTK.Graphics.OpenGL.TextureWrapMode.MirroredRepeat,
        ClampToEdge = OpenTK.Graphics.OpenGL.TextureWrapMode.ClampToEdge,
        ClampToBorder = OpenTK.Graphics.OpenGL.TextureWrapMode.ClampToBorder
    }

    enum TextureFilterMode
    {
        Nearest,
        Linear,
        NearestMipmap,
        LinearMipmap
    }

    class Texture2D : IDisposable
    {

        public Texture2D(string path, TextureWrapMode wrapMode, TextureFilterMode filterMode)
        {

            texture = GL.GenTexture();

            Bitmap bitmap = new Bitmap(path);
            Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData bitmap_data = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            TextureMagFilter magFilter;
            TextureMinFilter minFilter;
            switch (filterMode)
            {
                case TextureFilterMode.Nearest:
                    magFilter = TextureMagFilter.Nearest;
                    minFilter = TextureMinFilter.Nearest;
                    break;
                case TextureFilterMode.Linear:
                    magFilter = TextureMagFilter.Linear;
                    minFilter = TextureMinFilter.Linear;
                    break;
                case TextureFilterMode.NearestMipmap:
                    magFilter = TextureMagFilter.Nearest;
                    minFilter = TextureMinFilter.NearestMipmapNearest;
                    break;
                case TextureFilterMode.LinearMipmap:
                    magFilter = TextureMagFilter.Linear;
                    minFilter = TextureMinFilter.LinearMipmapLinear;
                    break;
                default:
                    magFilter = TextureMagFilter.Nearest;
                    minFilter = TextureMinFilter.Nearest;
                    break;
            }

            Bind(0);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bitmap_data.Scan0);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)minFilter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)magFilter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)wrapMode);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)wrapMode);

            if (filterMode == TextureFilterMode.NearestMipmap ||
                filterMode == TextureFilterMode.LinearMipmap)
            {
                GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
            }

            Unbind(0);

            bitmap.UnlockBits(bitmap_data);

        }

        public Texture2D(string path, TextureFilterMode filterMode) :
            this(path, TextureWrapMode.ClampToBorder, filterMode)
        { }

        public Texture2D(string path) :
            this(path, TextureWrapMode.ClampToBorder, TextureFilterMode.Nearest)
        { }

        public void Bind(int unit)
        {
            GL.ActiveTexture(TextureUnit.Texture0 + unit);
            GL.BindTexture(TextureTarget.Texture2D, texture);
        }

        public void Unbind(int unit)
        {
            GL.ActiveTexture(TextureUnit.Texture0 + unit);
            GL.BindTexture(TextureTarget.Texture2D, 0);
        }

        public void Dispose()
        {
            GL.DeleteTexture(texture);
        }

        int texture;

    }

}


text:
var clickedLink;

$(function() {
  // add a hash to the URL when the user clicks on a tab
  $('a[data-toggle="tab"]').on('click', function(e) {
    history.pushState(null, null, $(this).attr('href'));
  });

  // when history changes
  window.addEventListener("popstate", function(e) {
    // when history changes and poped state is a state that come from ajax so reload the whole page
    if (e.state != null){
      if(e.state.hasOwnProperty('isAjax')){
        location.reload();
      }
    }
    // navigate to a tab when the history changes
    else{
      var activeTab = $('a[href="' + location.hash + '"]');
      if (activeTab.length) {
        activeTab.tab('show');
      } else {
        $('.nav-tabs a').first().tab('show');
      }
    }
  });
});

$(function() {
    var hash = window.location.hash;
    hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});

$(function() {
  $('form .show-preview').click(
    function() {
      var text = $(this).closest('form').find('textarea').val();
      form_parent = $(this).closest('form').parent().attr('id');
      $.ajax('/markdown/preview.js?source=' + encodeURIComponent(text) + '&form_parent=' + form_parent);
    });
});

$(function() {
  $('form .show-source').click(function(){
    setTimeout(
      function () {
        $('#preview-contents').addClass('hidden');
        $('#loading-spinner').removeClass('hidden');
      }, 200
    )
  });
});

// to add loader and opacity when ajax is start
$( document ).ajaxStart(function() {
  $("#content").css('opacity', '0.4');
  $( "#loader" ).show();

});

// to stop loader and remove opacity when ajax is stop
$( document ).ajaxStop(function() {
  $("#content").css('opacity', '');
  $( "#loader" ).hide();
});

// to get the link which will be used in ajax case for pushState
$(document).on("click", "a", function(){
  clickedLink = this.href;
})

$(function(){
  var emojis = [
    "smile", "iphone", "girl", "smiley", "heart", "kiss", "copyright", "coffee",
    "a", "ab", "airplane", "alien", "ambulance", "angel", "anger", "angry",
    "arrow_forward", "arrow_left", "arrow_lower_left", "arrow_lower_right",
    "arrow_right", "arrow_up", "arrow_upper_left", "arrow_upper_right",
    "art", "astonished", "atm", "b", "baby", "baby_chick", "baby_symbol",
    "balloon", "bamboo", "bank", "barber", "baseball", "basketball", "bath",
    "bear", "beer", "beers", "beginner", "bell", "bento", "bike", "bikini",
    "bird", "birthday", "black_square", "blue_car", "blue_heart", "blush",
    "boar", "boat", "bomb", "book", "boot", "bouquet", "bow", "bowtie",
    "boy", "bread", "briefcase", "broken_heart", "bug", "bulb",
    "person_with_blond_hair", "phone", "pig", "pill", "pisces", "plus1",
    "point_down", "point_left", "point_right", "point_up", "point_up_2",
    "police_car", "poop", "post_office", "postbox", "pray", "princess",
    "punch", "purple_heart", "question", "rabbit", "racehorse", "radio",
    "up", "us", "v", "vhs", "vibration_mode", "virgo", "vs", "walking",
    "warning", "watermelon", "wave", "wc", "wedding", "whale", "wheelchair",
    "white_square", "wind_chime", "wink", "wink2", "wolf", "woman",
    "womans_hat", "womens", "x", "yellow_heart", "zap", "zzz", "+1",
    "-1"
  ];
  var emojis = $.map(emojis, function(value, i) {return {key: value, name:value}});
  var emoji_config = {
    at: ":",
    data: emojis,
    displayTpl: "
${name}
",
    insertTpl: ':${key}:',
    delay: 400
  }
  $('textarea').atwho(emoji_config);
});

function textcover(txtarea, newtxt) {
  $(txtarea).val(
        $(txtarea).val().substring(0, txtarea.selectionStart)+
        newtxt +
        $(txtarea).val().substring(txtarea.selectionStart,txtarea.selectionEnd)+
        newtxt +
        $(txtarea).val().substring(txtarea.selectionEnd)
   );
}

$(document).on('click', '.show-preview, .show-source', function (e) {
  $(this).parent().next('.btnbar').toggle();
})


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
	<!-- Theme Styles -->
    <style name="Theme">
		<item name="spinnerStyle">@android:style/Widget.Spinner</item>
		<item name="dropDownSpinnerStyle">@style/Widget.Spinner.DropDown</item>
	</style>
	<style name="Theme.Holo">
        <item name="spinnerStyle">?android:attr/dropDownSpinnerStyle</item>
		<item name="dropDownSpinnerStyle">@style/Widget.Holo.Spinner.DropDown</item>
	</style>

	<style name="Theme.Holo.Light" parent="@android:style/Theme.Light">
		<item name="spinnerStyle">?android:attr/dropDownSpinnerStyle</item>
		<item name="dropDownSpinnerStyle">@style/Widget.Holo.Light.Spinner.DropDown</item>
	</style>

	<!-- Widget Styles -->

	<style name="Widget">
        <item name="android:textAppearance">?android:textAppearance</item>
        <item name="android:paddingLeft">10dip</item>
        <item name="android:gravity">center</item>
    </style>

	<style name="Widget.Spinner">
        <item name="android:background">@android:drawable/btn_dropdown</item>
        <item name="android:clickable">true</item>
        <item name="android:spinnerMode">dialog</item>
        <item name="android:dropDownSelector">@drawable/list_selector_background</item>
        <item name="android:popupBackground">@drawable/spinner_dropdown_background</item>
        <item name="android:dropDownVerticalOffset">-10dip</item>
        <item name="android:dropDownHorizontalOffset">0dip</item>
        <item name="android:dropDownWidth">wrap_content</item>
<!--         <item name="android:popupPromptView">@android:layout/simple_dropdown_hint</item> -->
        <item name="android:gravity">center</item>
    </style>

	<style name="Widget.Spinner.DropDown">
        <item name="android:spinnerMode">dropdown</item>
    </style>

	<style name="Widget.Holo.Spinner" parent="Widget.Spinner.DropDown">
        <item name="android:background">@drawable/spinner_background_holo_dark</item>
        <item name="android:dropDownSelector">@drawable/list_selector_holo_dark</item>
<!--         <item name="android:popupBackground">@android:drawable/menu_dropdown_panel_holo_dark</item> -->
        <item name="android:dropDownVerticalOffset">0dip</item>
        <item name="android:dropDownHorizontalOffset">0dip</item>
        <item name="android:dropDownWidth">wrap_content</item>
<!--         <item name="android:popupPromptView">@android:layout/simple_dropdown_hint</item> -->
        <item name="android:gravity">left|center_vertical</item>
<!--         <item name="android:disableChildrenWhenDisabled">true</item> -->
    </style>

	<style name="Widget.Holo.Light.Spinner" parent="Widget.Holo.Spinner">
        <item name="android:background">@drawable/spinner_background_holo_light</item>
        <item name="android:dropDownSelector">@drawable/list_selector_holo_light</item>
<!--         <item name="android:popupBackground">@android:drawable/menu_dropdown_panel_holo_light</item> -->
        <item name="android:dropDownVerticalOffset">0dip</item>
        <item name="android:dropDownHorizontalOffset">0dip</item>
        <item name="android:dropDownWidth">wrap_content</item>
<!--         <item name="android:popupPromptView">@android:layout/simple_dropdown_hint</item> -->
    </style>

    <style name="Widget.Holo.Spinner.DropDown">
    </style>
    <style name="Widget.Holo.Light.Spinner.DropDown">
    </style>
</resources>


text:
package com.space.invaders.modelos;

import java.util.ArrayList;
import java.util.List;
import com.space.invaders.entidades.Nivel;
import com.space.invaders.entidades.iterador.IteradorGenerico;
import com.space.invaders.entidades.iterador.IteradorListaGenerica;

/**
 * Modelo para los niveles del juego.
 */
public class ModeloNivel {

	/**
	 * Niveles del juego.
	 */
	private List<Nivel> niveles;

	private IteradorGenerico<Nivel> iteradorNiveles;

	/**
	 * Nivel actual.
	 */
	private Nivel nivelActual;

	/**
	 * Crea una nueva instancia del modelo de nivel.
	 */
	public 	ModeloNivel() {
		cargarNiveles();
		crearIteradorNiveles();
	}

	private void crearIteradorNiveles(){
		iteradorNiveles = new IteradorListaGenerica<Nivel>(niveles);
	}

	/**
	 * Carga los niveles configurados en el juego.
	 */
	private void cargarNiveles() {

		niveles = new ArrayList<Nivel>();
		Nivel nivel = new Nivel();
		nivel.setNombre("Lets kill some aliens!  ;)");
		nivel.setNumero(1);
		nivel.setVelocidadEnemigos(1f);
		nivel.setVelocidadJugador(5f);
		nivel.setVelocidadDisparosEnemigos(2.5f);
		nivel.setVelocidadDisparosJugador(5);
		nivel.getConfiguracionEnemigos().put(0, 10);
		nivel.getConfiguracionEnemigos().put(1, 10);
		nivel.getConfiguracionEnemigos().put(2, 10);
		nivel.setCantidadEnemigosPorFila(10);
		nivel.setFrecuenciaDisparosEnemigos(1);

		niveles.add(nivel);

		nivel = new Nivel();
		nivel.setNombre("It's getting complicated!  :o");
		nivel.setNumero(2);
		nivel.setVelocidadEnemigos(3);
		nivel.setVelocidadJugador(6);
		nivel.setVelocidadDisparosEnemigos(4);
		nivel.setVelocidadDisparosJugador(8);
		nivel.getConfiguracionEnemigos().put(0, 10);
		nivel.getConfiguracionEnemigos().put(1, 20);
		nivel.getConfiguracionEnemigos().put(2, 10);
		nivel.setCantidadEnemigosPorFila(10);
		nivel.setFrecuenciaDisparosEnemigos(0.75f);

		niveles.add(nivel);

		nivel = new Nivel();
		nivel.setNombre("This is the end!  X(");
		nivel.setNumero(3);
		nivel.setVelocidadEnemigos(5);
		nivel.setVelocidadJugador(7.5f);
		nivel.setVelocidadDisparosEnemigos(8);
		nivel.setVelocidadDisparosJugador(16);
		nivel.getConfiguracionEnemigos().put(0, 15);
		nivel.getConfiguracionEnemigos().put(1, 30);
		nivel.getConfiguracionEnemigos().put(2, 15);
		nivel.setCantidadEnemigosPorFila(15);
		nivel.setFrecuenciaDisparosEnemigos(0.5f);

		niveles.add(nivel);

		nivel = new Nivel();
		nivel.setNombre("Hardcore mode!");
		nivel.setNumero(4);
		nivel.setVelocidadEnemigos(7.5f);
		nivel.setVelocidadJugador(10f);
		nivel.setVelocidadDisparosEnemigos(10);
		nivel.setVelocidadDisparosJugador(20);
		nivel.getConfiguracionEnemigos().put(0, 20);
		nivel.getConfiguracionEnemigos().put(1, 40);
		nivel.getConfiguracionEnemigos().put(2, 20);
		nivel.setCantidadEnemigosPorFila(20);
		nivel.setFrecuenciaDisparosEnemigos(0.2f);

		niveles.add(nivel);
	}

	/**
	 * Obtiene los niveles del juego.
	 * @return Niveles.
	 */
	public List<Nivel> getNiveles() {
		return niveles;
	}

	/**
	 * Asigna la lista de niveles del juego.
	 * @param niveles Niveles.
	 */
	public void setNiveles(List<Nivel> niveles) {
		this.niveles = niveles;
	}

	/**
	 * Obtiene el nivel en el indice dado.
	 * @param numeroNivel Indice nivel.
	 * @return Nivel.
	 */
	public Nivel getNivel(int indiceNivel) {
		return this.niveles.get(indiceNivel);
	}

	/**
	 * Obtiene el siguiente nivel.
	 * @return Nivel
	 */
	public Nivel getSiguienteNivel() {
		nivelActual = iteradorNiveles.next();
		return nivelActual;
	}

	/**
	 * Obtiene el primer nivel.
	 * @return
	 */
	public Nivel getPrimerNivel() {
		crearIteradorNiveles();
		Nivel primerNivel = getSiguienteNivel();
		return primerNivel;
	}

	/**
	 * Obtiene el nivel actual.
	 * @return Nivel actual.
	 */
	public Nivel getNivelActual() {
		return nivelActual;
	}

	/**
	 * Valida si el nivel actual es el ultimo nivel.
	 * @return Retorna true si el nivel actual es el ultimo nivel; de lo contrario retorna false.
	 */
	public boolean esUltimoNivel() {
		boolean esUltimoNivel = !iteradorNiveles.hasNext();
		return esUltimoNivel;
	}
}


text:
namespace at {

// Returns true if size represents an "no element" or "empty" tensor.
// See Note [empty versus 0-dim tensors]
static inline bool is_noelem_tensor_size(ArrayRef<int64_t> size) {
  return size.size() == 1 && size[0] == 0;
}

// make a fake storage out of a size, pointer pair...
// used as an argument where THSize and THStride are passed into TH
class THLongStorageView {
public:
  static THLongStorageView makeFromSize(ArrayRef<int64_t> ref) {
    return THLongStorageView(ref, true, false, false);
  }
  // noelem_to_empty is to differentiate strides of empty tensors vs scalars.  In ATen, both may have strides [1],
  // but in TH an empty tensor should have stride [], while a scalar should have stride [1].
  static THLongStorageView makeFromStride(ArrayRef<int64_t> ref, bool noelem_to_empty) {
    return THLongStorageView(ref, false, true, noelem_to_empty);
  }
  static THLongStorageView makeFromLength(ArrayRef<int64_t> ref) {
    return THLongStorageView(ref, false, false, false);
  }
  operator THLongStorage*() {
    if (storage.size == 0 && zero_dim_to_null) {
      return nullptr;
    }
    return &storage;
  }
private:
  // zero_dim_to_one converts an empty ArrayRef into [1]
  // zero_dim_to_null converts an empty ArrayRef into a null THLongStorage
  // noelem_to_empty makes an ArrayRef of [0] into an empty THLongStorage
  THLongStorageView(ArrayRef<int64_t> ref, bool zero_dim_to_one, bool zero_dim_to_null, bool noelem_to_empty)
    : zero_dim_to_null(zero_dim_to_null)
  {
    if(zero_dim_to_one && ref.size() == 0) {
      // make storage of size 0 actually a 1-length storage with 1 element
      // so that our 0-dim tensors get allocated as 1-dim inside TH
      one = 1;
      storage.data = &one;
      storage.size = 1;
    } else if (noelem_to_empty && is_noelem_tensor_size(ref)) {
      storage.data = (int64_t*)(ref.data());
      storage.size = 0;
    }
    else {
      storage.data = (int64_t*)(ref.data());
      storage.size = ref.size();
    }
    storage.refcount = 0;
    storage.flag = 0;
    storage.allocator = nullptr;
    storage.allocatorContext = nullptr;
  }
  int64_t one;
  THLongStorage storage;
  bool zero_dim_to_null;
};

}