text:
using sync_datatype_helper::test;

namespace printers_helper {

namespace {

using PrinterList = std::vector<chromeos::Printer>;

// Returns true if Printer#id, Printer#description, and Printer#uri all match.
bool PrintersAreMostlyEqual(const chromeos::Printer& left,
                            const chromeos::Printer& right) {
  return left.id() == right.id() && left.description() == right.description() &&
         left.uri() == right.uri();
}

// Returns true if both lists have the same elements irrespective of order.
bool ListsContainTheSamePrinters(const PrinterList& list_a,
                                 const PrinterList& list_b) {
  std::unordered_multimap<std::string, const chromeos::Printer*> map_b;
  for (const auto& b : list_b) {
    map_b.insert({b.id(), &b});
  }

  for (const auto& a : list_a) {
    auto range = map_b.equal_range(a.id());

    auto it = std::find_if(
        range.first, range.second,
        [&a](const std::pair<std::string, const chromeos::Printer*>& entry)
            -> bool { return PrintersAreMostlyEqual(a, *(entry.second)); });

    if (it == range.second) {
      // Element in a does not match an element in b. Lists do not contain the
      // same elements.
      return false;
    }

    map_b.erase(it);
  }

  return map_b.empty();
}

std::string PrinterId(int index) {
  return base::StringPrintf("printer%d", index);
}

chromeos::SyncedPrintersManager* GetPrinterStore(
    content::BrowserContext* context) {
  return chromeos::SyncedPrintersManagerFactory::GetForBrowserContext(context);
}

}  // namespace

void AddPrinter(chromeos::SyncedPrintersManager* manager,
                const chromeos::Printer& printer) {
  manager->UpdateSavedPrinter(printer);
}

void RemovePrinter(chromeos::SyncedPrintersManager* manager, int index) {
  chromeos::Printer testPrinter(CreateTestPrinter(index));
  manager->RemoveSavedPrinter(testPrinter.id());
}

bool EditPrinterDescription(chromeos::SyncedPrintersManager* manager,
                            int index,
                            const std::string& description) {
  PrinterList printers = manager->GetSavedPrinters();
  std::string printer_id = PrinterId(index);
  auto found =
      std::find_if(printers.begin(), printers.end(),
                   [&printer_id](const chromeos::Printer& printer) -> bool {
                     return printer.id() == printer_id;
                   });

  if (found == printers.end())
    return false;

  found->set_description(description);
  manager->UpdateSavedPrinter(*found);

  return true;
}

chromeos::Printer CreateTestPrinter(int index) {
  chromeos::Printer printer(PrinterId(index));
  printer.set_description("Description");
  printer.set_uri(base::StringPrintf("ipp://192.168.1.%d", index));

  return printer;
}

std::unique_ptr<sync_pb::PrinterSpecifics> CreateTestPrinterSpecifics(
    int index) {
  auto specifics = std::make_unique<sync_pb::PrinterSpecifics>();
  specifics->set_id(PrinterId(index));
  specifics->set_description("Description");
  specifics->set_uri(base::StringPrintf("ipp://192.168.1.%d", index));

  return specifics;
}

void WaitForPrinterStoreToLoad(content::BrowserContext* context) {
  GetPrinterStore(context);
  // Run tasks to allow a ModelTypeStore to be associated with the
  // SyncedPrinterManager.
  //
  // TODO(sync): Remove this forced initialization once there is a mechanism
  // to queue writes/reads before the ModelTypeStore is associated with the
  // SyncedPrinterManager. https://crbug.com/709094.
  content::RunAllTasksUntilIdle();
}

chromeos::SyncedPrintersManager* GetVerifierPrinterStore() {
  chromeos::SyncedPrintersManager* manager =
      GetPrinterStore(sync_datatype_helper::test()->verifier());

  return manager;
}

chromeos::SyncedPrintersManager* GetPrinterStore(int index) {
  chromeos::SyncedPrintersManager* manager =
      GetPrinterStore(sync_datatype_helper::test()->GetProfile(index));

  return manager;
}

int GetVerifierPrinterCount() {
  return GetVerifierPrinterStore()->GetSavedPrinters().size();
}

int GetPrinterCount(int index) {
  return GetPrinterStore(index)->GetSavedPrinters().size();
}

bool AllProfilesContainSamePrinters() {
  auto reference_printers = GetPrinterStore(0)->GetSavedPrinters();
  for (int i = 1; i < test()->num_clients(); ++i) {
    auto printers = GetPrinterStore(i)->GetSavedPrinters();
    if (!ListsContainTheSamePrinters(reference_printers, printers)) {
      VLOG(1) << "Printers in client [" << i << "] don't match client 0";
      return false;
    }
  }

  return true;
}

bool ProfileContainsSamePrintersAsVerifier(int index) {
  return ListsContainTheSamePrinters(
      GetVerifierPrinterStore()->GetSavedPrinters(),
      GetPrinterStore(index)->GetSavedPrinters());
}

PrintersMatchChecker::PrintersMatchChecker()
    : AwaitMatchStatusChangeChecker(
          base::Bind(&printers_helper::AllProfilesContainSamePrinters),
          "All printers match") {}

PrintersMatchChecker::~PrintersMatchChecker() {}

}  // namespace printers_helper


text:
package commands

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/nanopack/mist/clients"
)

var (

	// alias for publish
	messageCmd = &cobra.Command{
		Hidden: true,

		Use:           "message",
		Short:         "Publish a message",
		Long:          ``,
		SilenceErrors: true,
		SilenceUsage:  true,

		RunE: publish,
	}

	publishCmd = &cobra.Command{
		Use:           "publish",
		Short:         "Publish a message",
		Long:          ``,
		SilenceErrors: true,
		SilenceUsage:  true,

		RunE: publish,
	}

	// alias for publish
	sendCmd = &cobra.Command{
		Hidden: true,

		Use:           "send",
		Short:         "Publish a message",
		Long:          ``,
		SilenceErrors: true,
		SilenceUsage:  true,

		RunE: publish,
	}
)

var data string

// init
func init() {
	publishCmd.Flags().StringVar(&host, "host", host, "The IP of a running mist server to connect to")
	messageCmd.Flags().StringVar(&host, "host", host, "The IP of a running mist server to connect to")
	sendCmd.Flags().StringVar(&host, "host", host, "The IP of a running mist server to connect to")

	publishCmd.Flags().StringVar(&data, "data", data, "The string data to publish")
	messageCmd.Flags().StringVar(&data, "data", data, "The string data to message")
	sendCmd.Flags().StringVar(&data, "data", data, "The string data to send")

	publishCmd.Flags().StringSliceVar(&tags, "tags", tags, "Tags to publish to")
	messageCmd.Flags().StringSliceVar(&tags, "tags", tags, "Tags to publish to")
	sendCmd.Flags().StringSliceVar(&tags, "tags", tags, "Tags to publish to")
}

// publish
func publish(ccmd *cobra.Command, args []string) error {

	// missing tags
	if tags == nil {
		fmt.Println("Unable to publish - Missing tags")
		return fmt.Errorf("")
	}

	// missing data
	if data == "" {
		fmt.Println("Unable to publish - Missing data")
		return fmt.Errorf("")
	}

	client, err := clients.New(host, viper.GetString("token"))
	if err != nil {
		fmt.Printf("Failed to connect to '%s' - %s\n", host, err.Error())
		return err
	}

	err = client.Publish(tags, data)
	if err != nil {
		fmt.Printf("Failed to publish message - %s\n", err.Error())
		return err
	}

	fmt.Println("success")

	return nil
}

redpajama_set_name: RedPajamaGithub


text:
// const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common");
// const { RootActor } = require("devtools/server/actors/root");
// const { ThreadActor } = require("devtools/server/actors/script");
// const { DebuggerServer } = require("devtools/server/main");
// const { TabSources } = require("devtools/server/actors/utils/TabSources");
// const promise = require("promise");
// const makeDebugger = require("devtools/server/actors/utils/make-debugger");

let gTestGlobals = [];
let needToSendNavigation = false;
let testTab = null;

// A mock tab list, for use by tests. This simply presents each global in
// gTestGlobals as a tab, and the list is fixed: it never calls its
// onListChanged handler.
//
// As implemented now, we consult gTestGlobals when we're constructed, not
// when we're iterated over, so tests have to add their globals before the
// root actor is created.
function TestTabList(aConnection) {
  this.conn = aConnection;

  // An array of actors for each global added with
  // DebuggerServer.addTestGlobal.
  this._tabActors = [];

  // A pool mapping those actors' names to the actors.
  this._tabActorPool = new ActorPool(aConnection);

  for (let global of gTestGlobals) {
    let actor = new TestTabActor(aConnection, global);
    testTab = actor;
    actor.selected = false;
    this._tabActors.push(actor);
    this._tabActorPool.addActor(actor);
  }
  if (this._tabActors.length > 0) {
    this._tabActors[0].selected = true;
  }

  aConnection.addActorPool(this._tabActorPool);
}

TestTabList.prototype = {
  constructor: TestTabList,
  getList: function () {
    return resolve([...this._tabActors]);
  }
};

function createRootActor(aConnection)
{
  let root = new RootActor(aConnection, {
    tabList: new TestTabList(aConnection),
    globalActorFactories: DebuggerServer.globalActorFactories,
  });

  // root.applicationType = "xpcshell-tests";
  return root;
}

function TestTabActor(aConnection, aGlobal)
{
  this.makeDebugger = function() {
    let dbg = new Debugger();
    dbg.addDebuggee(this._global);
    return dbg;
  };

  this.conn = aConnection;
  this._global = aGlobal;
  this._global.wrappedJSObject = aGlobal;
  this.threadActor = new ThreadActor(this, this._global);
  this.conn.addActor(this.threadActor);
  this.consoleActor = new WebConsoleActor(this.conn, this);
  this.conn.addActor(this.consoleActor);
  this._attached = false;
  this._extraActors = {};
  // this.makeDebugger = makeDebugger.bind(null, {
  //   findDebuggees: () => [this._global],
  //   shouldAddNewGlobalAsDebuggee: g => g.hostAnnotations &&
  //                                      g.hostAnnotations.type == "document" &&
  //                                      g.hostAnnotations.element === this._global

  // });
}

TestTabActor.prototype = {
  constructor: TestTabActor,
  actorPrefix: "TestTabActor",

  get window() {
    return this._global;
  },

  get url() {
    // return "http://cocos2d-x.org";
    return "about:cehome";
  },

  get sources() {
    if (!this._sources) {
      this._sources = new TabSources(this.threadActor);
    }
    return this._sources;
  },

  form: function() {
    let response = { actor: this.actorID, title: "cocos project", 'consoleActor': this.consoleActor.actorID };

    // Walk over tab actors added by extensions and add them to a new ActorPool.
    let actorPool = new ActorPool(this.conn);
    // this._createExtraActors(DebuggerServer.tabActorFactories, actorPool);
    if (!actorPool.isEmpty()) {
      this._tabActorPool = actorPool;
      this.conn.addActorPool(this._tabActorPool);
    }

    // this._appendExtraActors(response);

    return response;
  },

  onAttach: function(aRequest) {
    this._attached = true;

    let response = { type: "tabAttached", threadActor: this.threadActor.actorID};
    // this._appendExtraActors(response);

    return response;
  },

  onDetach: function(aRequest) {
    if (!this._attached) {
      return { "error":"wrongState" };
    }
    return { type: "detached" };
  },

  onReload: function(aRequest) {
    this.sources.reset({ sourceMaps: true });
    this.threadActor.clearDebuggees();
    this.threadActor.dbg.addDebuggees();
    return {};
  },

  removeActorByName: function(aName) {
    const actor = this._extraActors[aName];
    if (this._tabActorPool) {
      this._tabActorPool.removeActor(actor);
    }
    delete this._extraActors[aName];
  },

  /* Support for DebuggerServer.addTabActor. */
  // _createExtraActors: createExtraActors,
  // _appendExtraActors: appendExtraActors
};

TestTabActor.prototype.requestTypes = {
  "attach": TestTabActor.prototype.onAttach,
  "detach": TestTabActor.prototype.onDetach,
  "reload": TestTabActor.prototype.onReload
};

let conn = null;
let transport = null;

let incomingData = '';

this.processInput = function (inputstr) {
    if (!inputstr) {

      return;
    }

    if (inputstr === "connected")
    {
    	DebuggerServer.init();
      DebuggerServer.setRootActor(createRootActor);
      conn = DebuggerServer._onConnection(transport);

      return;
    }

    function extractPacket(inputString) {
      // Well this is ugly.
      let sep = inputString.indexOf(':');
      if (sep < 0) {
        return null;
      }

      let count = inputString.substring(0, sep);
      // Check for a positive number with no garbage afterwards.
      if (!/^[0-9]+$/.exec(count)) {
        return null;
      }

      count = +count;
      if (inputString.length - (sep + 1) < count) {
        // Don't have a complete request yet.
        return null;
      }

      // We have a complete request, pluck it out of the data and parse it.
      inputString = inputString.substring(sep + 1);
      let packet = inputString.substring(0, count);
      incomingData = inputString.substring(count);

      return packet;
    }

    function handlePacket(packet) {
      try {
        // packet = this._converter.ConvertToUnicode(packet);
        packet = DevToolsUtils.utf8to16(packet);
        var parsed = JSON.parse(packet);
        conn.onPacket(parsed);
      } catch(e) {
        let msg = "Error parsing incoming packet: " + packet + " (" + e + " - " + e.stack + ")";
      }
    }

    incomingData += inputstr;
    var packet;
    while (packet = extractPacket(incomingData)) {
      handlePacket(packet);
    }
};

this._prepareDebugger = function (global) {

    this.globalDebuggee = global;
    cc = global.cc;
    // exports = global;
    // load all functions exported in DevToolsUtils to global(exports)
    require('script/debugger/DevToolsUtils.js', 'debug');
    require('script/debugger/event-emitter.js', 'debug');
    require('script/debugger/actors/utils/ScriptStore.js', 'debug');
    require('script/debugger/actors/common.js', 'debug');
    require('script/debugger/core/promise.js', 'debug');
    require('script/debugger/transport.js', 'debug');
    require('script/debugger/main.js', 'debug');
    require('script/debugger/actors/object.js', 'debug');
    require('script/debugger/actors/root.js', 'debug');
    require('script/debugger/actors/script.js', 'debug');
    require('script/debugger/actors/webconsole.js', 'debug')
    require('script/debugger/actors/utils/TabSources.js', 'debug');

    //DebuggerServer.addTestGlobal = function(aGlobal) {
      gTestGlobals.push(global);
    //};

    transport = new DebuggerTransport();
};


text:
package org.jetbrains.plugins.scala
package testingSupport.test.specs2

import org.jetbrains.plugins.scala.testingSupport.test.AbstractTestFramework

/**
 * @author Ksenia.Sautina
 * @since 5/15/12
 */

class Specs2TestFramework extends AbstractTestFramework {

  def getDefaultSuperClass: String = "org.specs2.mutable.Specification"

  def getName: String = "Specs2"

  def getMarkerClassFQName: String = "org.specs2.mutable.Specification"

  def getMnemonic: Char = 'p'

  override protected def getLibraryDependencies(scalaVersion: Option[String]): Seq[String] = scalaVersion match {
    case Some(v) if v.startsWith("2.11") => Seq("\"org.specs2\" % \"specs2-core_2.11\" % \"latest.integration\" % \"test\"")
    case Some(v) if v.startsWith("2.10") => Seq("\"org.specs2\" % \"specs2-core_2.10\" % \"latest.integration\" % \"test\"")
    case _ => Seq("\"org.specs2\" %% \"specs2-core\" % \"latest.integration\" % \"test\"")
  }

  override protected def getLibraryResolvers(scalaVersion: Option[String]): Seq[String] = scalaVersion match {
    case Some(v) if v.startsWith("2.11") => Seq("\"scalaz-bintray\" at \"http://dl.bintray.com/scalaz/releases\"")
    case Some(v) if v.startsWith("2.10") => Seq("\"scalaz-bintray\" at \"http://dl.bintray.com/scalaz/releases\"")
    case _ => Seq()
  }

  override protected def getAdditionalBuildCommands(scalaVersion: Option[String]): Seq[String] =
    Seq("\"-Yrangepos\"")

  override def getSuitePaths: Seq[String] = Specs2Util.suitePaths

  override def getTestFileTemplateName = "Specs2 Class"
}


text:
@protocol CRAppRestorationStateConfigurator <NSObject>

@optional

- (UIViewController *)viewControllerWithIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder;

- (BOOL)shouldSaveApplicationState:(NSCoder *)coder;
- (BOOL)shouldRestoreApplicationState:(NSCoder *)coder;

- (void)willEncodeRestorableStateWithCoder:(NSCoder *)coder;
- (void)didDecodeRestorableStateWithCoder:(NSCoder *)coder;

@end


text:
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
-->
<ivy-module version="1.0">
	<info organisation="org1"
	       module="mod1.6"
	       revision="1.0.3"
	/>
	<dependencies>
		<dependency name="mod1.4" rev="1.3" />
		<dependency name="mod1.3" rev="3.0">
			<artifact name="mod1.3-A" type="jar" />
			<artifact name="mod1.3-B" type="jar" />
		</dependency>
	</dependencies>
</ivy-module>


text:
import {Component} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {Dropdown, DropdownToggle} from 'ng2-bootstrap/ng2-bootstrap';
import {DROPDOWN_DIRECTIVES, ACCORDION_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
import {RouteConfig,ROUTER_DIRECTIVES,Router} from 'angular2/router';
import { HTTP_PROVIDERS }    from 'angular2/http';
import {UserService}	from '../../../shared/services/user.service';
import {HomeCmp} from '../../../pages/home/components/home';
import {ProfileCmp} from '../../../pages/profile/components/profile';

@Component({
	selector: 'topnav',
	templateUrl: './widgets/topnav/components/topnav.html',
	directives: [Dropdown, DropdownToggle, ROUTER_DIRECTIVES, CORE_DIRECTIVES, ACCORDION_DIRECTIVES],
	viewProviders: [Dropdown, DropdownToggle, DROPDOWN_DIRECTIVES],
	providers:[HTTP_PROVIDERS, UserService]
})
@RouteConfig([
	{ path: '/home', component: HomeCmp, as: 'Home' },
  { path: '/profile', component: ProfileCmp, as: 'Profile' }
])
export class TopNavCmp {
	public oneAtATime:boolean = true;
	public items: Array<any> = [{name:'google',link: 'https://google.com'},{name:'facebook',link: 'https://facebook.com'}];
	public status:Object = {
	    isFirstOpen: true,
	    isFirstDisabled: false
	};
	username:string;

	constructor(private _router: Router, private _userService: UserService) { }
	gotoDashboard() {
		this._router.navigate(['Home']);
	}
	logout() {
		this._userService.logout()
   				.subscribe(
   					()=>this._router.navigate(['Login']));
	}

	ngOnInit() {
		this.username = localStorage.getItem('connectedUserName');
		/*console.log('localstorage'+localStorage.getItem('connectedUserName'));
		console.log('user'+this.username);*/
    }
}


text:
package seedu.jimi.logic.commands;

import java.io.IOException;

import seedu.jimi.commons.core.Config;
import seedu.jimi.commons.exceptions.DataConversionException;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.commons.util.ConfigUtil;
import seedu.jimi.commons.util.FileUtil;

/**
 *
 * @@author A0143471L
 *
 * Sets save directory for the tasks and events in Jimi.
 */
public class SaveAsCommand extends Command {

    public static final String COMMAND_WORD = "saveas";

    public static final String COMMAND_WORD_RESET = "reset";

    public static final String MESSAGE_USAGE =
            COMMAND_WORD + ": Set a new save directory for all your tasks and events in Jimi.\n"
            + "Parameters: FILEPATH/FILENAME.xml or FILEPATH\\FILENAME.xml \n"
            + "Example: " + COMMAND_WORD + " C:/dropbox/taskbook.xml\n"
            + "> Tip: type \"saveas reset\" to reset Jimi's save directory back to its default.";

    public static final String MESSAGE_INVALID_PATH = "Specified directory is invalid!";
    public static final String MESSAGE_SUCCESS = "Save directory changed: %1$s";
    public static final String MESSAGE_CONFIG_FILE_NOT_FOUND = "Config file not found.";
    public static final String MESSAGE_DUPLICATE_SAVE_DIRECTORY =
            "New save directory is the same as the old save directory.";

    private static String configFilePath = Config.DEFAULT_CONFIG_FILE;

    private final String taskBookFilePath;

    /**
     * Empty constructor for stub usage
     */
    public SaveAsCommand() {
        this.taskBookFilePath = null;
    }

    /**
     * Convenience constructor using raw values.
     * @throws IllegalValueException
     */
    public SaveAsCommand(String filePath) throws IllegalValueException {
        if (!FileUtil.isValidPath(filePath)) {
            throw new IllegalValueException(MESSAGE_INVALID_PATH);
        }

        this.taskBookFilePath = filePath;
    }

    public static void setConfigFilePath(String newConfigFilePath) {
        configFilePath = newConfigFilePath;
    }

    @Override
    public CommandResult execute() {
        assert FileUtil.isValidPath(taskBookFilePath);

        try {
            Config config = ConfigUtil.readConfig(configFilePath).orElse(new Config());

            String oldTaskBookFilePath = config.getTaskBookFilePath();
            if (oldTaskBookFilePath.equals(taskBookFilePath)) {
                indicateAttemptToExecuteIncorrectCommand();
                return new CommandResult(String.format(MESSAGE_DUPLICATE_SAVE_DIRECTORY));
            }
            config.setTaskBookFilePath(taskBookFilePath);

            ConfigUtil.saveConfig(config, configFilePath);

            indicateStoragePathChanged(oldTaskBookFilePath, taskBookFilePath);

            return new CommandResult(String.format(MESSAGE_SUCCESS, config.getTaskBookFilePath()));
        } catch (DataConversionException e) {
            return new CommandResult(MESSAGE_CONFIG_FILE_NOT_FOUND);
        } catch (IOException e) {
            return new CommandResult(e.getMessage());
        }
    }

    @Override
    public boolean isValidCommandWord(String commandWord) {
        return commandWord.equalsIgnoreCase(COMMAND_WORD);
    }

    @Override
    public String getMessageUsage() {
        return MESSAGE_USAGE;
    }

    @Override
    public String getCommandWord() {
        return COMMAND_WORD;
    }
}


text:
A tree data structure that is always updated from the root, even if the modification is triggered by one of the leaves, making easier to think in a reactive way.

[![Build Status](https://secure.travis-ci.org/arqex/freezer.svg)](https://travis-ci.org/arqex/freezer)
[![npm version](https://badge.fury.io/js/freezer-js.svg)](http://badge.fury.io/js/freezer-js)

Freezer is made with React.js in mind and uses real immutable structures, it is the perfect store for your Flux implementation.

What makes Freezer special is:

* Immutable trees to make fast comparison among nodes.
* Eventful nodes to notify updates to other parts of the app.
* No dependencies.
* Lightweight: ~7KB minified (much less if gzipped).
* Packaged as UMD module to be loaded everywhere.
* Uses common JS array and objects to store the data, so you can use it with your favourite libs like [lodash](https://lodash.com/), [underscore](http://underscorejs.org/) or [ramda](http://ramdajs.com/)

Do you want to know more?

* [Demos](#demos)
* [Installation](#installation)
* [Example](#example-of-use)
* [Motivation](#why-another-store)
* [Freezer API](#api)
* [Updating the data](#update-methods)
* [Events](#events-1)
* [Batch updates](#batch-updates)
* [Changelog](#changelog)

## Demos
* [You can **test** freezer.js in this JSbin](http://jsbin.com/fedeva/4/edit?js,console)
* [A JSON editor with undo and redo](http://jsbin.com/hugusi/1/edit?js,output), and [here the blog article](http://arqex.com/991/json-editor-react-immutable-data) explaining it

## Installation
Freezer is available as a npm package.
```
npm install freezer-js
```

Also as a bower package
```
bower install freezer-js
```

It is possible to download the [full version](https://raw.githubusercontent.com/arqex/freezer/master/build/freezer.js) (~13KB) or [minified](https://raw.githubusercontent.com/arqex/freezer/master/build/freezer.min.js) (~7KB).

## Example of use
You can play with [this example in JSBin](http://jsbin.com/suvoxivizi/2/edit?js,console).
```js
// Browserify/Node style of loading
var Freezer = require('freezer-js');

// Let's create a freezer store
var store = new Freezer({
    a: {x: 1, y: 2, z: [0, 1, 2] },
    b: [ 5, 6, 7 , { m: 1, n: 2 } ],
    c: 'Hola',
    d: null // It is possible to store whatever
});

// Let's get the frozen data stored
var data = store.get();

// Listen to changes in the store
store.on('update', function( newValue ){
    // New value will have the updated store's data
    console.log( 'I was updated' );
});

// The data is read as usual
console.log( data.c ); // logs 'Hola'

// And used as usual
data.a.z.forEach( function( item ){
    console.log( item );
}); // logs 0, 1 and 2

// But it is immutable, so...
data.d = 3; console.log( data.d ); // logs null
data.e = 4; console.log( data.e ); // logs undefined

// to update, use methods like set that returns new frozen data
var updated = data.set( 'e', 4 ); // On next tick it will log 'I was updated'

console.log( data.e ); // Still logs undefined
console.log( updated.e ); // logs 4

// Store data has changed!
store.get() !== data; // true
store.get() === updated; // true

// The nodes that weren't updated are reused
data.a === updated.a; // true
data.b === updated.b; // true

// Updates can be chained because the new immutable
// data node is always returned
var updatedB = updated.b.push( 100 )
    .shift()
    .set(0, 'Updated')
; // It will log 'I was updated' on next tick, just once

// updatedB is the current b property
store.get().b === updatedB; // true

// And it is different from the one that started
updated !== store.get(); // true
updated.b !== updatedB; // true
console.log( updated.b[0] ); // updated did't/can't change: logs 5
console.log( updatedB[0] ); // logs 'Updated'
console.log( updatedB[4] ); // logs 100
updatedB.length === 5; // true: We added 2 elements and removed 1

// Untouched nodes are still the same
data.a === store.get().a; // still true
updated.a === store.get().a; // still true

// Reverting to a previous state is as easy as
// set the data again (Undo/redo made easy)
store.set( data ); // It will log 'I was updated' on next tick

store.get() === data; // true
```

## Why another store?

**Freezer** is inspired by other tree cursor libraries, specially [Cortex](https://github.com/mquan/cortex) that try to solve an inconvenient of the Flux architecture:

* If you have a store with deep nested data and you need to update some value from a child component that reflect that data, you need to dispatch an action and from the top of the store look for the bit of data again to update it. That may involve a lot of extra code to propagate the change and it is more painful when you think that the component knew already what data to update.

In the other hand, data changes always flowing in the same direction is what make Flux architecure so easy to reason about. If we let every component to update the data independently we are building a mess again.

So *Freezer*, instead of letting the child component to update the data directly, gives in every node the tools to require the change. The updates are always made by the root of the store and the data can keep flowing just in one direction.

Imagine that we have the following tree structure as our app store: ![Initial tree](img/initialTree.png)

And we have a component responsible of handling the `store.c.f` ( the yellow node ) part of the data. Its scope is just that part of the tree, so the component receives it as a prop:
```js
// The component receives a part of the freezer data
this.props.branch = { h: 4, i: 5};
```
Eventually the component is used to update `store.c.f.h = 8`. You can dispatch an action with the frozen node as the payload ( making easier for your actions know what to update ), or even use the node itself to require the change:
```js
this.props.branch.set( {h: 8} );
```
Then, *Freezer* will create a new immutable data structure starting from the top of the tree, and our component will receive a new branch to render. The store finished like this: ![Updated tree](img/updatedTree.png)

Since the whole tree is updated, we can have the main app state in one single object and make the top level components re-render in a reactive way to changes that are made deep in the store hierarchy.

**Freezer** is very influenced by the way that [Facebook's Immutable](https://github.com/facebook/immutable-js) handles immutabilty. It creates a new tree every time that a modification is required referencing the non modified nodes from the previous tree. Sharing node references among frozen objects saves memory and boost the performance on creating new frozens.

Using immutability with React is great, because you don't need to make deep comparisons in order to know when to update a component:
```js
shouldComponentUpdate: function( nextProps ){

    // The comparison is fast, and we won't render the component if
    // it does not need it. This is a huge gain in performance.
    return this.props.store != nextProps.store;
}
```

*Freezer* has less features than *Immutable*, but its API is simpler and it is much more lightweight (Minified, Immutable is ~56KB and Freezer ~7KB).

Instead on learning the set of methods needed to use *Immutable*, *Freezer* uses common JS objects and arrays to store the data, so you can start using it right now.

## API

Create a freezer object using the constructor:
```js
var store = new Freezer({a: 'hola', b:[1,2, [3,4,5]], c: false });
```
And then, Freezer API is really simple and only have 2 methods: `get` and `set`. A freezer object also implements the [listener API](#listener-api).

#### get()

Returns an frozen object with the freezer data.
```js
// Logs: {a: 'hola', b:[1,2, [3,4,5]], c: false }
console.log( store.get() );
```
The data returned is actually formed by arrays and objects, but they are sealed to prevent their mutation and they have some methods in them to update the store.
Everytime an update is performed, `get` will return a new frozen object.

#### set( data )

Replace the current frozen data with new one.
```js

// An example on how to undo an update would be like this...
var store = new Freezer({a: 'hola', b:[1,2, [3,4,5]], c: false }),
    data = store.get()
;

var updated = data.set({c: true});
console.log( updated.c ); // true

// Restore the inital state
store.set( data );
console.log( store.get().c ); // false
```

#### Events

Every time that the data is updated, an `update` event is triggered on the store. In order to use those events, *Freezer* stores implement the [listener API](#listener-api), and `on`, `once` and `off` methods are available on them.

## Update methods

Freezer data has three different types of nodes: *Hashes*, *Arrays* and *leaf nodes*. A leaf node can't be updated by itself and it need to be updated using its parent node. Every updating method return a new immutable object with the new node result of the update:
```js
var store = new Freezer({obj: {a:'hola', b:'adios'}, arr: [1,2]});

var updatedObj = store.get().obj.set('a', 'hello');
console.log( updatedObj ); // {a:'hello', b:'adios'}

var updatedArr = store.get().arr.unshift( 0 );
console.log( udpatedArr ); // [0,1,2]

// {obj: {a:'hello', b:'adios'}, arr: [0,1,2]}
console.log( store.get() );
```

 Both, *Array* and *Hashes* nodes have a `set` method to update or add elements to the node and a `reset` method to replace the node by other data.

#### set( keyOrHash, value )
Arrays and hashes can update their children using the `set` method. It accepts a hash with the keys and values to update or two arguments, the key and the value.
```js
var store = new Freezer({obj: {a:'hola', b:'adios'}, arr: [1,2]});

// Updating using a hash
store.get().obj.set( {b:'bye', c:'ciao'} );

// Updating using key and value
store.get().arr.set( 0, 0 );

// {obj: {a:'hola', b:'bye', c:'ciao'}, arr: [0,2]}
console.log( store.get() )
```

#### reset( newData )
Reset/replaces the node with new data. Listeners are preserved if the new data is an `array` or `object`, so it is possible to listen to reset calls.

```js
var store = new Freezer({ foobar: {a: 'a', b: 'b', c: [0, 1, 2] } });

var newfoobar = { foo: 'bar', bar: 'foo' };

var reset = data.foobar.reset(newfoobar);

console.log( reset ); //{ foo: 'bar', bar: 'foo' }
```

#### toJS()
*Freezer* nodes are immutable. `toJS` transform *Freezer* nodes to plain mutable JS objects in case you need them.
```js
// Require node.js assert
var assert = require('assert');

var data = {obj: {a:'hola', b:'adios'}, arr: [1,2]},
    store = new Freezer( data )
;

assert.deepEqual( data, store.get().toJS ); // Ok
```

## Hash methods
#### remove( keyOrKeys )
Removes elements from a hash node. It accepts a string or an array with the names of the strings to remove.

```js
var store = new Freezer({a:'hola', b:'adios', c:'hello', d:'bye'});

var updated = store.get()
    .remove('d') // Removing an element
    .remove(['b', 'c']) // Removing two elements
;

console.log( updated ); //{a: 'hola'}
```

## Array methods
Array nodes have modified versions of the `push`, `pop`, `unshift`, `shift` and `splice` methods that update the cursor and return the new node, instead of updating the immutable array node ( that would be impossible ).
```js
var store = new Freezer({ arr: [0,1,2,3,4] });

store.get().arr
    .push( 5 ) // [0,1,2,3,4,5]
    .pop() // [0,1,2,3,4]
    .unshift( 'a' ) // ['a',0,1,2,3,4]
    .shift() // [0,1,2,3,4]
    .splice( 1, 1, 'a', 'b') // [ 0, 'a', 'b', 2, 3, 4]
;
```

Array nodes also have the `append` and `prepend` methods to batch insert elements at the begining or the end of the array.
```js
var store = new Freezer({ arr: [2] });

store.get().arr
    .prepend([0,1]) // [0,1,2]
    .append([3,4]) // [0,1,2,3,4]
;
```

## Events
Freezer objects emit `update` events whenever their data changes. It is also possible to listen to `update` events in a intermediate node by creating a listener on it using the method `getListener`.

#### getListener()
Returns a listener that emits an `update` event when the node is updated. The listener implements the [listener API](#listener-api).
```js
var store = new Cursor({ arr: [2] }),
    data = store.get(),
    listener = data.arr.getListener()
;

listener.on('update', function( data ){
    console.log( 'Updated!' );
    console.log( data );
});

data.arr.push( 3 ); //logs 'Updated!' [2,3]
```

## Listener API
Freezer stores and listeners implement this API that is influenced by the way Backbone handle events. The only event that Freezer emits is `update`, end is emitted on every store/node update.

#### on( eventName, callback )
Register a function to be called when an event occurs.
#### once( eventName, callback )
Register a function to be called once when an event occurs. After being called the callback is unregistered.
#### off( eventName, callback )
Can unregister all callbacks from a listener if the `eventName` parameter is omitted, or all the callbacks for a `eventName` if the `callback` parameter is omitted.
#### trigger( eventName [, param, param, ...] )
Trigger an event on the listener. All the extra parameters will be passed to the registered callbacks.

## Batch updates
At some point you will find yourself wanting to apply multiple changes on some node at a time. On every change the full tree is re-generated, but probably the only tree needed is the final result of all those changes.

Freezer nodes offer a `transact` method to make local modifications to them without generating intermediate frozen trees, and a `run` method to commit all the changes at once. This way your app can have a really good performance.

```js
var frozen = new Freezer({list:[]}),
    data = frozen.get()
;

// transact returns a mutable object
// to make all the local changes
var trans = data.list.transact();

// trans is a common array
for( var i = 0; i < 1000; i++ )
    trans.push(i);

// use it as a normal array
trans[0] = 1000; // [1000, 1, 2, ..., 999]

// the store does not know about the yet
frozen.get().list.length == 0; // true

// to commit the changes use the run method in the node
data.list.run();

// all the changes are made at once
frozen.get().list; // [1000, 1, 2, ..., 999]
```

Transactions are designed to always commit the changes, so if you start a transaction but you forget to call `run`, it will be called automatically on the next tick.

It is possible to update children nodes of a node that is making a transaction, but it is not really recommended. Those updates will not update the store until the transaction in the parent node is commited, and that may lead to confussion if you use child nodes as common freezer nodes. Updating child nodes doesn't improve its performance much because of having a transacting parent, so it is recommended to make the changes in the transaction node and run it as soon as you have finished with the modifications to prevent undesired behavior.

## Changelog
[Here](https://github.com/arqex/freezer/blob/master/CHANGELOG.md)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Grid List - Material Components Catalog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="/images/logo_components_color_2x_web_48dp.png" />

    <link href="demos.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

            

          Grid List

              <input type="checkbox" class="mdc-checkbox__native-control" id="toggle-rtl" aria-labelledby="toggle-rtl-label" />

                <svg class="mdc-checkbox__checkmark" viewBox="0 0 24 24">
                  <path class="mdc-checkbox__checkmark__path" fill="none" stroke="white" d="M1.73,12.91 8.1,19.28 22.79,4.59" />
                </svg>

            Toggle RTL

Grid List (Default): empty grid

Grid List (Default): tile aspect ratio 1x1 with oneline footer caption

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

Grid List: tile aspect ratio 1x1 with 1px gutter

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

Grid List: tile aspect ratio 1x1 image only

Grid List: tile aspect ratio 1x1 with oneline header caption

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

Grid List: tile aspect ratio 1x1 with twoline footer caption

                Single Very Long Grid Title Line
                Support text

                Single Very Long Grid Title Line
                Support text

                Single Very Long Grid Title Line
                Support text

                Single Very Long Grid Title Line
                Support text

                Single Very Long Grid Title Line
                Support text

                Single Very Long Grid Title Line
                Support text

Grid List: tile aspect ratio 1x1 with oneline footer caption and icon at start of the caption

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

Grid List: tile aspect ratio 1x1 with twoline footer caption and icon at start of the caption

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

Grid List: tile aspect ratio 1x1 with oneline footer caption and icon at end of the caption

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

                star_border
                Single Very Long Grid Title Line

Grid List: tile aspect ratio 1x1 with twoline footer caption and icon at end of the caption

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

                star_border
                Single Very Long Grid Title Line
                Support text

Grid List: tile aspect ratio 16x9 with oneline footer caption (Support: 16:9, 4:3, 3:4, 2:3, 3:2 as well)

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

Grid List: use div's background instead of img tag (useful when image ratio cannot be ensured)

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line

                Single Very Long Grid Title Line


text:
#import "ASPPdfExportOptions.h"

@implementation ASPPdfExportOptions

/**
 * Maps json key to property name.
 * This method is used by `JSONModel`.
 */
+ (JSONKeyMapper *)keyMapper
{
  return [[JSONKeyMapper alloc] initWithDictionary:@{ @"TextCompression": @"textCompression", @"EmbedFullFonts": @"embedFullFonts", @"Compliance": @"compliance", @"JpegQuality": @"jpegQuality", @"SaveMetafilesAsPng": @"saveMetafilesAsPng", @"Password": @"password", @"EmbedTrueTypeFontsForASCII": @"embedTrueTypeFontsForASCII", @"ExportFormat": @"exportFormat" }];
}

/**
 * Indicates whether the property with the given name is optional.
 * If `propertyName` is optional, then return `YES`, otherwise return `NO`.
 * This method is used by `JSONModel`.
 */
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
  NSArray *optionalProperties = @[@"textCompression", @"embedFullFonts", @"compliance", @"jpegQuality", @"saveMetafilesAsPng", @"password", @"embedTrueTypeFontsForASCII", @"exportFormat"];

  if ([optionalProperties containsObject:propertyName]) {
    return YES;
  }
  else {
    return NO;
  }
}

/**
 * Gets the string presentation of the object.
 * This method will be called when logging model object using `NSLog`.
 */
- (NSString *)description {
    return [[self toDictionary] description];
}

@end


text:
<?php
    class Category_posts_block_handler extends  block_handler{
        function info()
        {
            $info['category_name'] = "Blog";
            $info['category_icon'] = "dsf";

            $info['block_name'] = "Category Posts";
            $info['block_icon'] = "fa-envelope-o";

            return $info;
        }
        public function generate_admin()
        {
            $post_count = $this->block->data('post_count');
            $alphabetical_order = $this->block->data('alphabetical_order');
            $category = $this->block->data('category');

            $count = array(
                "1" => "1",
                "2" => "2",
                "3" => "3",
                "4" => "4",
                "5" => "5",
                "all" => "All"
                );

            $option = array(
                "yes" => "Yes",
                "no" => "No"
                );

            $category_option = array(
                "all" => "All"
                );
            $categores = new Category();
            $all_category = $categores->get();
            foreach ($all_category->all as $key => $value) {
                $category_option[$value->id] = $value->name;
            }

            $this->admin_select('post_count', $count, 'Post Count: ', $post_count);
            $this->admin_select('alphabetical_order', $option, 'Alphabetical Order (a-z): ', $alphabetical_order);
            $this->admin_select('category', $category_option, 'Category: ', $category);
        }
        public function generate_style()
        {
			include $_SERVER['DOCUMENT_ROOT'].'/builderengine/public/animations/animations.php';

            $sections_font_color = $this->block->data('sections_font_color');
            $sections_font_weight = $this->block->data('sections_font_weight');
            $sections_font_size = $this->block->data('sections_font_size');
            $sections_background_color = $this->block->data('sections_background_color');
			$sections_animation_type = $this->block->data('sections_animation_type');
		    $sections_animation_duration = $this->block->data('sections_animation_duration');
		    $sections_animation_event = $this->block->data('sections_animation_event');
		    $sections_animation_delay = $this->block->data('sections_animation_delay');
            ?>

                        <?php
                        $this->admin_input('sections_font_color','text', 'Font color: ', $sections_font_color);
                        $this->admin_input('sections_font_weight','text', 'Font weight: ', $sections_font_weight);
                        $this->admin_input('sections_font_size','text', 'Font size: ', $sections_font_size);
                        $this->admin_input('sections_background_color','text', 'Background color: ', $sections_background_color);
						$this->admin_select('sections_animation_type', $types,'Animation type: ',$sections_animation_type);
						$this->admin_select('sections_animation_duration', $durations,'Animation duration: ',$sections_animation_duration);
						$this->admin_select('sections_animation_event', $events,'Animation Start: ',$sections_animation_event);
						$this->admin_select('sections_animation_delay', $delays,'Animation Delay: ',$sections_animation_delay);
                        ?>

            <?php
        }
        public function generate_content()
        {

            $CI = & get_instance();
            $CI->load->model('visits');
            $sequence = $CI->visits->populyar_post_by_visits();

            $sections_font_color = $this->block->data('sections_font_color');
            $sections_font_weight = $this->block->data('sections_font_weight');
            $sections_font_size = $this->block->data('sections_font_size');
            $sections_background_color = $this->block->data('sections_background_color');
            $post_count = $this->block->data('post_count');
            $alphabetical_order = $this->block->data('alphabetical_order');
            $category = $this->block->data('category');

			$sections_animation_type = $this->block->data('sections_animation_type');
		    $sections_animation_duration = $this->block->data('sections_animation_duration');
		    $sections_animation_event = $this->block->data('sections_animation_event');
		    $sections_animation_delay = $this->block->data('sections_animation_delay');
			$settings[0][0] ='category'.$this->block->get_id();
			$settings[0][1] = $sections_animation_event;
			$settings[0][2] = $sections_animation_duration.' '.$sections_animation_delay.' '.$sections_animation_type;
			add_action("be_foot", generate_animation_events($settings));
            $section_style =
                'style="
                    background-color: '.$sections_background_color.' !important;
                "';
            $section_link_style =
                'style="
                    color: '.$sections_font_color.' !important;
                    font-weight: '.$sections_font_weight.' !important;
                    font-size: '.$sections_font_size.' !important;
                "';

            $users = new User();
            $all_posts = new Post();
            $all_category = new Category();
            $BuilderEngine = new BuilderEngine();

            $recent_posts = $all_posts->order_by('time_created','desc');

            if($category == 'all' || intval($category) == 0){
                $recent_posts = $recent_posts->get();
            }else{
                $recent_posts = $recent_posts->get_where(array('category_id' => intval($category)));
            }
            $recent_post_limit = $BuilderEngine->get_option('be_blog_posts_per_page');
            if($recent_post_limit == '' || $recent_post_limit == 0){
                $recent_post_limit = 5;
            }
            if(isset($post_count)){
                if($post_count == 'all')
                {
                    $recent_post_limit = count($recent_posts->all);
                }else{
                    $recent_post_limit = $post_count;
                }
            }

            if($alphabetical_order == 'yes')
                ksort($sequence);

            $output = '

';

            $i = 1;
            foreach ($sequence as $key => $value) {
                foreach($recent_posts as $post){
                    if($key == $post->slug){
                        if($i <= $recent_post_limit){
                            $user = $users->get_by_id($post->user_id);
                            $output .= '
							<link href="'.base_url('blocks/category_posts/style.css').'" rel="stylesheet">
							<link href="'.base_url('builderengine/public/animations/css/animate.min.css').'" rel="stylesheet" />

block->get_id().'">

slug.'"> '.$post->title.'

											';
                                                $post_comments = array();
                                                $CI = & get_instance();
                                                $CI->load->model('comment');
                                                $comments = new Comment;
                                                foreach($comments->where('post_id',$post->id)->get() as $comment)
                                                    {array_push($post_comments,$comment->id);}
                                                $num_comments = count($post_comments);
                                                $pluralizer = ($num_comments == 1) ? 'Comment' : 'Comments' ;
                                        $output .= '
                                            slug.'#comments" class="label label-default light"> '.$num_comments.''.$pluralizer.'
                                            '.date('M d, Y', $post->time_created).'
											Post by:  '.$user->username.'

                                            slug.'">image.'" class="img-responsive thumbnail" alt="" />

';
                                            $text_without_slashes = ChEditorfix($post->text);
                                            if(strlen($post->text) > 300)
                                            {
                                                $text = substr($text_without_slashes, 0, 300).'...';
                                            }
                                            else{
                                                $text = $text_without_slashes;
                                            }
                                    $output .= '
'.$text.'

                                        slug.'" class="btn-primary btn-xs pull-right"> READ MORE..

';
                            $i++;
                        }
                    }
                }
            }
            $output .= '

';
            return $output;
        }
        public function generate_admin_menus()
        {
        }
    }
?>


text:
/**
 * @name- SingleBadlee.js
 *
 * @chill- Do not seek to follow in the footsteps of the wise ones: seek what they sought- Matsuo Basho
 *
 *
 * @description- Single badlee Page
 *
 * @author- heartit pirates
 */

"use strict";

import {
  Container,
  Content,
  Header,
  Left,
  Right,
  StyleProvider
} from "native-base";
import React, { Component } from "react";
import { Image, TouchableOpacity } from "react-native";
import { connect } from "react-redux";

import * as actionCreators from "../../badlee__redux/action_creators";
import Icon from "../../components/Icon";
import getTheme from "../../theme/components";
import Comments from "./comments";
import User from "./user";
import BadleeCard from "../../components/BadleeCard";
import Reactions from "./reactions";

class SingleBadlee extends Component {
  constructor(props) {
    super(props);
    this.onBackPress = this.onBackPress.bind(this);
    this.onClickUser = this.onClickUser.bind(this);
    this.onClickLike = this.onClickLike.bind(this);
    this.onClickWish = this.onClickWish.bind(this);
    this.onClickComment = this.onClickComment.bind(this);
    this.onClickDelete = this.onClickDelete.bind(this);
    this.onClickReaction = this.onClickReaction.bind(this);
  }
  onBackPress() {
    this.props.goBack();
  }
  onClickUser(id) {
    requestAnimationFrame(() => {
      this.props.showUserPage(id, {
        navigator: this.props.navigator,
        component: User
      });
    });
  }

  onClickLike(id, didLike) {
    didLike ? this.props.onClickLike(id) : this.props.onClickUnlike(id);
  }
  onClickWish(id, didWish) {
    didWish ? this.props.onClickWish(id) : this.props.onClickUnwish(id);
  }
  onClickComment(id) {
    requestAnimationFrame(() => {
      this.props.showCommentPage(id, {
        navigator: this.props.navigator,
        component: Comments
      });
    });
  }
  onClickDelete(id) {}
  onClickReaction(id) {
    requestAnimationFrame(() => {
      this.props.showReactionPage(id, {
        navigator: this.props.navigator,
        component: Reactions
      });
    });
  }
  render() {
    let cardData = this.props.badlee.toJS();

    return (
      <StyleProvider style={getTheme()}>
        <Container style={{ flex: 1 }}>
          <Header style={{ backgroundColor: "#fff" }}>
            <Left>
              <TouchableOpacity onPress={this.onBackPress}>
                <Icon name="menuBackIcon" width="21" height="21" />
              </TouchableOpacity>
            </Left>
            <Right>
              {cardData.purpose === "showOff" && (
                <Icon name="showoff" width="39" height="39" />
              )}
              {cardData.purpose === "shoutOut" && (
                <Icon name="shoutout" width="33" height="33" />
              )}
              {cardData.purpose === "exchange" && (
                <Icon name="exchange" width="33" height="33" />
              )}
            </Right>
          </Header>
          <Content style={{ flex: 1 }} contentContainerStyle={{ flex: 1 }}>
            <BadleeCard
              id={cardData.id}
              media={cardData.media}
              purpose={cardData.purpose}
              userAvatar={cardData.user_info.avatar}
              userName={cardData.user_info.username}
              time={cardData.timestamp}
              location={cardData.location}
              description={cardData.description}
              likes={cardData.likes}
              wishes={cardData.wishes}
              commentCount={cardData.comment_count}
              userID={cardData.user}
              loggedUserID={this.props.loggedUserID}
              onClickUser={this.onClickUser}
              onClickLike={this.onClickLike}
              onClickWish={this.onClickWish}
              onClickReaction={this.onClickReaction}
              onClickComment={this.onClickComment}
              onClickDelete={this.onClickDelete}
            />
          </Content>
        </Container>
      </StyleProvider>
    );
  }
}

var styles = {
  card: {
    position: "relative",
    marginBottom: 3,
    marginTop: 6,
    borderRadius: 0,
    flex: 1
  },
  purposeIcon: {
    position: "absolute",
    top: 30,
    right: 18,
    zIndex: 9,
    shadowColor: "#000",
    shadowOffset: { width: 10, height: 10 },
    shadowOpacity: 0.8,
    shadowRadius: 100,
    width: 36,
    height: 36
  },
  userAvatar: { height: 40, width: 40, marginRight: 6 },
  userName: { fontWeight: "bold", fontSize: 14, color: "rgba(0, 0, 0, 0.87)" },
  badleeImage: { height: 200, width: "100%", zIndex: 1 },
  badleeLocation: {
    marginLeft: 12,
    marginTop: 2,
    fontSize: 12,
    fontWeight: "bold",
    color: "rgba(0, 0, 0, 0.87)"
  },
  badleeDescription: {
    marginLeft: 12,
    marginTop: 6,
    marginBottom: 5,
    fontSize: 24,
    lineHeight: 36,
    fontFamily: "Ubuntu-Regular",
    color: "rgba(0, 0, 0, 0.87)"
  }
};

const _Wrapped = connect(
  state => ({
    loading: state.getIn(["application", "isLoading"]),
    badlee: state.getIn([
      "badlees",
      "data",
      state.getIn(["badlees", "currentShowing"])
    ]),
    loggedUserID: state.getIn(["user", "loggedUserID"])
  }),
  actionCreators
)(SingleBadlee);

export default _Wrapped;


text:
using LinqToTwitter.Common;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace LinqToTwitter
{
    public record Tweet
    {
        /// <summary>
        /// Attachments, such as polls, images, and videos
        /// </summary>
        [JsonPropertyName("attachments")]
        public TweetAttachments? Attachments { get; init; }

        /// <summary>
        /// Posting user's ID
        /// </summary>
        [JsonPropertyName("author_id")]
        public string? AuthorID { get; init; }

        /// <summary>
        /// Contextual metadata associated with tweet
        /// </summary>
        [JsonPropertyName("context_annotations")]
        public List<TweetContextAnnotation>? ContextAnnotations { get; init; }

        /// <summary>
        /// ID of conversation this tweet is part of (matches original tweet ID)
        /// </summary>
        [JsonPropertyName("conversation_id")]
        public string? ConversationID { get; init; }

        /// <summary>
        /// When tweeted
        /// </summary>
        [JsonPropertyName("created_at")]
        public DateTime? CreatedAt { get; init; }

        /// <summary>
        /// Extracted parts of the tweet, like hashtags, urls, etc.
        /// </summary>
        [JsonPropertyName("entities")]
        public TweetEntities? Entities { get; init; }

        /// <summary>
        /// Tweet location (if user provided)
        /// </summary>
        [JsonPropertyName("geo")]
        public TweetGeo? Geo { get; init; }

        /// <summary>
        /// ID of this tweet
        /// </summary>
        [JsonPropertyName("id")]
        public string? ID { get; init; }

        /// <summary>
        /// If replying, this is the ID of the user being replied to
        /// </summary>
        [JsonPropertyName("in_reply_to_user_id")]
        public string? InReplyToUserID { get; init; }

        /// <summary>
        /// BCP47 Language tag - https://tools.ietf.org/html/bcp47
        /// </summary>
        [JsonPropertyName("lang")]
        public string? Language { get; init; }

        // TODO: finish implementation - requires permissions to access
        /// <summary>
        /// Non-Public Metrics
        /// </summary>
        // TODO: finish implementation - requires permissions to access
        [JsonPropertyName("non_public_metrics")]
        public object? NonPublicMetrics { get; init; }

        /// <summary>
        /// Organic Metrics
        /// </summary>
        // TODO: finish implementation - requires permissions to access
        [JsonPropertyName("organic_metrics")]
        public object? OrganicMetrics { get; init; }

        /// <summary>
        /// Media or links might reveal sensitive information
        /// </summary>
        [JsonPropertyName("possibly_sensitive")]
        public bool? PossiblySensitive { get; init; }

        /// <summary>
        /// Promoted content metrics
        /// </summary>
        // TODO: finish implementation - requires permissions to access
        [JsonPropertyName("promoted_metrics")]
        public object? PromotedMetrics { get; init; }

        /// <summary>
        /// Public metrics
        /// </summary>
        [JsonPropertyName("public_metrics")]
        public TweetPublicMetrics? PublicMetrics { get; init; }

        /// <summary>
        /// Any other tweets that this one refers to
        /// </summary>
        [JsonPropertyName("referenced_tweets")]
        public List<TweetReference>? ReferencedTweets { get; init; }

        /// <summary>
        /// Who can reply to tweet
        /// </summary>
        [JsonPropertyName("reply_settings")]
        public TweetReplySettings ReplySettings { get; set; }

        /// <summary>
        /// The application sending the tweet
        /// </summary>
        [JsonPropertyName("source")]
        public string? Source { get; init; }

        /// <summary>
        /// User's tweet text
        /// </summary>
        [JsonPropertyName("text")]
        public string? Text { get; init; }

        /// <summary>
        /// Information regarding a request to withhold information
        /// </summary>
        [JsonPropertyName("withheld")]
        public TwitterWithheld? Withheld { get; init; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: src/typescript-handler.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: src/typescript-handler.js

var tsApi = require('typescript-api');
var fs = require('fs');
var path = require('path');

/**
 * @module typescript-handler module
 * @description Expressive NodeJS module for importing and managing TS compilation at runtime.
 */
module.exports = (function() {
    /** Default encoding of external TS file */
    var defaultFileEncoding = 'utf-8';
    var compiledFilesDirectory = null;

    /**
     * Run cleanup when our process is finished.
     */
    process.on('exit', function() {
        if (compiledFilesDirectory) {
            removeFolder(compiledFilesDirectory);
        }
    });

    // TODO: Need to refactor this into separate module.
    /**
     * Removes a folder and all files within.
     * @param {string} folder - Path of folder.
     */
    function removeFolder(folder) {
        var directoryExists = fs.existsSync(folder);
        if (directoryExists) {
            fs.readdirSync(folder).forEach(function (file) {
                var fullPath = path.join(folder, file);
                fs.unlinkSync(fullPath);
            });
            fs.rmdirSync(folder);
        }
    }

    /**
     * Wrapper for importing CommonJS module.
     * @private
     * @param {string} source - Raw JS module
     * @returns {Object} CommonJS module
     */
    function require(source) {
        var mod = new module.constructor();
        mod._compile(source);
        return mod.exports;
    }

    /**
     * Invokes the TS API for compilation.
     * @private
     * @param {Object} options - Object that represents the compilation context.
     * @returns {Object} Compilation result
     */
    function compile(options) {
        var compiler = new tsApi.TypeScriptCompiler();
        var snapshot = tsApi.ScriptSnapshot.fromString(options.source);
        compiler.addFile('typescriptHandler.ts', snapshot);

        var iterator = compiler.compile();
        iterator.moveNext();
        var compileResult = iterator.current();

        if (compileResult.diagnostics &&
            compileResult.diagnostics.length > 0) {
            throw new Error('TS compilation error.');
        }

        return compileResult;
    }

    /**
     * Manages process of compilation and importing of in-memory based TS content.
     * @private
     * @param {Object} options - Object that represents the compilation context.
     * @returns {Object} Node Module
     */
    function requireFromSource(options) {
        var compileResult = compile(options);
        return require(compileResult.outputFiles[0].text);
    }

    /**
     * Manages process of compilation and importing of external file based TS content.
     * @private
     * @param {Object} options - Object that represents the compilation context.
     * @returns {Object} Node Module
     */
    function requireFromFile(options) {
        var contents = readFile(options.file, options.fileEncoding);

        return requireFromSource({
            source: contents
        });
    }

    /**
     * Reads and returns the contents of a file synchronously.
     * @private
     * @param {string} path - Path to file
     * @param {string} encoding - Encoding of file
     * @returns {NodeBuffer|string}
     */
    function readFile(path, encoding) {
        return fs.readFileSync(path, encoding);
    }

    /**
     * Writes contents to a file synchronously.
     * @private
     * @param {string} path - Path to file
     * @param {string} encoding - Encoding of file
     * @param {string} contents - Contents to write to file
     */
    function writeFile(path, encoding, contents) {
        fs.writeFileSync(path, contents, encoding);
    }

    /**
     * Common validation for compilation options.
     * @private
     * @param {Object} options - Object that represents the compilation context.
     */
    function validateOptions(options) {
        if (!options) {
            throw new Error("Options invalid.");
        }

        if (!options.source && !options.file) {
            throw new Error("No data source defined.");
        }

        if (options.source && options.file) {
            throw new Error("Unable to determine which data source to use. Both defined.");
        }

        if (options.file) {
            if (!fs.existsSync(options.file)) {
                throw new Error('Source file does not exist.');
            }

            if (!options.fileEncoding) {
                options.fileEncoding = defaultFileEncoding;
            }
        }
    }

    /**
     * Validation specific to compileToDisk branch.
     * @private
     * @param {Object} options - Object that represents the compilation context.
     */
    function compileToDiskValidateOptions(options) {
        if (!options.compiledPath) {
            options.compiledPath = 'compiled_tmp/untitled.js';
        }

        var filePath = path.dirname(options.compiledPath);
        if (!fs.existsSync(filePath)) {
            fs.mkdirSync(filePath);
        }
    }

    function setCompiledFilesDirectory(filePath) {
        compiledFilesDirectory = path.dirname(filePath);
    }

    return {
        /**
         * Compiles and imports the passed TS module.
         * @public
         * @param {Object} options
         * @returns {Object} Node Module
         */
        require: function(options) {
            validateOptions(options);
            var result;

            if (options.source) {
                result = requireFromSource(options);
            } else if (options.file) {
                result = requireFromFile(options);
            }

            return result;
        },

        /**
         * Compiles the passed TS and returns the compilation as a string.
         * @public
         * @param {Object} options - Context for compilation.
         * @returns {string} Raw compiled JS
         */
        compile: function (options) {
            validateOptions(options);
            var text;

            if (options.source) {
                var compileResult = compile(options);
                text = compileResult.outputFiles[0].text;
            } else if (options.file) {
                var contents = readFile(options.file, options.fileEncoding);
                var compiledResult = compile({
                    source: contents
                });
                text = compiledResult.outputFiles[0].text;
            }

            return text;
        },

        /**
         * Compiles the passed TS to a JS file on the filesystem.
         * @public
         * @param {Object} options - Context for compilation.
         */
        compileToDisk: function (options) {
            validateOptions(options);
            compileToDiskValidateOptions(options);

            var compiledText, compiledResult;
            setCompiledFilesDirectory(options.compiledPath);

            if (options.source) {
                compiledResult = compile(options);
                compiledText = compiledResult.outputFiles[0].text;
            } else if (options.file) {
                var contents = readFile(options.file, options.fileEncoding);
                compiledResult = compile({
                    source: contents
                });
                compiledText = compiledResult.outputFiles[0].text;
            }

            writeFile(options.compiledPath, options.fileEncoding, compiledText);

            return {
                path: options.compiledPath,
                require: function() {
                    var compiledJs = readFile(options.compiledPath, options.fileEncoding);
                    return require(compiledJs.toString());
                }
            };
        }
    };
})();

Index

Modules

Integration tests

Integration tests for compileToDisk function.

typescript-handler module

Unit tests for public compile function

Unit tests for public require function

    Documentation generated by JSDoc 3.2.2 on Fri Sep 12 2014 13:50:07 GMT-0700 (PDT)


text:
package org.bdgenomics.adam.cli

import org.apache.spark.SparkContext
import org.bdgenomics.adam.projections.AlignmentRecordField._
import org.bdgenomics.adam.projections.Projection
import org.bdgenomics.adam.rdd.ADAMContext._
import org.bdgenomics.adam.rdd.read.AlignmentRecordRDD
import org.bdgenomics.utils.cli._
import org.kohsuke.args4j.{ Argument, Option => Args4jOption }

/**
 * Reads2Coverage (accessible as the command 'reads2coverage' through the CLI) takes two arguments,
 * an INPUT and OUTPUT, and calculates the number of reads from INPUT at every location in
 * the file. Optional arguments are only_negative_strands, only_positive_strands and collapse.
 * only_negative_strands and only_positive_strands save coverage computed from only negative and positive strands,
 * respectively. Collapse specifies whether saved coverage should merge neighboring coverage with the same counts
 * to one record.
 */
object Reads2Coverage extends BDGCommandCompanion {
  val commandName: String = "reads2coverage"
  val commandDescription: String = "Calculate the coverage from a given ADAM file"

  def apply(cmdLine: Array[String]): BDGCommand = {
    new Reads2Coverage(Args4j[Reads2CoverageArgs](cmdLine))
  }
}

class Reads2CoverageArgs extends Args4jBase with ParquetArgs {
  @Argument(required = true, metaVar = "INPUT", usage = "The reads file to use to calculate depths", index = 0)
  var inputPath: String = null
  @Argument(required = true, metaVar = "OUTPUT", usage = "Location to write the coverage data to", index = 1)
  var outputPath: String = null
  @Args4jOption(required = false, name = "-collapse", usage = "Collapses neighboring coverage records " +
    "of equal counts into the same record")
  var collapse: Boolean = false
  @Args4jOption(required = false, name = "-only_negative_strands", usage = "Compute coverage for negative strands")
  var onlyNegativeStrands: Boolean = false
  @Args4jOption(required = false, name = "-only_positive_strands", usage = "Compute coverage for positive strands")
  var onlyPositiveStrands: Boolean = false
  @Args4jOption(required = false, name = "-single", usage = "Saves OUTPUT as single file")
  var asSingleFile: Boolean = false
}

class Reads2Coverage(protected val args: Reads2CoverageArgs) extends BDGSparkCommand[Reads2CoverageArgs] {
  val companion: BDGCommandCompanion = Reads2Coverage

  def run(sc: SparkContext): Unit = {

    val proj = Projection(readMapped, contigName, start, end, cigar)

    // If saving strand specific coverage, require that only one direction is specified
    require(!(args.onlyNegativeStrands && args.onlyPositiveStrands),
      "Cannot compute coverage for both negative and positive strands separately")

    // load reads
    val readsRdd: AlignmentRecordRDD = sc.loadAlignments(args.inputPath, projection = Some(proj))

    val finalReads = if (args.onlyNegativeStrands && !args.onlyPositiveStrands) {
      readsRdd.transform(rdd => rdd.filter(_.getReadNegativeStrand))
    } else if (!args.onlyNegativeStrands && args.onlyPositiveStrands) {
      readsRdd.transform(rdd => rdd.filter(!_.getReadNegativeStrand))
    } else {
      readsRdd
    }

    finalReads.toCoverage(args.collapse)
      .save(args.outputPath, asSingleFile = args.asSingleFile)
  }
}


text:
def reverseString(aStr):
    """
    Given a string, recursively returns a reversed copy of the string.
    For example, if the string is 'abc', the function returns 'cba'.
    The only string operations you are allowed to use are indexing,
    slicing, and concatenation.

    aStr: a string
    returns: a reversed string
    """
    if len(aStr) == 0:
        return ''
    else:
        return aStr[-1] + reverseString(aStr[0:len(aStr)-1])

#
# Problem 4: X-ian
#
def x_ian(x, word):
    """
    Given a string x, returns True if all the letters in x are
    contained in word in the same order as they appear in x.

    >>> x_ian('eric', 'meritocracy')
    True
    >>> x_ian('eric', 'cerium')
    False
    >>> x_ian('john', 'mahjong')
    False

    x: a string
    word: a string
    returns: True if word is x_ian, False otherwise
    """
    if len(x) > len(word):
        return False

    if not x or x == word:
        return True

    if x[0]==word[0]:
        return True and x_ian(x[1:], word[1:])

    return x_ian(x, word[1:])

#
# Problem 5: Typewriter
#
def insertNewlines(text, lineLength):
    """
    Given text and a desired line length, wrap the text as a typewriter would.
    Insert a newline character ("\n") after each word that reaches or exceeds
    the desired line length.

    text: a string containing the text to wrap.
    line_length: the number of characters to include on a line before wrapping
        the next word.
    returns: a string, with newline characters inserted appropriately.
    """
    if len(text) <= lineLength:
        return text
    elif text[lineLength - 1] == ' ':
        return text[:lineLength] + "\n" + insertNewlines(text[lineLength:], lineLength)
    else:
        spaceAt = text[lineLength:].find(' ')
        return text[:spaceAt+lineLength] + "\n" + insertNewlines(text[lineLength+spaceAt+1:], lineLength)


text:
package ti.modules.titanium.ui.widget.listview;

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

import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiConvert;

public class TiListViewTemplate
{

	protected static final String TAG = "TiTemplate";

	protected HashMap<String, DataItem> dataItems;

	public static final String DEFAULT_TEMPLATE = "defaultTemplate";

	public static final String GENERATED_BINDING = "generatedBinding:";

	//Identifier for template, specified in ListView creation dict
	private String templateID;
	//Internal identifier for template, each template has a unique type
	private int templateType;

	protected DataItem rootItem;

	protected String itemID;
	//Properties of the template.
	private KrollDict properties;

	public class DataItem
	{
		//proxy for the item
		TiViewProxy vProxy;
		//binding id
		String bindId;
		DataItem parent;
		ArrayList<DataItem> children;
		KrollDict defaultProperties;

		public DataItem(TiViewProxy proxy, String id, DataItem parent)
		{
			vProxy = proxy;
			bindId = id;
			this.parent = parent;
			setProxyParent();
			children = new ArrayList<DataItem>();
			defaultProperties = new KrollDict();
		}

		private void setProxyParent()
		{

			if (vProxy != null && parent != null) {
				TiViewProxy parentProxy = parent.getViewProxy();
				if (parentProxy != null) {
					vProxy.setParent(parentProxy);
				}
			}
		}

		public TiViewProxy getViewProxy()
		{
			return vProxy;
		}

		public String getBindingId()
		{
			return bindId;
		}
		public void setDefaultProperties(KrollDict d)
		{
			defaultProperties = d;
		}

		public KrollDict getDefaultProperties()
		{
			return defaultProperties;
		}

		public DataItem getParent()
		{
			return parent;
		}

		public ArrayList<DataItem> getChildren()
		{
			return children;
		}

		public void addChild(DataItem child)
		{
			children.add(child);
		}

		public void release()
		{
			if (vProxy != null) {
				vProxy.release();
				vProxy = null;
			}
			children.clear();
			parent = null;
		}
	}

	public TiListViewTemplate(String id, KrollDict properties)
	{
		//Init our binding hashmaps
		dataItems = new HashMap<String, DataItem>();

		//Set item id. Item binding is always "properties"
		itemID = TiC.PROPERTY_PROPERTIES;
		//Init vars.
		templateID = id;
		templateType = -1;
		if (properties != null) {
			this.properties = properties;
			processProperties(this.properties);
		} else {
			this.properties = new KrollDict();
		}
	}

	private DataItem bindProxiesAndProperties(KrollDict properties, boolean isRootTemplate, DataItem parent)
	{
		Object proxy = null;
		String id = null;
		KrollDict props = null;
		DataItem item = null;
		if (properties.containsKey(TiC.PROPERTY_TI_PROXY)) {
			proxy = properties.get(TiC.PROPERTY_TI_PROXY);
		}

		//Get/generate random bind id
		if (isRootTemplate) {
			id = itemID;
		} else if (properties.containsKey(TiC.PROPERTY_BIND_ID)) {
			id = TiConvert.toString(properties, TiC.PROPERTY_BIND_ID);
		} else {
			id = GENERATED_BINDING + Math.random();
		}

		if (proxy instanceof TiViewProxy) {
			TiViewProxy viewProxy = (TiViewProxy) proxy;
			if (isRootTemplate) {
				rootItem = item = new DataItem(viewProxy, TiC.PROPERTY_PROPERTIES, null);
			} else {
				item = new DataItem(viewProxy, id, parent);
				parent.addChild(item);
			}
			dataItems.put(id, item);

			props = viewProxy.getProperties();
		}

		if (properties.containsKey(TiC.PROPERTY_PROPERTIES)) {
			KrollDict templateProperties = properties.getKrollDict(TiC.PROPERTY_PROPERTIES);
			if (templateProperties != null) {
				if (props != null) {
					props.putAll(templateProperties);
				} else {
					props = templateProperties;
				}
			}
		}
		if (props != null) {
			item.setDefaultProperties(props);
		}

		return item;
	}

	private void processProperties(KrollDict properties)
	{
		bindProxiesAndProperties(properties, true, null);
		if (properties.containsKey(TiC.PROPERTY_CHILD_TEMPLATES)) {
			processChildProperties(properties.get(TiC.PROPERTY_CHILD_TEMPLATES), rootItem);
		}
	}

	private void processChildProperties(Object childProperties, DataItem parent)
	{
		if (childProperties instanceof Object[]) {
			Object[] propertiesArray = (Object[]) childProperties;
			for (int i = 0; i < propertiesArray.length; i++) {
				HashMap<String, Object> properties = (HashMap<String, Object>) propertiesArray[i];
				//bind proxies and default properties
				DataItem item = bindProxiesAndProperties(new KrollDict(properties), false, parent);
				//Recursively calls for all childTemplates
				if (properties.containsKey(TiC.PROPERTY_CHILD_TEMPLATES)) {
					if (item == null) {
						Log.e(TAG, "Unable to generate valid data from child view", Log.DEBUG_MODE);
					}
					processChildProperties(properties.get(TiC.PROPERTY_CHILD_TEMPLATES), item);
				}
			}
		}
	}

	public String getTemplateID()
	{
		return templateID;
	}

	public void setType(int type)
	{
		templateType = type;
	}

	public int getType()
	{
		return templateType;
	}

	public String getItemID()
	{
		return itemID;
	}

	public void setRootParent(TiViewProxy listView)
	{
		ListItemProxy rootProxy = (ListItemProxy) rootItem.getViewProxy();
		if (rootProxy != null && rootProxy.getListProxy() == null) {
			rootProxy.setListProxy(listView);
		}
	}

	/**
	 * Returns the bound view proxy if exists.
	 */
	public DataItem getDataItem(String binding)
	{
		return dataItems.get(binding);
	}

	public DataItem getRootItem()
	{
		return rootItem;
	}

	/**
	 *
	 * @param data dictionary holding properties for template
	 * @param update if true update entry else copy non-null values into data parameter
	 */
	public void updateOrMergeWithDefaultProperties(KrollDict data, boolean update)
	{
		for (String binding : data.keySet()) {
			DataItem dataItem = dataItems.get(binding);
			if (dataItem == null)
				continue;

			KrollDict defaultProps = dataItem.getDefaultProperties();
			KrollDict newProps = new KrollDict((HashMap) data.get(binding));
			if (defaultProps != null) {
				if (update) {
					//update default properties
					Set<String> defaultPropsKeys = defaultProps.keySet();
					for (String key : newProps.keySet()) {
						if (!defaultPropsKeys.contains(key)) {
							defaultProps.put(key, null);
						}
					}
				} else {
					//merge default properties with new properties and update data
					HashMap<String, Object> newData = ((HashMap<String, Object>) defaultProps.clone());
					for (Map.Entry<String, Object> entry : newProps.entrySet()) {
						if (entry.getValue() != null) {
							newData.put(entry.getKey(), entry.getValue());
						}
					}
					data.put(binding, newData);
				}
			}
		}
	}

	public void release()
	{
		for (int i = 0; i < dataItems.size(); i++) {
			DataItem item = dataItems.get(i);
			if (item != null) {
				item.release();
			}
		}
		dataItems.clear();
		if (rootItem != null) {
			rootItem.release();
			rootItem = null;
		}
	}
}


text:
#ifndef __less_stylesheet_Selector_h__
#define __less_stylesheet_Selector_h__

#include <list>
#include "less/TokenList.h"

/**
 * If the selector contains commas then it is split up into multiple
 * selectors.
 *
 * For example p .class, a:hover is split up into
 * p .class and a:hover.
 */
class Selector: public std::list<TokenList> {
protected:

public:
  Selector();
  virtual ~Selector();

  void appendSelector(const Selector &selector);

  const TokenList::const_iterator walk(const TokenList::const_iterator &t_begin,
                                       const TokenList::const_iterator &t_end) const;

  void walk(TokenList::const_iterator &it1,
            const TokenList::const_iterator &it1_end,
            TokenList::const_iterator &it2,
            const TokenList::const_iterator &it2_end) const;

  bool match(const TokenList &tokens) const;
  bool match(const Selector &selector) const;
  int compare(const TokenList &tokens,
              TokenList::const_iterator offset,
              const TokenList::const_iterator end) const;
  bool replace(const TokenList &search,
               const TokenList &replace);

  void addPrefix(const Selector &prefix);

  std::string toString() const;
};

#endif  // __less_stylesheet_Selector_h__


text:
using FlaUI.Core.AutomationElements.Infrastructure;
using FlaUI.Core.Definitions;

namespace VcEngineAutomation.Models
{
    public class EcatComponent
    {
        public EcatComponent(AutomationElement automationElement)
        {
            this.AutomationElement = automationElement;
        }
        public AutomationElement AutomationElement { get; }

        public void Load()
        {
            AutomationElement.DoubleClick();
        }

        public string Name
        {
            get { return AutomationElement.FindFirstChild(cf => cf.ByControlType(ControlType.Text)).AsLabel().Text; }
        }
    }
}


text:
#include "Arduino.h"
#include "Nokia_5110.h"
#include "Font.h"

Nokia_5110::Nokia_5110(){}

Nokia_5110::Nokia_5110(unsigned short RST, unsigned short CE, unsigned short DC, unsigned short DIN, unsigned short CLK){
    _RST = RST;
    _CE = CE;
    _DC = DC;
    _DIN = DIN;
    _CLK = CLK;

    pinMode(RST, OUTPUT);
    pinMode(CE, OUTPUT);
    pinMode(DC, OUTPUT);
    pinMode(DIN, OUTPUT);
    pinMode(CLK, OUTPUT);

    _cursor = Cursor();

    reset();

    clear();
    setDisplayMode(Display_Mode::NORMAL);
    setBiasSystem(Mux_Rate::FORTY);
    setContrast(60);
}

void Nokia_5110::startTransmission(){
    digitalWrite(_CE, LOW);
}

void Nokia_5110::endTransmission(){
    digitalWrite(_CE, HIGH);
}

void Nokia_5110::transmitInformation(byte information){
    startTransmission();
    shiftOut(_DIN, _CLK, MSBFIRST, information);
    endTransmission();
}

void Nokia_5110::execute(byte command){
    initializeForSendingCommand();
    transmitInformation(command);
}

void Nokia_5110::initializeForSendingCommand(){
    digitalWrite(_DC, LOW);
}

/**
 * @param contrast could be 0 to 127
 */
void Nokia_5110::setContrast(unsigned short value){
    if(value > 127)
        return;

    extendedInstruction();

    const unsigned short leastValue = 128;
    execute(byte(leastValue + value));
}

void Nokia_5110::extendedInstruction(){
    execute(0x21);
}

void Nokia_5110::basicInstruction(){
    execute(0x20);
}

/**
 * Temperature Coefficient value could be one of 0, 1, 2 or 3;
 */
void Nokia_5110::setTemperatureCoefficient(unsigned short value){

    if(value > 3)
        return;

    extendedInstruction();

    const unsigned short leastValue = 4;
    execute(byte(leastValue + value));
}

void Nokia_5110::reset(){
    digitalWrite(_RST, LOW);
    digitalWrite(_RST, HIGH);
}

void Nokia_5110::initializeForSendingData(){
    digitalWrite(_DC, HIGH);
}

void Nokia_5110::makeEnoughSpaceForPrinting(unsigned short int newCharacterLength){
    if((newCharacterLength + _cursor.getPosition().x) < 85)
        return;

    _cursor.moveYAxis(1);
    setCursor(_cursor.getPosition().x, _cursor.getPosition().y);
    initializeForSendingData();
}

void Nokia_5110::_print(uint8_t charAsciiCode){

    if (charAsciiCode == 0x0a){ // \n for jumping to the beginning of a new line.
        _cursor.moveYAxis(1);
        return;
    }

    setCursor(_cursor.getPosition().x, _cursor.getPosition().y);

    initializeForSendingData();

    character fontData = findCorrespondingByte(charAsciiCode);
    makeEnoughSpaceForPrinting(fontData.definition_total_bytes);

    for(unsigned int i = 0; i < fontData.definition_total_bytes; i++){
        transmitInformation(fontData.definition[i]);
    }

    transmitInformation(0x0); // add an empty line after each chars
    _cursor.moveXAxis(fontData.definition_total_bytes + 1);
}

void Nokia_5110::setCursor(position x, position y){
    _cursor.setCursor(x, y);

    basicInstruction();

    //set x position
    unsigned short int leastXPositionValue = 128;
    execute(byte(leastXPositionValue + x));

    //set y position
    unsigned short int leastYPositionValue = 64;
    execute(byte(leastYPositionValue + y));
}

void Nokia_5110::clear(){
    initializeForSendingData();

    int i = 504;
    while(i >= 0){
        transmitInformation(0x0);
        i--;
    }

    setCursor(0, 0);
}

void Nokia_5110::clear(position inRow, position fromColumn, position toColumn){
    // toColumn has to be more than from Column, otherwise flip the values :D
    position temp;
    if(fromColumn > toColumn){
        temp       = fromColumn;
        fromColumn = toColumn;
        toColumn   = temp;
    }

    position counter = fromColumn;
    while(counter <= toColumn){
        setCursor(counter, inRow);
        initializeForSendingData();
        transmitInformation(0x0);
        counter++;
    }

    setCursor(fromColumn, inRow);
}

void Nokia_5110::setDisplayMode(display_mode value){
    basicInstruction();
    execute(value);
}

void Nokia_5110::setBiasSystem(mux_rate rate){
    extendedInstruction();
    execute(rate);
}

size_t Nokia_5110::write(uint8_t character) {
    _print(character);
    return 1;
}


text:
#ifndef ResourceLoader_h
#define ResourceLoader_h

#include "ResourceHandleClient.h"
#include "ResourceLoaderOptions.h"
#include "ResourceRequest.h"
#include "ResourceResponse.h"

#include <wtf/Forward.h>
#include <wtf/RefCounted.h>

namespace WebCore {

class AuthenticationChallenge;
class DocumentLoader;
class Frame;
class FrameLoader;
class KURL;
class ResourceBuffer;
class ResourceHandle;

class ResourceLoader : public RefCounted<ResourceLoader>, protected ResourceHandleClient {
public:
    virtual ~ResourceLoader();

    void cancel();

    virtual bool init(const ResourceRequest&);

    FrameLoader* frameLoader() const;
    DocumentLoader* documentLoader() const { return m_documentLoader.get(); }
    const ResourceRequest& originalRequest() const { return m_originalRequest; }

    virtual void cancel(const ResourceError&);
    ResourceError cancelledError();
    ResourceError blockedError();
    ResourceError cannotShowURLError();

    virtual void setDefersLoading(bool);

    unsigned long identifier() const { return m_identifier; }

    virtual void releaseResources();
    const ResourceResponse& response() const;

    virtual void addData(const char*, int, bool allAtOnce);
    virtual PassRefPtr<ResourceBuffer> resourceData();
    void clearResourceData();
    virtual bool isSubresourceLoader();

    virtual void willSendRequest(ResourceRequest&, const ResourceResponse& redirectResponse);
    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
    virtual void didReceiveResponse(const ResourceResponse&);
    virtual void didReceiveData(const char*, int, long long encodedDataLength, bool allAtOnce);
    virtual void didReceiveCachedMetadata(const char*, int) { }
    void willStopBufferingData(const char*, int);
    virtual void didFinishLoading(double finishTime);
    virtual void didFail(const ResourceError&);
#if HAVE(NETWORK_CFDATA_ARRAY_CALLBACK)
    virtual void didReceiveDataArray(CFArrayRef dataArray);
#endif

    virtual bool shouldUseCredentialStorage();
    virtual void didReceiveAuthenticationChallenge(const AuthenticationChallenge&);
    void didCancelAuthenticationChallenge(const AuthenticationChallenge&);
#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
    virtual bool canAuthenticateAgainstProtectionSpace(const ProtectionSpace&);
#endif
    virtual void receivedCancellation(const AuthenticationChallenge&);

    // ResourceHandleClient
    virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse& redirectResponse);
    virtual void didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
    virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
    virtual void didReceiveData(ResourceHandle*, const char*, int, int encodedDataLength);
    virtual void didReceiveCachedMetadata(ResourceHandle*, const char* data, int length) { didReceiveCachedMetadata(data, length); }
    virtual void didFinishLoading(ResourceHandle*, double finishTime);
    virtual void didFail(ResourceHandle*, const ResourceError&);
    virtual void wasBlocked(ResourceHandle*);
    virtual void cannotShowURL(ResourceHandle*);
    virtual void willStopBufferingData(ResourceHandle*, const char* data, int length) { willStopBufferingData(data, length); }
    virtual bool shouldUseCredentialStorage(ResourceHandle*) { return shouldUseCredentialStorage(); }
    virtual void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge) { didReceiveAuthenticationChallenge(challenge); }
    virtual void didCancelAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge) { didCancelAuthenticationChallenge(challenge); }
#if HAVE(NETWORK_CFDATA_ARRAY_CALLBACK)
    virtual void didReceiveDataArray(ResourceHandle*, CFArrayRef dataArray);
#endif
#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
    virtual bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace& protectionSpace) { return canAuthenticateAgainstProtectionSpace(protectionSpace); }
#endif
    virtual void receivedCancellation(ResourceHandle*, const AuthenticationChallenge& challenge) { receivedCancellation(challenge); }
    virtual void willCacheResponse(ResourceHandle*, CacheStoragePolicy&);
#if PLATFORM(MAC)
#if USE(CFNETWORK)
    virtual CFCachedURLResponseRef willCacheResponse(ResourceHandle*, CFCachedURLResponseRef);
#else
    virtual NSCachedURLResponse* willCacheResponse(ResourceHandle*, NSCachedURLResponse*);
#endif
#endif // PLATFORM(MAC)
#if PLATFORM(WIN) && USE(CFNETWORK)
    // FIXME: Windows should use willCacheResponse - <https://bugs.webkit.org/show_bug.cgi?id=57257>.
    virtual bool shouldCacheResponse(ResourceHandle*, CFCachedURLResponseRef);
#endif
#if PLATFORM(CHROMIUM)
    virtual void didDownloadData(ResourceHandle*, int);
    virtual void didDownloadData(int);
#endif
#if ENABLE(BLOB)
    virtual AsyncFileStream* createAsyncFileStream(FileStreamClient*);
#endif

    const KURL& url() const { return m_request.url(); }
    ResourceHandle* handle() const { return m_handle.get(); }
    bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }

    bool reachedTerminalState() const { return m_reachedTerminalState; }

    void setShouldBufferData(DataBufferingPolicy);

    virtual void reportMemoryUsage(MemoryObjectInfo*) const;

protected:
    ResourceLoader(Frame*, ResourceLoaderOptions);

    friend class ApplicationCacheHost;  // for access to request()
    friend class ResourceLoadScheduler; // for access to start()
    // start() actually sends the load to the network (unless the load is being
    // deferred) and should only be called by ResourceLoadScheduler or setDefersLoading().
    void start();

    void didFinishLoadingOnePart(double finishTime);

    const ResourceRequest& request() const { return m_request; }
    bool cancelled() const { return m_cancelled; }
    bool defersLoading() const { return m_defersLoading; }

    RefPtr<ResourceHandle> m_handle;
    RefPtr<Frame> m_frame;
    RefPtr<DocumentLoader> m_documentLoader;
    ResourceResponse m_response;

private:
    virtual void willCancel(const ResourceError&) = 0;
    virtual void didCancel(const ResourceError&) = 0;

    ResourceRequest m_request;
    ResourceRequest m_originalRequest; // Before redirects.
    RefPtr<ResourceBuffer> m_resourceData;

    unsigned long m_identifier;

    bool m_reachedTerminalState;
    bool m_calledWillCancel;
    bool m_cancelled;
    bool m_notifiedLoadComplete;

    bool m_defersLoading;
    ResourceRequest m_deferredRequest;
    ResourceLoaderOptions m_options;
};

inline const ResourceResponse& ResourceLoader::response() const
{
    return m_response;
}

}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- Waypoint -->
    <item
        android:id="@+id/action_nav_waypoint"
        android:title="@string/action_nav_waypoint"
        app:showAsAction="ifRoom" />

    <!-- Map  -->
    <item
        android:id="@+id/action_nav_map"
        android:title="@string/action_nav_map"
        app:showAsAction="ifRoom" />

    <!-- Compass -->
    <item
        android:id="@+id/action_nav_compass"
        android:title="@string/action_nav_compass"
        app:showAsAction="ifRoom" />

    <!-- Comm -->
    <item
        android:id="@+id/action_nav_comm"
        android:title="@string/action_nav_comm"
        app:showAsAction="ifRoom" />

    <!-- Settings, should always be in the overflow -->
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>


text:
package redisclient

import (
	"fmt"
	"sync"

	"github.com/garyburd/redigo/redis"
	"github.com/spf13/viper"
	"github.com/topfreegames/mqttbot/logger"
)

var once sync.Once
var client *RedisClient

type RedisClient struct {
	Pool *redis.Pool
}

func GetRedisClient(redisHost string, redisPort int, redisPass string) *RedisClient {
	once.Do(func() {
		client = &RedisClient{}
		redisAddress := fmt.Sprintf("%s:%d", redisHost, redisPort)
		client.Pool = redis.NewPool(func() (redis.Conn, error) {
			if viper.GetString("redis.password") != "" {
				c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", viper.GetString("redis.host"),
					viper.GetInt("redis.port")), redis.DialPassword(viper.GetString("redis.password")))
				if err != nil {
					logger.Logger.Error(err.Error())
				}
				return c, err
			}
			c, err := redis.Dial("tcp", redisAddress)
			if err != nil {
				if err != nil {
					logger.Logger.Error(err.Error())
				}
			}
			return c, err
		}, viper.GetInt("redis.maxPoolSize"))
	})
	return client
}


text:
Path to a Packer JSON template file that exists on the node.

For more details on templates consult Packer documentation.


text:
class HoboMigration33 < ActiveRecord::Migration
  def self.up
    change_column :users, :preferred_view, :string, :limit => 255, :default => :expanded

    add_column :companies, :plan, :string, :default => "basic"
  end

  def self.down
    change_column :users, :preferred_view, :string, default: "expanded"

    remove_column :companies, :plan
  end
end