text:
import fetch from 'isomorphic-fetch';

import {REQUEST_KEYS, RECEIVE_KEYS, REQUEST_NAMESPACES, RECEIVE_NAMESPACES} from '../constants/AnalysisTypes';

export function requestNamespaces() {
  return {
    type: REQUEST_NAMESPACES
  };
}

export function receiveNamespaces(namespaces) {
  return {
    type: RECEIVE_NAMESPACES,
    itemCnt: namespaces.length,
    namespaces
  };
}

export function requestKeys() {
  return {
    type: REQUEST_KEYS
  };
}
export function receiveKeys(keys, namespace) {
  return {
    type: RECEIVE_KEYS,
    keyCnt: keys.length,
    namespace
  };
}

function getKeys(namespace) {
  return dispatch => {
    return fetch(`https://play.dhis2.org/test/api/25/dataStore/${namespace}`, {
      method: "GET",
      mode: "cors",
      headers: {
        "Authorization": `Basic ${btoa("admin:district")}`,
        "Accept": "application/json",
        "Content-Type": "application/json"
      }
    }).then(response => {
      return response.json();
    }).then(json => {
      // console.log("Amount of keys: ", json.length);
      dispatch(receiveKeys(json, namespace));
    }).catch(error => {
      console.log(error.message);
    });
  };
}

export function fetchNamespaces() {
  return dispatch => {
    dispatch(requestNamespaces());
    return fetch('https://play.dhis2.org/test/api/25/dataStore', {
      method: "GET",
      mode: "cors",
      headers: {
        "Authorization": `Basic ${btoa("admin:district")}`,
        "Accept": "application/json",
        "Content-Type": "application/json"
      }
    }).then(response => {
      return response.json();
    }).then(namespaces => {
      dispatch(receiveNamespaces(namespaces));
      namespaces.forEach(namespace => {
        dispatch(getKeys(namespace));
      });
    }).catch(error => {
      console.log("Error:");
      console.log(error.message);
    });
  };
}


text:
package net.imagej.launcher;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A classloader whose classpath can be augmented after instantiation.
 *
 * @author Johannes Schindelin
 */
public class ClassLoaderPlus extends URLClassLoader {

	// A frozen ClassLoaderPlus will add only to the urls array
	protected static Set<ClassLoader> frozen = new HashSet<ClassLoader>();
	protected static Map<URLClassLoader, List<URL>> urlsMap = new HashMap<URLClassLoader, List<URL>>();
	protected static Method addURL;

	public static URLClassLoader getInImageJDirectory(final URLClassLoader classLoader,
		final String... relativePaths)
	{
		try {
			final File directory = new File(getImageJDir());
			final Set<URL> urls = new LinkedHashSet<URL>(relativePaths.length);
			for (final String path : relativePaths) {
				discoverDependencies(new File(directory, path), urls);
			}
			return get(classLoader, urls.toArray(new URL[urls.size()]));
		}
		catch (final Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Uh oh: " + e.getMessage());
		}
	}

	private static void discoverDependencies(final File jarFile, final Set<URL> result) {
		final File versioned = getPossiblyVersionedFile(jarFile);
		if (!versioned.exists()) return;
		try {
			final URL url = versioned.toURI().toURL();
			if (result.contains(url)) return;
			result.add(url);
			final Manifest manifest = new JarFile(versioned).getManifest();
			if (manifest == null) return;
			final String classPath = (String)manifest.getMainAttributes().get(Attributes.Name.CLASS_PATH);
			if (classPath == null) return;
			File directory = jarFile.getParentFile();
			if (directory == null) directory = jarFile.getAbsoluteFile().getParentFile();
			for (final String path : classPath.split(" +")) {
				discoverDependencies(new File(directory, path), result);
			}
		} catch (MalformedURLException e) {
			// ignore this class path element
		} catch (IOException e) {
			// ignore this class path element
		}
	}

	public static URLClassLoader get(final URLClassLoader classLoader, final File... files) {
		try {
			final URL[] urls = new URL[files.length];
			for (int i = 0; i < urls.length; i++) {
				urls[i] = files[i].toURI().toURL();
			}
			return get(classLoader, urls);
		}
		catch (final Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Uh oh: " + e.getMessage());
		}
	}

	public static URLClassLoader get(URLClassLoader classLoader, final URL... urls) {
		if (classLoader == null) {
			final ClassLoader currentClassLoader = ClassLoaderPlus.class.getClassLoader();
			if (currentClassLoader instanceof URLClassLoader) {
				classLoader = (URLClassLoader)currentClassLoader;
			} else {
				final ClassLoader contextClassLoader =
					Thread.currentThread().getContextClassLoader();
				if (contextClassLoader instanceof URLClassLoader) {
					classLoader = (URLClassLoader)contextClassLoader;
				}
			}
		}
		if (classLoader == null) return new ClassLoaderPlus(urls);
		for (final URL url : urls) {
			add(classLoader, url);
		}
		return classLoader;
	}

	public static URLClassLoader getRecursivelyInImageJDirectory(final URLClassLoader classLoader,
		final String... relativePaths)
	{
		return getRecursivelyInImageJDirectory(classLoader, false, relativePaths);
	}

	public static URLClassLoader getRecursivelyInImageJDirectory(URLClassLoader classLoader,
		final boolean onlyJars, final String... relativePaths)
	{
		try {
			final File directory = new File(getImageJDir());
			final File[] files = new File[relativePaths.length];
			for (int i = 0; i < files.length; i++)
				classLoader =
					getRecursively(classLoader, onlyJars, new File(directory, relativePaths[i]));
			return classLoader;
		}
		catch (final Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Uh oh: " + e.getMessage());
		}
	}

	public static URLClassLoader getRecursively(final URLClassLoader classLoader, final File directory) {
		return getRecursively(classLoader, false, directory);
	}

	public static URLClassLoader getRecursively(URLClassLoader classLoader, final boolean onlyJars,
		final File directory)
	{
		try {
			if (!onlyJars)
				classLoader = get(classLoader, directory);
			final File[] list = directory.listFiles();
			if (list != null) {
				/*
				Note that this code is replicated in ij1-patcher's LegacyHooks class.
				Improvements to this Pattern string should also be mirrored there.
				*/
				final Pattern pattern =
						Pattern.compile("(batik|jython|jython-standalone|jruby)(-[0-9].*)?\\.jar");
				Arrays.sort(list, new FatJarFileComparator(pattern));
				for (final File file : list) {
					if (file.isDirectory()) classLoader = getRecursively(classLoader, onlyJars, file);
					else if (file.getName().endsWith(".jar")) classLoader = get(classLoader, file);
				}
			}
			return classLoader;
		}
		catch (final Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Uh oh: " + e.getMessage());
		}
	}

	public ClassLoaderPlus() {
		this(new URL[0]);
	}

	public ClassLoaderPlus(final URL... urls) {
		super(urls, Thread.currentThread().getContextClassLoader());
		Thread.currentThread().setContextClassLoader(this);
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append(getClass().getName()).append("(");
		for (final URL url : getURLs()) {
			builder.append(" ").append(url.toString());
		}
		builder.append(" )");
		return builder.toString();
	}

	public static void addInImageJDirectory(final URLClassLoader classLoader, final String relativePath) {
		try {
			add(classLoader, new File(getImageJDir(), relativePath));
		}
		catch (final Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Uh oh: " + e.getMessage());
		}
	}

	public static void add(final URLClassLoader classLoader, final String path) throws MalformedURLException {
		add(classLoader, new File(path));
	}

	public static void add(final URLClassLoader classLoader, final File file) throws MalformedURLException {
		add(classLoader, file.toURI().toURL());
	}

	public static void add(final URLClassLoader classLoader, final URL url) {
		List<URL> urls = urlsMap.get(classLoader);
		if (urls == null) {
			urls = new ArrayList<URL>();
			urlsMap.put(classLoader, urls);
		}
		urls.add(url);
		if (!frozen.contains(classLoader)) {
			if (classLoader instanceof ClassLoaderPlus) {
				((ClassLoaderPlus)classLoader).addURL(url);
			}
			else try {
				if (addURL == null) {
					addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
					addURL.setAccessible(true);
				}
				addURL.invoke(classLoader, url);
			} catch (Throwable t) {
				throw new RuntimeException(t);
			}
		}
	}

	public static void freeze(final ClassLoader classLoader) {
		frozen.add(classLoader);
	}

	public static String getClassPath(final ClassLoader classLoader) {
		List<URL> urls = urlsMap.get(classLoader);
		if (urls == null) return "";

		final StringBuilder builder = new StringBuilder();
		String sep = "";
		for (final URL url : urls)
			if (url.getProtocol().equals("file")) {
				builder.append(sep).append(url.getPath());
				sep = File.pathSeparator;
			}
		return builder.toString();
	}

	public static String getImageJDir() throws ClassNotFoundException {
		String path = System.getProperty("ij.dir");
		if (path != null) return path;
		final String prefix = "file:";
		final String suffix = "/jars/imagej-launcher.jar!/imagej/ClassLoaderPlus.class";
		path =
			Class.forName("net.imagej.launcher.ClassLoaderPlus")
				.getResource("ClassLoaderPlus.class").getPath();
		if (path.startsWith(prefix)) path = path.substring(prefix.length());
		if (path.endsWith(suffix)) {
			path = path.substring(0, path.length() - suffix.length());
		}
		return path;
	}

	public static String getJarPath(final ClassLoader classLoader, final String className) {
		try {
			final Class<?> clazz = classLoader.loadClass(className);
			String path =
				clazz.getResource("/" + className.replace('.', '/') + ".class")
					.getPath();
			if (path.startsWith("file:")) path = path.substring(5);
			final int bang = path.indexOf("!/");
			if (bang > 0) path = path.substring(0, bang);
			return path;
		}
		catch (final Throwable t) {
			t.printStackTrace();
			return null;
		}
	}

	// keep this synchronized with net.imagej.updater.FileObject
	private static Pattern versionPattern = Pattern.compile("(.+?)(-\\d+(\\.\\d+)+[a-z]?(-[A-Za-z0-9.]+|\\.GA)*)(\\.jar)");

	public static File getPossiblyVersionedFile(final File file) {
		if (file.exists()) return file;

		final String baseName;
		final Matcher matcher = versionPattern.matcher(file.getName());
		if (matcher.matches())
			baseName = matcher.group(1);
		else if (file.getName().endsWith(".jar"))
			baseName = file.getName().substring(0, file.getName().length() - 4);
		else
			return file;

		File[] list = file.getParentFile().listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (!name.startsWith(baseName)) return false; // quicker than regex matching
				final Matcher matcher = versionPattern.matcher(name);
				return matcher.matches() && matcher.group(1).equals(baseName);
			}
		});
		if (list == null || list.length < 1) return file;
		if (list.length == 1) return list[0];

		int newest = 0;
		System.err.println("Warning: " + file.getName() + " matched multiple versions:");
		for (int i = 0; i < list.length; i++) {
			System.err.println("\t" + list[i].getName());
			if (i > 0 && list[newest].lastModified() < list[i].lastModified()) newest = i;
		}
		System.err.println("Picking " + list[newest]);
		return list[newest];
	}

	/**
	 * Comparator to ensure that problematic fat JARs are sorted last.
	 * It is intended to be used with a {@link Pattern} that filters things this
	 * way.
	 */
	public final static class FatJarFileComparator implements Comparator<File> {

		private final Pattern pattern;

		private FatJarFileComparator(Pattern pattern) {
			this.pattern = pattern;
		}

		@Override
		public int compare(final File a, final File b) {
			return (pattern.matcher(a.getName()).matches() ? 1 : 0) -
				(pattern.matcher(b.getName()).matches() ? 1 : 0);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
namespace content {

class Navigator;
class RenderFrameHostImpl;

// When a page contains iframes, its renderer process maintains a tree structure
// of those frames. We are mirroring this tree in the browser process. This
// class represents a node in this tree and is a wrapper for all objects that
// are frame-specific (as opposed to page-specific).
class CONTENT_EXPORT FrameTreeNode {
 public:
  static const int64 kInvalidFrameId;

  FrameTreeNode(Navigator* navigator,
                RenderFrameHostDelegate* render_frame_delegate,
                RenderViewHostDelegate* render_view_delegate,
                RenderWidgetHostDelegate* render_widget_delegate,
                RenderFrameHostManager::Delegate* manager_delegate,
                int64 frame_id,
                const std::string& name);

  ~FrameTreeNode();

  void AddChild(scoped_ptr<FrameTreeNode> child);
  void RemoveChild(FrameTreeNode* child);

  // TODO(nasko): This method should be removed once RenderFrameHosts are
  // created by RenderFrameHostManager.
  void set_render_frame_host(
      RenderFrameHostImpl* render_frame_host,
      bool owns_render_frame_host) {
    render_frame_host_ = render_frame_host;
    owns_render_frame_host_ = owns_render_frame_host;
  }

  // Transitional API allowing the RenderFrameHost of a FrameTreeNode
  // representing the main frame to be provided by someone else. After
  // this is called, the FrameTreeNode no longer owns its RenderFrameHost.
  //
  // This should only be used for the main frame (aka root) in a frame tree.
  //
  // TODO(ajwong): Remove this method once the main frame RenderFrameHostImpl is
  // no longer owned by the RenderViewHostImpl.
  void ResetForMainFrame(RenderFrameHostImpl* new_render_frame_host);

  Navigator* navigator() {
    return navigator_.get();
  }

  RenderFrameHostManager* render_manager() {
    return &render_manager_;
  }

  int64 frame_tree_node_id() const {
    return frame_tree_node_id_;
  }

  // DO NOT USE.  Only used by FrameTree until we replace renderer-specific
  // frame IDs with RenderFrameHost routing IDs.
  void set_frame_id(int64 frame_id) {
    DCHECK_EQ(frame_id_, kInvalidFrameId);
    frame_id_ = frame_id;
  }
  int64 frame_id() const {
    return frame_id_;
  }

  const std::string& frame_name() const {
    return frame_name_;
  }

  size_t child_count() const {
    return children_.size();
  }

  FrameTreeNode* child_at(size_t index) const {
    return children_[index];
  }

  const GURL& current_url() const {
    return current_url_;
  }

  void set_current_url(const GURL& url) {
    current_url_ = url;
  }

  RenderFrameHostImpl* render_frame_host() const {
    return render_frame_host_;
  }

 private:
  // The next available browser-global FrameTreeNode ID.
  static int64 next_frame_tree_node_id_;

  // The Navigator object responsible for managing navigations at this node
  // of the frame tree.
  scoped_refptr<Navigator> navigator_;

  // Manages creation and swapping of RenderViewHosts for this frame.  This must
  // be declared before |children_| so that it gets deleted after them.  That's
  // currently necessary so that RenderFrameHostImpl's destructor can call
  // GetProcess.
  // TODO(creis): This will eliminate the need for |render_frame_host_| below.
  RenderFrameHostManager render_manager_;

  // A browser-global identifier for the frame in the page, which stays stable
  // even if the frame does a cross-process navigation.
  const int64 frame_tree_node_id_;

  // The renderer-specific identifier for the frame in the page.
  // TODO(creis): Remove this in favor of the RenderFrameHost's routing ID once
  // we create FrameTreeNodes for all frames (even without a flag), since this
  // value can change after cross-process navigations.
  int64 frame_id_;

  // The assigned name of the frame. This name can be empty, unlike the unique
  // name generated internally in the DOM tree.
  std::string frame_name_;

  // The immediate children of this specific frame.
  ScopedVector<FrameTreeNode> children_;

  // When ResetForMainFrame() is called, this is set to false and the
  // |render_frame_host_| below is not deleted on destruction.
  //
  // For the mainframe, the FrameTree does not own the |render_frame_host_|.
  // This is a transitional wart because RenderFrameHostManager does not yet
  // have the bookkeeping logic to handle creating a pending RenderFrameHost
  // along with a pending RenderViewHost. Thus, for the main frame, the
  // RenderViewHost currently retains ownership and the FrameTreeNode should
  // not delete it on destruction.
  bool owns_render_frame_host_;

  // The active RenderFrameHost for this frame. The FrameTreeNode does not
  // always own this pointer.  See comments above |owns_render_frame_host_|.
  // TODO(ajwong): Replace with RenderFrameHostManager.
  RenderFrameHostImpl* render_frame_host_;

  // Track the current frame's last committed URL, so we can estimate the
  // process impact of out-of-process iframes.
  // TODO(creis): Remove this when we can store subframe URLs in the
  // NavigationController.
  GURL current_url_;

  DISALLOW_COPY_AND_ASSIGN(FrameTreeNode);
};

}  // namespace content

#endif  // CONTENT_BROWSER_FRAME_HOST_FRAME_TREE_NODE_H_


text:
import os
import re
import sys
import csv
import argparse
import urllib.request
import urllib.error

class Colour(object):
    """
    That's colour with a 'u', you Yankee bastards!
    """
    RED = '\033[91m'
    GREEN = '\033[92m'
    ENDC = '\033[0m'

class ExploitCSV(object):
    """
    Exploit-Database CSV file object

    Attributes:
        csv_file: The path to the local exploit-db CSV file.
        parsed_results: List of results matching the search criterias.
    """

    def __init__(self, filename):
        if not os.path.isfile(filename):
            raise IOError("File {0} could not be found".format(filename))
        self.csv_file = filename
        self.parsed_results = None

    def search(self, term, field, verbose):
        """
        Parse field found search term and store results in self.parsed_results

        Args:
            term: Match term to use during search.
            field: CSV field to perform search on.
            verbose: Print status of completed search.

        Raises:
            IOError: Error when reading CSV file.
        """
        results = list()
        if self.parsed_results is None:  # Must be the first pass
            with open(self.csv_file, 'r') as _csv:
                try:
                    reader = csv.DictReader(_csv)
                except csv.Error as e:
                    raise IOError(str(e))

                for row in reader:
                    if re.search(term, row[field], re.IGNORECASE):
                        results.append(row)
        else:
            for row in self.parsed_results:
                if re.search(term, row[field], re.IGNORECASE):
                    results.append(row)

        if verbose:
            if len(results) == 0:
                print(("[  {0}FAIL{1}  ] 0 results "
                       "found for term '{2}'".format(Colour.RED,
                                                   Colour.ENDC,
                                                   term)))
            else:
                print(("[   {0}OK{1}   ] {2} results "
                       "found for term '{3}'".format(Colour.GREEN,
                                                   Colour.ENDC,
                                                   len(results),
                                                   term)))
        self.parsed_results = results

    def pprint(self):
        """
        Pretty print the search results with familiar searchsploit banner
        """
        banner = " Description{0}Path\n{1} {2}".format((" " * 70),
                                                       ("-" * 80),
                                                       ("-" * 25))
        print(banner)
        if self.parsed_results is None:
            print()
        else:
            for result in self.parsed_results:
                print(result['description'],
                      " " * (79 - len(result['description'])),
                      result['file'][9:])

    @staticmethod
    def update(path):
        """
        Update exploit-db CSV file from the offensive-security
        git repo and exit.

        Args:
            path: Path to CSV file to write to.
        """
        repo = (r"http://raw.githubusercontent.com"
                r"/offensive-security/exploit-database/master/files.csv")
        if os.path.isfile(path):
            os.replace(path, "{0}.old".format(path))  # Move path to path.old
        try:
            status = 0
            urllib.request.urlretrieve(repo, filename=path)
            print(("[   {0}OK{1}   ] Updated local "
                   "exploit-db CSV succesfully".format(Colour.GREEN,
                                                       Colour.ENDC)))
        except urllib.error.URLError as e:
            sys.stderr.write("{0}: URLError: {1}\n".format(sys.argv[0], e))
            status = 10
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}\n".format(sys.argv[0], e))
            status = 11
        sys.exit(status)

def main():
    parser = argparse.ArgumentParser(prog='searchsploit2')
    parser.add_argument('--file', '-f', metavar='PATH', action='store',
                        default=("{0}/.searchsploit/"
                                 "exploitdb.csv".format(os.getenv('HOME'))),
                        help='Path to exploit-db CSV file')
    parser.add_argument('--author', '-a', metavar='AUTHOR', action='store',
                        help='Search for exploit author\'s name')
    parser.add_argument('--date', '-y', metavar='YYYY-MM-DD', action='store',
                        help=('Search for exploits published on '
                              'YYYY-MM-DD'))
    parser.add_argument('--platform', '-o', metavar='PLATFORM',
                        action='store',
                        help='Search for exploit affecting OS platform')
    parser.add_argument('--type', '-t', metavar='TYPE', action='store',
                        help='Search for exploit type')
    parser.add_argument('--port', '-p', metavar='PORT', action='store',
                        help='Search for exploit affecting port')
    parser.add_argument('--description', '-d', metavar='TERM',
                        action='store',
                        help='Search exploit description for term')
    parser.add_argument('--update', '-u', action='store_true',
                        help='Update local copy of exploit-db')
    parser.add_argument('--verbose', '-v', action='store_true',
                        help='Enable verbose output')
    parser.add_argument('--version', action='version',
                        version="Searchsploit2 0.8")
    args = parser.parse_args()

    if not os.path.isdir("{0}/.searchsploit/".format(os.getenv('HOME'))):
        try:
            os.mkdir("{0}/.searchsploit/".format(os.getenv('HOME')))
        except os.OSError as e:
            if args.verbose:
                sys.stderr.write('{0}: OSError: {1}\n'.format(sys.argv[0], e))

    if args.update:  # Perform updates and exit
        ExploitCSV.update(args.file)

    try:
        exploitdb = ExploitCSV(args.file)
    except IOError:
        sys.stderr.write(("{0}: File error: File '{1}' "
                          "not found\n".format(sys.argv[0], args.file)))
        sys.exit(1)

    if args.author:
        exploitdb.search(args.author, 'author', args.verbose)

    if args.date:
        if re.match(r'[\d|\D]{4}-[\d|\D]{2}-[\d|\D]{2}', args.date) is None:
            sys.stderr.write(("{0}: DateError: Improper "
                              "date format '{1}'\n".format(sys.argv[0],
                                                           args.date)))
            sys.exit(2)
        try:
            exploitdb.search(args.date, 'date', args.verbose)
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}".format(sys.argv[0], e))
            sys.exit(3)

    if args.platform:
        try:
            exploitdb.search(args.platform, 'platform', args.verbose)
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}".format(sys.argv[0], e))
            sys.exit(3)

    if args.type:
        try:
            exploitdb.search(args.type, 'type', args.verbose)
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}".format(sys.argv[0], e))
            sys.exit(3)

    if args.port:
        try:
            exploitdb.search(args.port, 'port', args.verbose)
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}".format(sys.argv[0], e))
            sys.exit(3)

    if args.description:
        try:
            exploitdb.search(args.description, 'description', args.verbose)
        except IOError as e:
            sys.stderr.write("{0}: IOError: {1}".format(sys.argv[0], e))
            sys.exit(3)

    exploitdb.pprint()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CollectionFacility
</TITLE>

<META NAME="date" CONTENT="2011-09-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

it.essepuntato.facility.collection

Class CollectionFacility

java.lang.Object
  it.essepuntato.facility.collection.CollectionFacility

public class CollectionFacility
extends java.lang.Object

A class defining facilities for collections.

Author:

Silvio Peroni

Constructor Summary

CollectionFacility()

Method Summary

static java.util.Collection
copy(java.util.Collection c)

          It returns a copy of an input collection.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CollectionFacility

public CollectionFacility()

Method Detail

copy

public static java.util.Collection copy(java.util.Collection c)

It returns a copy of an input collection.

Parameters:
c - a collection to be copied.

Returns:
a copy of the input collection.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
using System;
using System.Collections.Generic;

namespace SolrDemo.Extensions
{
    public static class DictionaryExtensions
    {
        public static TValue ValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
        {
            return dict.ContainsKey(key) ? dict[key] : default(TValue);
        }
    }
}


text:
from airflow import DAG
from airflow.contrib.operators import gcs_to_bq, gcs_to_gcs
from airflow.operators import bash_operator

default_args = {
    "owner": "Google",
    "depends_on_past": False,
    "start_date": "2021-03-01",
}

with DAG(
    dag_id="covid19_tracking.covid_racial_data_tracker",
    default_args=default_args,
    max_active_runs=1,
    schedule_interval="@once",
    catchup=False,
    default_view="graph",
) as dag:

    # Task to copy CRDT CSV file from COVID-19 Tracking Project to GCS
    download_raw_csv_file = bash_operator.BashOperator(
        task_id="download_raw_csv_file",
        bash_command="mkdir -p $airflow_home/data/covid19_tracking/covid_racial_data_tracker\ncurl -o $airflow_home/data/covid19_tracking/covid_racial_data_tracker/raw-crdt-data-{{ ds }}.csv -L $csv_source_url\n",
        env={
            "csv_source_url": "https://docs.google.com/spreadsheets/d/e/2PACX-1vS8SzaERcKJOD_EzrtCDK1dX1zkoMochlA9iHoHg_RSw3V8bkpfk1mpw4pfL5RdtSOyx_oScsUtyXyk/pub?gid=43720681&single=true&output=csv",
            "airflow_home": "{{ var.value.airflow_home }}",
        },
    )

    # Run a custom/*.py script to process the raw CSV contents into a BigQuery friendly format
    process_raw_csv_file = bash_operator.BashOperator(
        task_id="process_raw_csv_file",
        bash_command="SOURCE_CSV=$airflow_home/data/$dataset/$pipeline/raw-crdt-data-{{ ds }}.csv TARGET_CSV=$airflow_home/data/$dataset/$pipeline/crdt-data-{{ ds }}.csv python $airflow_home/dags/$dataset/$pipeline/custom/transform_dates.py\n",
        env={
            "airflow_home": "{{ var.value.airflow_home }}",
            "dataset": "covid19_tracking",
            "pipeline": "covid_racial_data_tracker",
        },
    )

    # Task to load the data from Airflow data folder to BigQuery
    load_csv_file_to_bq_table = gcs_to_bq.GoogleCloudStorageToBigQueryOperator(
        task_id="load_csv_file_to_bq_table",
        bucket="{{ var.value.composer_bucket }}",
        source_objects=[
            "data/covid19_tracking/covid_racial_data_tracker/crdt-data-{{ ds }}.csv"
        ],
        source_format="CSV",
        destination_project_dataset_table="covid19_tracking.covid_racial_data_tracker",
        skip_leading_rows=1,
        write_disposition="WRITE_TRUNCATE",
        schema_fields=[
            {
                "name": "date",
                "type": "DATE",
                "mode": "REQUIRED",
                "description": "Date of the observations",
            },
            {
                "name": "state",
                "type": "STRING",
                "mode": "REQUIRED",
                "description": "2-letter postal abbreviation for the state",
            },
            {"name": "cases_total", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_white", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_black", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_latinx", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_asian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_aian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_nhpi", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_multiracial", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_other", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "cases_ethnicity_hispanic", "type": "INTEGER", "mode": "NULLABLE"},
            {
                "name": "cases_ethnicity_nonhispanic",
                "type": "INTEGER",
                "mode": "NULLABLE",
            },
            {"name": "cases_ethnicity_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {
                "name": "deaths_total",
                "type": "INTEGER",
                "mode": "NULLABLE",
                "description": "Total cumulative number of people that have died",
            },
            {"name": "deaths_white", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_black", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_latinx", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_asian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_aian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_nhpi", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_multiracial", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_other", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "deaths_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {
                "name": "deaths_ethnicity_hispanic",
                "type": "INTEGER",
                "mode": "NULLABLE",
            },
            {
                "name": "deaths_ethnicity_nonhispanic",
                "type": "INTEGER",
                "mode": "NULLABLE",
            },
            {"name": "deaths_ethnicity_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_total", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_white", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_black", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_latinx", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_asian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_aian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_nhpi", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_multiracial", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_other", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "hosp_ethnicity_hispanic", "type": "INTEGER", "mode": "NULLABLE"},
            {
                "name": "hosp_ethnicity_nonhispanic",
                "type": "INTEGER",
                "mode": "NULLABLE",
            },
            {"name": "hosp_ethnicity_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_total", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_white", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_black", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_latinx", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_asian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_aian", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_nhpi", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_multiracial", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_other", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_unknown", "type": "INTEGER", "mode": "NULLABLE"},
            {"name": "tests_ethnicity_hispanic", "type": "INTEGER", "mode": "NULLABLE"},
            {
                "name": "tests_ethnicity_nonhispanic",
                "type": "INTEGER",
                "mode": "NULLABLE",
            },
            {"name": "tests_ethnicity_unknow", "type": "INTEGER", "mode": "NULLABLE"},
        ],
    )

    # Task to archive the CSV file in the destination bucket
    archive_csv_file_to_destination_bucket = gcs_to_gcs.GoogleCloudStorageToGoogleCloudStorageOperator(
        task_id="archive_csv_file_to_destination_bucket",
        source_bucket="{{ var.value.composer_bucket }}",
        source_object="data/covid19_tracking/covid_racial_data_tracker/crdt-data-{{ ds }}.csv",
        destination_bucket="{{ var.json.covid19_tracking.destination_bucket }}",
        destination_object="datasets/covid19_tracking/covid_racial_data_tracker/crdt-data-{{ ds }}.csv",
        move_object=True,
    )

    download_raw_csv_file >> process_raw_csv_file
    process_raw_csv_file >> load_csv_file_to_bq_table
    load_csv_file_to_bq_table >> archive_csv_file_to_destination_bucket


text:
//
// System.Runtime.Remoting.MetadataServices.MetaDataExporter
//
// Authors:
//		Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2003 Novell, Inc
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Net;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Metadata;
using System.Runtime.Serialization;

namespace System.Runtime.Remoting.MetadataServices
{
	internal class MetaDataExporter
	{
		public void ExportTypes (ServiceType[] servicetypes, SdlType sdltype, XmlTextWriter tw)
		{
			if (sdltype == SdlType.Sdl)	// Obsolete, we don't support this
				throw new NotSupportedException ();

			if (servicetypes.Length == 0) return;
			Type maint = servicetypes [0].ObjectType;

			Hashtable dataTypes = new Hashtable ();
			ArrayList services = new ArrayList ();
			FindTypes (servicetypes, dataTypes, services);

			if (services.Count > 0)
				maint = ((ServiceType) services[0]).ObjectType;

			string serviceNs = GetXmlNamespace (maint, null);

			tw.Formatting = Formatting.Indented;
			tw.WriteStartElement ("definitions", MetaData.WsdlNamespace);
			tw.WriteAttributeString ("name", maint.Name);
			tw.WriteAttributeString ("targetNamespace", serviceNs);
			tw.WriteAttributeString ("xmlns", MetaData.XmlnsNamespace, MetaData.WsdlNamespace);
			tw.WriteAttributeString ("xmlns", "tns", MetaData.XmlnsNamespace, serviceNs);
			tw.WriteAttributeString ("xmlns", "xsd", MetaData.XmlnsNamespace, MetaData.SchemaNamespace);
			tw.WriteAttributeString ("xmlns", "xsi", MetaData.XmlnsNamespace, MetaData.SchemaInstanceNamespace);
			tw.WriteAttributeString ("xmlns", "suds", MetaData.XmlnsNamespace, MetaData.SudsNamespace);
			tw.WriteAttributeString ("xmlns", "wsdl", MetaData.XmlnsNamespace, MetaData.WsdlNamespace);
			tw.WriteAttributeString ("xmlns", "soapenc", MetaData.XmlnsNamespace, MetaData.SoapEncodingNamespace);
			tw.WriteAttributeString ("xmlns", "soap", MetaData.XmlnsNamespace, MetaData.SoapNamespace);

			int nums = 0;
			foreach (DictionaryEntry entry in dataTypes)
			{
				string ns = (string) entry.Key;
				if (tw.LookupPrefix (ns) != null) continue;
				tw.WriteAttributeString ("xmlns", "ns"+nums, MetaData.XmlnsNamespace, ns);
				nums++;
			}

			// Schema

			if (dataTypes.Count > 0)
			{
				tw.WriteStartElement ("types", MetaData.WsdlNamespace);
				foreach (DictionaryEntry entry in dataTypes)
				{
					SchemaInfo sinfo = (SchemaInfo) entry.Value;
					if (sinfo == null || sinfo.Types.Count == 0) continue;

					tw.WriteStartElement ("s", "schema", MetaData.SchemaNamespace);
					tw.WriteAttributeString ("targetNamespace", (string) entry.Key);
					tw.WriteAttributeString ("elementFormDefault", "unqualified");
					tw.WriteAttributeString ("attributeFormDefault", "unqualified");

					foreach (string ns in sinfo.Imports)
					{
						if (ns == (string) entry.Key) continue;
						tw.WriteStartElement ("import", MetaData.SchemaNamespace);
						tw.WriteAttributeString ("namespace", ns);
						tw.WriteEndElement ();
					}

					foreach (Type type in sinfo.Types)
						WriteDataTypeSchema (tw, type);

					tw.WriteEndElement ();
				}
				tw.WriteEndElement ();
			}

			// Bindings

/*			foreach (ServiceType st in servicetypes)
				WriteServiceBinding (tw, st);
*/
			foreach (ServiceType st in services)
				WriteServiceBinding (tw, st, dataTypes);

			// Service element

			tw.WriteStartElement ("service", MetaData.WsdlNamespace);
			if (services.Count > 0)
				tw.WriteAttributeString ("name", GetServiceName (maint));
			else
				tw.WriteAttributeString ("name", "Service");

			foreach (ServiceType st in services)
			{
				WriteServiceType (tw, st);
			}
			tw.WriteEndElement ();

			// Closing

			tw.WriteEndElement ();
			tw.Flush ();
		}

		void WriteServiceType (XmlTextWriter tw, ServiceType st)
		{
			tw.WriteStartElement ("port", MetaData.WsdlNamespace);
			tw.WriteAttributeString ("name", GetPortName (st.ObjectType));
			tw.WriteAttributeString ("binding", "tns:" + GetBindingName (st.ObjectType));

			if (st.Url != null)
			{
				tw.WriteStartElement ("soap","address", MetaData.SoapNamespace);
				tw.WriteAttributeString ("location", st.Url);
				tw.WriteEndElement ();
			}

			tw.WriteEndElement ();
		}

		void WriteServiceBinding  (XmlTextWriter tw, ServiceType st, Hashtable dataTypes)
		{
			Type type = st.ObjectType;
			string typeName = type.Name;
			MethodInfo[] mets = type.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			bool isService = IsService (type);

			// Messages

			if (isService)
			{
				foreach (MethodInfo met in mets)
				{
					if (met.DeclaringType.Assembly == typeof(object).Assembly) continue;

					ParameterInfo[] pars = met.GetParameters ();
					tw.WriteStartElement ("message", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", typeName + "." + met.Name + "Input");
					foreach (ParameterInfo par in pars)
					{
						if (!par.ParameterType.IsByRef)
							WritePart (tw, par.Name, par.ParameterType, type);
					}
					tw.WriteEndElement ();	// message

					tw.WriteStartElement ("message", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", typeName + "." + met.Name + "Output");

					if (met.ReturnType != typeof(void))
						WritePart (tw, "return", met.ReturnType, type);

					foreach (ParameterInfo par in pars)
					{
						if (par.ParameterType.IsByRef || par.IsOut)
							WritePart (tw, par.Name, par.ParameterType, type);
					}
					tw.WriteEndElement ();	// message
				}
			}

			// Port type

			tw.WriteStartElement ("portType", MetaData.WsdlNamespace);
			tw.WriteAttributeString ("name", typeName + "PortType");

			if (isService)
			{
				foreach (MethodInfo met in mets)
				{
					if (met.DeclaringType.Assembly == typeof(object).Assembly) continue;

					tw.WriteStartElement ("operation", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name);

					StringBuilder sb = new StringBuilder ();
					ParameterInfo[] pars = met.GetParameters ();
					foreach (ParameterInfo par in pars)
					{
						if (sb.Length != 0) sb.Append (" ");
						sb.Append (par.Name);
					}
					tw.WriteAttributeString ("parameterOrder", sb.ToString ());

					tw.WriteStartElement ("input", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name + "Request");
					tw.WriteAttributeString ("message", "tns:" + typeName + "." + met.Name + "Input");
					tw.WriteEndElement ();

					tw.WriteStartElement ("output", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name + "Response");
					tw.WriteAttributeString ("message", "tns:" + typeName + "." + met.Name + "Output");
					tw.WriteEndElement ();

					tw.WriteEndElement ();	// operation
				}
			}
			tw.WriteEndElement ();	// portType

			// Binding

			tw.WriteStartElement ("binding", MetaData.WsdlNamespace);
			tw.WriteAttributeString ("name", typeName + "Binding");
			tw.WriteAttributeString ("type", "tns:" + typeName + "PortType");

			tw.WriteStartElement ("soap", "binding", MetaData.SoapNamespace);
			tw.WriteAttributeString ("style", "rpc");
			tw.WriteAttributeString ("transport", "http://schemas.xmlsoap.org/soap/http");
			tw.WriteEndElement ();

			WriteTypeSuds (tw, type);

			SchemaInfo sinfo = (SchemaInfo) dataTypes [GetXmlNamespace (type,null)];
			if (sinfo != null && !sinfo.SudsGenerated)
			{
				foreach (Type dt in sinfo.Types)
					WriteTypeSuds (tw, dt);
				sinfo.SudsGenerated = true;
			}

			if (isService)
			{
				foreach (MethodInfo met in mets)
				{
					if (met.DeclaringType.Assembly == typeof(object).Assembly) continue;

					tw.WriteStartElement ("operation", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name);

					tw.WriteStartElement ("soap", "operation", MetaData.SoapNamespace);
					tw.WriteAttributeString ("soapAction", GetSoapAction (met));
					tw.WriteEndElement ();

					tw.WriteStartElement ("suds", "method", MetaData.SudsNamespace);
					tw.WriteAttributeString ("attributes", "public");
					tw.WriteEndElement ();

					tw.WriteStartElement ("input", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name + "Request");
					WriteMessageBindingBody (tw, type);
					tw.WriteEndElement ();

					tw.WriteStartElement ("output", MetaData.WsdlNamespace);
					tw.WriteAttributeString ("name", met.Name + "Response");
					WriteMessageBindingBody (tw, type);
					tw.WriteEndElement ();

					tw.WriteEndElement ();	// operation
				}
			}
			tw.WriteEndElement ();	// binding
		}

		void WriteTypeSuds (XmlTextWriter tw, Type type)
		{
			if (type.IsArray || type.IsEnum)
			{
				return;
			}
			else if (type.IsInterface)
			{
				tw.WriteStartElement ("suds", "interface", MetaData.SudsNamespace);
				tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, type, null));
				foreach (Type interf in type.GetInterfaces ()) {
					tw.WriteStartElement ("suds","extends", MetaData.SudsNamespace);
					tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, interf, null));
					tw.WriteEndElement ();
				}
			}
			else if (type.IsValueType)
			{
				tw.WriteStartElement ("suds", "struct", MetaData.SudsNamespace);
				tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, type, null));
				if (type.BaseType != typeof(ValueType))
					tw.WriteAttributeString ("extends", GetQualifiedXmlType (tw, type.BaseType, null));
			}
			else
			{
				tw.WriteStartElement ("suds", "class", MetaData.SudsNamespace);
				tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, type, null));

				if (IsService (type))
				{
					if (type.IsMarshalByRef)
						tw.WriteAttributeString ("rootType", "MarshalByRefObject");
					else
						tw.WriteAttributeString ("rootType", "Delegate");

					if (type.BaseType != typeof(MarshalByRefObject))
						tw.WriteAttributeString ("extends", GetQualifiedXmlType (tw, type.BaseType, null));

					if (type.IsMarshalByRef) {
						foreach (Type interf in type.GetInterfaces ()) {
							tw.WriteStartElement ("suds","implements", MetaData.SudsNamespace);
							tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, interf, null));
							tw.WriteEndElement ();
						}
					}
				}
				else if (typeof(ISerializable).IsAssignableFrom (type))
					tw.WriteAttributeString ("rootType", "ISerializable");

			}
			tw.WriteEndElement ();	// suds
		}

		void WriteMessageBindingBody (XmlTextWriter tw, Type t)
		{
			tw.WriteStartElement ("soap", "body", MetaData.SoapNamespace);
			tw.WriteAttributeString ("use", "encoded");
			tw.WriteAttributeString ("encodingStyle", MetaData.SoapEncodingNamespace);
			tw.WriteAttributeString ("namespace", GetXmlNamespace (t, null));
			tw.WriteEndElement ();
		}

		void WritePart (XmlTextWriter tw, string name, Type t, Type containerType)
		{
			tw.WriteStartElement ("part", MetaData.WsdlNamespace);
			tw.WriteAttributeString ("name", name);
			tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, t, containerType));
			tw.WriteEndElement ();
		}

		void WriteDataTypeSchema (XmlTextWriter tw, Type type)
		{
			if (type.IsArray)
				WriteArraySchema (tw, type);
			else if (type.IsEnum)
				WriteEnumSchema (tw, type);
			else
				WriteClassSchema (tw, type);
		}

		void WriteArraySchema (XmlTextWriter tw, Type type)
		{
			tw.WriteStartElement ("complexType", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("name", GetXmlType (type));
			tw.WriteStartElement ("complexContent", MetaData.SchemaNamespace);
			tw.WriteStartElement ("restriction", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("base", GetQualifiedName (tw, MetaData.SoapEncodingNamespace, "Array"));
			tw.WriteStartElement ("attribute", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("ref", GetQualifiedName (tw, MetaData.SoapEncodingNamespace, "arrayType"));

			string arrayType = "";

			while (type.IsArray)
			{
				arrayType = arrayType + "[" + new string (',', type.GetArrayRank()-1) + "]";
				type = type.GetElementType ();
			}
			arrayType = GetQualifiedXmlType (tw, type, null) + arrayType;

			tw.WriteAttributeString ("wsdl", "arrayType", MetaData.WsdlNamespace, arrayType);
			tw.WriteEndElement ();	// attribute
			tw.WriteEndElement ();  // restriction
			tw.WriteEndElement ();  // complexContent
			tw.WriteEndElement ();  // complexType
		}

		void WriteEnumSchema (XmlTextWriter tw, Type type)
		{
			tw.WriteStartElement ("simpleType", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("name", GetXmlType (type));
			tw.WriteAttributeString ("suds", "enumType", MetaData.SudsNamespace, GetQualifiedXmlType (tw, EnumToUnderlying (type), null));
			tw.WriteStartElement ("restriction", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("base", "xsd:string");

			foreach (string name in Enum.GetNames (type))
			{
				tw.WriteStartElement ("enumeration", MetaData.SchemaNamespace);
				tw.WriteAttributeString ("value", name);
				tw.WriteEndElement ();
			}
			tw.WriteEndElement ();  // restriction
			tw.WriteEndElement ();  // simpleType
		}

		void WriteClassSchema (XmlTextWriter tw, Type type)
		{
			tw.WriteStartElement ("element", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("name", type.Name);
			tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, type, null));
			tw.WriteEndElement ();

			tw.WriteStartElement ("complexType", MetaData.SchemaNamespace);
			tw.WriteAttributeString ("name", GetXmlType (type));
			if (type.BaseType != null && type.BaseType != typeof(object) && type.BaseType != typeof(ValueType))
				tw.WriteAttributeString ("base", GetQualifiedXmlType (tw, type.BaseType, null));

			FieldInfo[] fields = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

			// Element fields

			bool elemsStart = false;
			foreach (FieldInfo fi in fields)
			{
				SoapFieldAttribute att = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (fi);
				if (att.UseAttribute) continue;

				if (!elemsStart) { tw.WriteStartElement ("all", MetaData.SchemaNamespace); elemsStart = true; }
				tw.WriteStartElement ("element", MetaData.SchemaNamespace);
				tw.WriteAttributeString ("name", att.XmlElementName);
				tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, fi.FieldType, type));
				tw.WriteEndElement ();
			}
			if (elemsStart) tw.WriteEndElement ();	// all

			// Attribute fields

			foreach (FieldInfo fi in fields)
			{
				SoapFieldAttribute att = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (fi);
				if (!att.UseAttribute) continue;

				tw.WriteStartElement ("attribute", MetaData.SchemaNamespace);
				tw.WriteAttributeString ("name", att.XmlElementName);
				tw.WriteAttributeString ("type", GetQualifiedXmlType (tw, fi.FieldType, type));
				tw.WriteEndElement ();
			}

			tw.WriteEndElement ();	// complexType

		}

		ArrayList FindServices (ServiceType[] servicetypes)
		{
			ArrayList list = new ArrayList ();
			foreach (ServiceType st in servicetypes)
				if (IsService (st.ObjectType)) list.Add (st);
			return list;
		}

		string GetSoapAction (MethodInfo mb)
		{
			return SoapServices.GetSoapActionFromMethodBase (mb);
		}

		string GetXmlNamespace (Type t, Type containerType)
		{
			string name, ns;

			if (t.IsArray)
			{
				return GetXmlNamespace (containerType, null);
			}

			if (SoapServices.GetXmlTypeForInteropType (t, out name, out ns))
				return ns;

			SoapTypeAttribute att = (SoapTypeAttribute) InternalRemotingServices.GetCachedSoapAttribute (t);
			return att.XmlNamespace;
		}

		string GetQualifiedName (XmlTextWriter tw, string namspace, string localName)
		{
			return tw.LookupPrefix (namspace) + ":" + localName;
		}

		string GetQualifiedXmlType (XmlTextWriter tw, Type type, Type containerType)
		{
			string name, ns;

			if (type.IsArray)
			{
				name = GetXmlType (type);
				ns = GetXmlNamespace (type, containerType);
			}
			else
			{
				name = GetXsdType (type);
				if (name != null) return "xsd:" + name;

				if (!SoapServices.GetXmlTypeForInteropType (type, out name, out ns))
				{
					SoapTypeAttribute att = (SoapTypeAttribute) InternalRemotingServices.GetCachedSoapAttribute (type);
					name = att.XmlTypeName;
					ns = att.XmlNamespace;
				}
			}

			return GetQualifiedName (tw, ns, name);
		}

		string GetXmlType (Type type)
		{
			if (type.IsArray)
			{
				string itemType = GetXmlType (type.GetElementType ());
				itemType = "ArrayOf" + char.ToUpper (itemType[0]) + itemType.Substring (1);
				if (type.GetArrayRank () > 1) itemType += type.GetArrayRank ();
				return itemType;
			}
			else
			{
				string name = null, ns;

				name = GetXsdType (type);
				if (name != null) return name;

				if (SoapServices.GetXmlTypeForInteropType (type, out name, out ns))
					return name;

				SoapTypeAttribute att = (SoapTypeAttribute) InternalRemotingServices.GetCachedSoapAttribute (type);
				return att.XmlTypeName;
			}
		}

		string GetServiceName (Type t)
		{
			return t.Name + "Service";
		}

		string GetPortName (Type t)
		{
			return t.Name + "Port";
		}

		string GetBindingName (Type t)
		{
			return t.Name + "Binding";
		}

		void FindTypes (ServiceType[] servicetypes, Hashtable dataTypes, ArrayList services)
		{
			ArrayList mbrTypes = new ArrayList();

			foreach (ServiceType st in servicetypes)
				FindDataTypes (st.ObjectType, null, dataTypes, mbrTypes);

			foreach (Type mbrType in mbrTypes)
			{
				ServiceType stFound = null;
				foreach (ServiceType st in servicetypes)
					if (mbrType == st.ObjectType) stFound = st;

				if (stFound != null) services.Add (stFound);
				else services.Add (new ServiceType (mbrType));
			}
		}

		void FindDataTypes (Type t, Type containerType, Hashtable types, ArrayList services)
		{
			if (IsSystemType (t))
			{
				string ns = GetXmlNamespace (t, null);
				types [ns] = null;
				return;
			}

			if (!IsService (t))
			{
				if (!t.IsSerializable) return;

				string ns = GetXmlNamespace (t, containerType);
				SchemaInfo sinfo = (SchemaInfo) types [ns];
				if (sinfo == null)
				{
					sinfo = new SchemaInfo ();
					types [ns] = sinfo;
				}

				if (sinfo.Types.Contains (t)) return;

				sinfo.Types.Add (t);
				if (t.IsArray) return;

				FieldInfo[] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
				foreach (FieldInfo fi in fields)
				{
					string fns = GetXmlNamespace (fi.FieldType, t);
					if (!sinfo.Imports.Contains (fns)) sinfo.Imports.Add (fns);
					FindDataTypes (fi.FieldType, t, types, services);
				}
			}
			else
			{
				if (services.Contains (t)) return;
				services.Add (t);

				foreach (MethodInfo met in t.GetMethods (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
				{
					ParameterInfo[] pars = met.GetParameters ();
					foreach (ParameterInfo par in pars)
						FindDataTypes (par.ParameterType, t, types, services);

					FindDataTypes (met.ReturnType, t, types, services);
				}
			}
		}

		bool IsService (Type t)
		{
			return t.IsMarshalByRef || t.IsInterface || typeof(Delegate).IsAssignableFrom (t);
		}

		bool IsSystemType (Type t)
		{
			return t.FullName.StartsWith ("System.") && !t.IsArray;
		}

		static string GetXsdType (Type type)
		{
			if (type.IsEnum) return null;

			switch (Type.GetTypeCode (type))
			{
				case TypeCode.Boolean: return "boolean";
				case TypeCode.Byte: return "unsignedByte";
				case TypeCode.Char: return "char";
				case TypeCode.DateTime: return "dateTime";
				case TypeCode.Decimal: return "decimal";
				case TypeCode.Double: return "double";
				case TypeCode.Int16: return "short";
				case TypeCode.Int32: return "int";
				case TypeCode.Int64: return "long";
				case TypeCode.SByte: return "byte";
				case TypeCode.Single: return "float";
				case TypeCode.UInt16: return "unsignedShort";
				case TypeCode.UInt32: return "unsignedInt";
				case TypeCode.UInt64: return "unsignedLong";
				case TypeCode.String: return "string";
			}

			if (type == typeof (TimeSpan))
				return "duration";
			if (type == typeof (object))
				return "anyType";

			return null;
		}

		//
		// This is needed, because enumerations from assemblies
		// do not report their underlyingtype, but they report
		// themselves
		//
		public static Type EnumToUnderlying (Type t)
		{
			TypeCode tc = Type.GetTypeCode (t);

			switch (tc){
			case TypeCode.Boolean:
				return typeof (bool);
			case TypeCode.Byte:
				return typeof (byte);
			case TypeCode.SByte:
				return typeof (sbyte);
			case TypeCode.Int16:
				return typeof (short);
			case TypeCode.UInt16:
				return typeof (ushort);
			case TypeCode.Int32:
				return typeof (int);
			case TypeCode.UInt32:
				return typeof (uint);
			case TypeCode.Int64:
				return typeof (long);
			case TypeCode.UInt64:
				return typeof (ulong);
			}
			throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
		}
	}

	class SchemaInfo
	{
		public ArrayList Types = new ArrayList ();
		public ArrayList Imports = new ArrayList ();
		public bool SudsGenerated;
	}
}


text:
@implementation MOFBPermission

@synthesize delegate, extPerm;

- (void)obtain:(NSString *)anExtPerm {
	self.extPerm = anExtPerm;
	NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: self.extPerm, @"ext_perm", nil];
	[[FBRequest requestWithDelegate:self] call:@"facebook.Users.hasAppPermission" params:params];
}

- (void)request:(FBRequest*)request didLoad:(NSString *)result {
	if ([result isEqualToString:@"1"])
		[delegate permissionGranted: self];
	else {
		FBPermissionDialog* dialog = [[[FBPermissionDialog alloc] init] autorelease];
		dialog.delegate = self;
		dialog.permission = self.extPerm;
		[dialog show];
	}
}

- (void)dialogDidSucceed:(FBDialog*)dialog {
	[delegate permissionGranted:self];
}

- (void)dialogDidCancel:(FBDialog*)dialog {
	[delegate permissionDenied:self];
}

- (void)dealloc {
	[extPerm release];
	[super dealloc];
}

@end


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "task".
 *
 * @property integer $task_id
 * @property integer $project_id
 * @property integer $user_id
 * @property string $name
 * @property string $start_date
 * @property string $end_date
 * @property integer $estimated_time
 * @property integer $operating_time
 * @property string $regist_date
 * @property string $update_date
 * @property integer $del_chk
 *
 * @property Project $project
 * @property User $user
 */
class Task extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'task';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id', 'user_id', 'name'], 'required'],
            [['project_id', 'user_id', 'estimated_time', 'operating_time', 'del_chk'], 'integer'],
            [['start_date', 'end_date', 'regist_date', 'update_date'], 'safe'   ],
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'task_id' => 'Task ID',
            'project_id' => 'Project ID',
            'user_id' => 'User ID',
            'name' => 'Name',
            'start_date' => 'Start Date',
            'end_date' => 'End Date',
            'estimated_time' => 'Estimated Time',
            'operating_time' => 'Operating Time',
            'regist_date' => 'Regist Date',
            'update_date' => 'Update Date',
            'del_chk' => 'Del Chk',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProject()
    {
        return $this->hasOne(Project::className(), ['project_id' => 'project_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['user_id' => 'user_id']);
    }
}


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.exceptions.BuildTargetParseException;
import com.facebook.buck.core.model.UnconfiguredBuildTarget;
import com.facebook.buck.core.parser.buildtargetparser.UnconfiguredBuildTargetViewFactory;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.common.reflect.TypeToken;

/** {@link TypeCoercer} for {@link UnconfiguredBuildTarget} */
public class UnconfiguredBuildTargetTypeCoercer
    extends LeafUnconfiguredOnlyCoercer<UnconfiguredBuildTarget> {

  private final UnconfiguredBuildTargetViewFactory unconfiguredBuildTargetFactory;

  public UnconfiguredBuildTargetTypeCoercer(
      UnconfiguredBuildTargetViewFactory unconfiguredBuildTargetFactory) {
    this.unconfiguredBuildTargetFactory = unconfiguredBuildTargetFactory;
  }

  @Override
  public TypeToken<UnconfiguredBuildTarget> getUnconfiguredType() {
    return new TypeToken<UnconfiguredBuildTarget>() {};
  }

  @Override
  public UnconfiguredBuildTarget coerceToUnconfigured(
      CellNameResolver cellRoots,
      ProjectFilesystem filesystem,
      ForwardRelativePath pathRelativeToProjectRoot,
      Object object)
      throws CoerceFailedException {
    if (!(object instanceof String)) {
      throw CoerceFailedException.simple(object, getOutputType());
    }
    String param = (String) object;

    try {
      return unconfiguredBuildTargetFactory.createForPathRelativeToProjectRoot(
          pathRelativeToProjectRoot, param, cellRoots);
    } catch (BuildTargetParseException e) {
      throw new CoerceFailedException(
          String.format(
              "Unable to find the target %s.\n%s", object, e.getHumanReadableErrorMessage()),
          e);
    }
  }
}


text:
using SecureService.Clients.WebMVCClientWithCookie.Helpers;
using SecureService.Clients.WebMVCClientWithCookie.Helpers.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Unity;
using Unity.AspNet.Mvc;

namespace SecureService.Clients.WebMVCClientWithCookie.DependencyInjection
{
    public static class UnityBootstrapper
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            container.RegisterType<IAuthorizationManager, AuthorizationManager>();
            container.RegisterType<ICookieSetup, CookieSetup>();
            container.RegisterType<ISessionManager, SessionManager>();
            container.RegisterType<IServiceManager, ServiceManager>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}


text:
INSTALL_WINDOWS_AGENT = """
# download the cloud endure agent
Invoke-WebRequest -Uri https://console.cloudendure.com/installer_win.exe -OutFile C:\installer_win.exe

# install the agent, and configure it using your account's agent installation token.
C:\installer_win.exe -t "{{ agent_installation_token }}" --no-prompt
"""

INSTALL_LINUX_AGENT = """
#download the cloudendure agent
wget -O ./installer_linux.py https://console.cloudendure.com/installer_linux.py

#install the agetn, using your account's agent installation token
sudo python ./installer_linux.py -t "{{ agent_installation_token }}" --no-prompt
"""


text:
"""
File: find_primes.py
Copyright (c) 2016 Austin Ayers
License: MIT

Course: PHYS227
Assignment: 3.34
Date: Feb 11, 2016
Email: ayers111@mail.chapman.edu
Name: Austin Ayers
Description: Implementing a prime sieve
"""

def find_primes(n):
    """
    Creates a generator that outputs prime numbers between 1 and n
    """
    nums = [True] * n
    nums[0] = nums[1] = False
    for i, isPrime in enumerate(nums):
        if isPrime:
            yield i
            for j in range(i*i, n, i):
                nums[j] = False
    return

def test_primse():
    nums = find_primes(100)
    assert(next(nums) == 2 and next(nums) == 3 and next(nums) == 5 and next(nums) == 7 and next(nums) == 11)

def output():
    nums = find_primes(100)
    for i in range(20):
        print(str(next(nums)))


text:
from setuptools import find_packages, setup

import os

from aima import __version__ as version
from aima import __authors__, __github_url__
from aima import __doc__ as description
from aima import __name__ as package_name

print('Installing package named {0}. . .'.format(package_name))

try:
    from pip.req import parse_requirements
    requirements = list(parse_requirements('requirements.txt'))
except:
    requirements = []
install_requires=[str(req).split(' ')[0].strip() for req in requirements if req.req and not req.url]
print('requires: %r' % install_requires)
dependency_links=[req.url for req in requirements if req.url]
print('dependcies: %r' % dependency_links)

long_description = 'Python packages implementing the algorithms and example code in the textbook "Artificial Intalligence: A Modern Approach" by Norvig and Russell.'
try:
    long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
except:
    pass

EXCLUDE_FROM_PACKAGES = []

setup(
    name = package_name,
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),   #[package_name],
    include_package_data = True,  # install non-.py files listed in MANIFEST.in (.js, .html, .txt, .md, etc)
    install_requires = install_requires,
    dependency_links = dependency_links,
    version = version,
    description = description,
    long_description = long_description,
    author = ', '.join(__authors__),
    author_email = "peter.norvig@gmail.com",
    #tests_require = ['doctest'],
    #test_suite = 'setuptest.setuptest.SetupTestSuite',
    #cmdclass = {'test': test},
    url = __github_url__,
    download_url = "%s/tarball/%s" % (__github_url__, version),
    keywords = ["ai", "ml", "artificial intelligence", "machine intelligence", "norvig", "russell", "agent", "bot", "book", "textbook", "algorithm", "machine-learning", "search"],
    classifiers = [
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.5",
        "Development Status :: 3 - Alpha",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
        "Topic :: Scientific/Engineering :: Visualization",
        "Topic :: Scientific/Engineering :: Mathematics",
        ],
)


text:
import moment from 'moment';
import * as types from './mutation-types';

import { gqMutation, gqQuery } from '../helpers';

export default {
  setTimerId({ commit }, { timerId }) {
    commit('SET_TIMER_ID', timerId);
  },

  getTasks({ commit }, payload) {
    let date = '';
    if (payload.date === undefined) {
      date = moment().format('YYYY-MM-DD');
    } else {
      ({ date } = payload);
    }
    return gqQuery('fetchTasks', {
      userUuid: payload.userUuid,
      organizationUuid: payload.orgUuid,
      date,
    })
      .then(({ fetchTasks }) => {
        commit('SET_TASKS', {
          tasks: fetchTasks,
          date,
        });
      });
  },

  createTask({ commit }, payload) {
    return gqMutation('CREATE_TASK', { task: payload.task })
      .then(({ createTask }) => {
        commit('SET_ONE_TASK', createTask);
      });
  },

  updateTask({ commit }, { task, date }) {
    return gqMutation('UPDATE_TASK', { task, date })
      .then(({ updateTask }) => commit('SET_ONE_TASK', updateTask));
  },

  deleteTask({ commit }, { uuid, uuids }) {
    return gqMutation('DELETE_TASK', { uuid, uuids })
      .then(() => commit('DELETE_TASK', { uuid, uuids }));
  },

  createTimeEntry({ dispatch, commit }, { timeEntry }) {
    return gqMutation('CREATE_TIME_ENTRY', {
      timeEntry,
    })
      .then(({ createTimeEntry }) => {
        commit('SET_TIME_ENTRY', createTimeEntry);
        if (createTimeEntry.active === true) {
          dispatch('setActiveTimeEntry', createTimeEntry.uuid);
        }
      });
  },

  setActiveTimeEntry({ commit }, uuid) {
    commit('SET_ACTIVE_TIME_ENTRY', uuid);
  },

  updateTimeEntry({ commit }, { timeEntry }) {
    return gqMutation('UPDATE_TIME_ENTRY', {
      timeEntry,
    })
      .then(({ updateTimeEntry }) => {
        commit('SET_TIME_ENTRY', updateTimeEntry);
      });
  },

  stopTimeEntry({ commit }, { uuid }) {
    return gqMutation('STOP_TIME_ENTRY', {
      uuid,
    })
      .then(({ stopTimeEntry }) => {
        commit('SET_TIME_ENTRY', stopTimeEntry);
      });
  },

  deleteTimeEntry({ commit }, { uuid }) {
    return gqMutation('DELETE_TIME_ENTRY', {
      uuid,
    })
      .then(({ deleteTimeEntry }) => commit('DELETE_TIME_ENTRY', deleteTimeEntry));
  },

  getMe({ commit }) {
    return gqQuery('fetchMe')
      .then(({ fetchMe }) => commit('SET_ME', fetchMe));
  },

  updateUser(context, { user }) {
    return gqMutation('UPDATE_USER', {
      user,
    })
      .then(({ data }) => data);
  },

  clearUser(context) {
    context.commit(types.CLEAR_USER);
  },
  validateEmail({ commit }, { email }) {
    return gqQuery('getUser', { email })
      .then(({
        users: [user],
      }) => commit('SET_EXISTS_EMAIL', user));
    // return Http.post('/api/user/validate-email', { email: payload.email });
  },

  getOneTeam({ commit }, { uuid }) {
    return gqQuery('fetchTeam', { uuid })
      .then(({
        fetchTeam,
      }) => {
        commit('SET_ONE_TEAM', fetchTeam);
      });
  },

  getTeams({ commit }, { ownerType, ownerUuid, userUuid }) {
    return gqQuery('fetchTeams', {
      ownerType,
      ownerUuid,
      userUuid,
    })
      .then(({ fetchTeams }) => {
        commit('SET_TEAMS', fetchTeams);
      });
  },

  searchPersonalTeams({ commit }, { queryString, userUuid }) {
    return gqQuery('searchPersonalTeams', {
      queryString,
      userUuid,
    })
      .then(({ searchPersonalTeams }) => commit('SET_PERSONAL_TEAMS', searchPersonalTeams));
  },

  searchOrganizationTeams({ commit }, { queryString, orgUuid }) {
    return gqQuery('searchOrganizationTeams', {
      queryString,
      organizationUuid: orgUuid,
    })
      .then(({ searchOrganizationTeams }) => commit(
        'SET_ORGANIZATION_TEAMS',
        searchOrganizationTeams,
      ));
  },

  createTeam(context, { team }) {
    return gqMutation('CREATE_TEAM', { team })
      .then(({ data }) => data);
  },

  updateTeam(context, { team }) {
    return gqMutation('UPDATE_TEAM', { team })
      .then(data => data);
  },

  deleteTeam(context, { uuid }) {
    return gqMutation('DELETE_TEAM', { uuid })
      .then(data => data);
  },

  clearTeam(context) {
    context.commit(types.CLEAR_TEAM);
  },

  clearTeams(context) {
    context.commit(types.CLEAR_TEAMS);
  },

  getOneProject({ commit }, { uuid }) {
    return gqQuery('fetchProject', { uuid })
      .then(({ fetchProject }) => commit('SET_ONE_PROJECT', fetchProject));
  },

  getProjects({ commit }, payload) {
    return gqQuery('fetchProjects', {
      ownerType: payload.ownerType,
      ownerUuid: payload.ownerUuid,
      userUuid: payload.userUuid,
      key: payload.key,
    })
      .then(({ fetchProjects }) => commit('SET_PROJECTS', fetchProjects));
  },

  inviteToOrganization({ commit }, payload) {
    return gqMutation('UPDATE_ORGANIZATION_MEMBERS', {
      members: payload.members,
      organizationUuid: payload.orgUuid,
    })
      .then(({ updateOrganizationMembers }) => commit(
        'SET_ORGANIZATION_MEMBERS',
        updateOrganizationMembers,
      ));
  },
  fetchOrganizationInvites({ commit }, { organizationUuid }) {
    return gqQuery('fetchOrganizationInvites', {
      organizationUuid,
    })
      .then(({ fetchOrganizationInvites }) => commit('SET_ORGANIZATION_INVITES', fetchOrganizationInvites));
  },
  createOrganizationInvite({ commit }, { organizationUuid, emails }) {
    return gqMutation('CREATE_ORGANIZATION_INVITE', {
      organizationUuid,
      emails,
    })
      .then(({ createOrganizationInvite }) => commit('SET_ORGANIZATION_INVITES', createOrganizationInvite));
  },

  deleteOrganizationMember(context, { organizationUuid, memberUuid }) {
    return gqMutation('DELETE_ORGANIZATION_MEMBER', {
      organizationUuid,
      memberUuid,
    })
      .then(({ deleteOrganizationMember }) => deleteOrganizationMember);
  },

  acceptOrganizationInvite(context, { token }) {
    return gqMutation('ACCEPT_ORGANIZATION_INVITE', {
      token,
    })
      .then(({ acceptOrganizationInvite }) => acceptOrganizationInvite);
  },

  deleteOrganizationInvite({ commit }, { uuid }) {
    return gqMutation('DELETE_ORGANIZATION_INVITE', {
      uuid,
    })
      .then(({ deleteOrganizationInvite }) => commit('DELETE_ORGANIZATION_INVITE', deleteOrganizationInvite));
  },

  createProject(context, { project }) {
    return gqMutation('CREATE_PROJECT', { project })
      .then(({ data }) => data);
  },

  updateProject(context, { project }) {
    return gqMutation('UPDATE_PROJECT', { project })
      .then(({ data }) => data);
  },

  deleteProject(context, { uuid }) {
    return gqMutation('DELETE_PROJECT', { uuid })
      .then(data => data);
  },

  clearProject(context) {
    context.commit(types.CLEAR_PROJECT);
  },

  clearProjects(context) {
    context.commit(types.CLEAR_PROJECTS);
  },

  searchAllUsers({ commit }, { queryString }) {
    return gqQuery('searchAllUsers', {
      queryString,
    })
      .then(({ searchAllUsers }) => {
        commit(types.SET_ALL_USERS, searchAllUsers);
      });
  },

  getOneOrganization({ commit }, { uuid }) {
    return gqQuery('fetchOrganization', { uuid })
      .then(({ fetchOrganization }) => commit('SET_ONE_ORGANIZATION', fetchOrganization));
  },

  createOrganization({ commit }, { organization, userUuid }) {
    return gqMutation('CREATE_ORGANIZATION', {
      organization,
      userUuid,
    })
      .then(({ createOrganization }) => commit('UPDATE_USER_ORGANIZATIONS', createOrganization));
  },

  updateOrganization({ commit }, { uuid, organization }) {
    return gqMutation('UPDATE_ORGANIZATION', {
      uuid,
      organization,
    })
      .then(({ updateOrganization }) => commit('SET_ONE_ORGANIZATION', updateOrganization));
  },

  searchOrganizationMembers({ commit }, payload) {
    return gqQuery('searchOrganizationMembers', {
      queryString: payload.queryString,
      organizationUuid: payload.orgUuid,
    })
      .then(({ searchOrganizationMembers }) => commit(
        'SET_ORGANIZATION_MEMBERS',
        searchOrganizationMembers,
      ));
  },

  getOrganizationMembers({ commit }, payload) {
    return gqQuery('fetchOrganizationMembers', {
      organizationUuid: payload.orgUuid,
    })
      .then(({ fetchOrganizationMembers }) => commit(
        'SET_ORGANIZATION_MEMBERS',
        fetchOrganizationMembers,
      ));
  },

  clearOrganization(context) {
    context.commit(types.CLEAR_ORGANIZATION);
  },

  clearOrganizationMembers(context) {
    context.commit(types.CLEAR_ORGANIZATION_MEMBERS);
  },

  getClients({ commit }, payload) {
    return gqQuery('fetchClients', {
      organizationUuid: payload.orgUuid,
    })
      .then(({ fetchClients }) => commit('SET_CLIENTS', fetchClients));
  },

  createClient(context, { client, contact }) {
    return gqMutation('CREATE_CLIENT', {
      client,
      contact,
    });
  },

  updateClient(context, { client, contact }) {
    return gqMutation('UPDATE_CLIENT', {
      client,
      contact,
    });
  },

  deleteClient(context, payload) {
    return gqMutation('DELETE_CLIENT', {
      clientUuid: payload.clientUuid,
      contactUuid: payload.contactUuid,
    });
  },

  getOneClient({ commit }, { uuid }) {
    return gqQuery('fetchClient', {
      uuid,
    })
      .then(({
        fetchClient,
      }) => commit('SET_ONE_CLIENT', fetchClient));
  },

  clearClient(context) {
    context.commit(types.CLEAR_CLIENT);
  },

  login(context, { user }) {
    return gqMutation('LOGIN_USER', { email: user.email, password: user.password })
      .then(({ loginUser }) => loginUser);
  },

  createUser(context, { user }) {
    return gqMutation('CREATE_USER', { user })
      .then(data => data);
  },

  verifyEmail(context, { verificationCode }) {
    return gqMutation('VERIFY_EMAIL', {
      verificationCode,
    })
      .then(data => data)
      .catch(reject => reject);
  },

  logout() {
    localStorage.clear();
  },

  startLoading({ commit }) {
    commit('START_LOADING');
  },

  stopLoading({ commit }) {
    commit('STOP_LOADING');
  },
};


text:
title: "Happy couple sitting on the grass"
excerpt: "PaperFaces portrait of Kyle and Bridget drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-kyle-bridget-lg.jpg
  thumb: paperfaces-kyle-bridget-150.jpg
tags: [portrait, illustration, Paper by 53, time lapse]
---

PaperFaces portrait of project donator Kyle and Bridget.

{% include boilerplate/paperfaces.html %}

<iframe width="560" height="315" src="https://www.youtube.com/embed/wWHJPy9FIhA" frameborder="0"> </iframe>


text:
PACKAGESERVER="https://distributor.measure-it.net/api/upload/"
SYMBOLSERVER="https://distributor.measure-it.net/api/upload_debug_symbols/"

if [ $# -ne 2 ]; then
	echo "Usage: $0 <branch> <distribution>"
	exit 1
fi

BRANCH=$1
DISTRO=$2

cd `dirname $0`
cd ..

# Check whether the distributor wants this upload or not
HTTP_CODE=$(curl -s -o /dev/null -w \"%{http_code}\" $PACKAGESERVER?branch=$BRANCH&channel=$DISTRO)
if [ "$HTTP_CODE" != "\"200\"" ]; then
	echo "Branch $BRANCH not wanted by the server: $HTTP_CODE"
	exit 0
fi

if [ "$OS" == "Windows_NT" ]; then
	cd setup
	cd Output

	for file in *.exe; do
		echo "Uploading $file"

		curl --form package=@$file --form channel=$DISTRO --form branch=$BRANCH $PACKAGESERVER
	done
else
	cd ..
	cd build || true

	symbols_file="$(find . -type f -name 'glimpse_*-dbg.tar.gz')"
	curl --form debug_symbols=@$symbols_file $SYMBOLSERVER

	# Upload each file to the distributor server
	for file in *.deb *.rpm *.tar.xz *.apk *.exe *.dmg; do
		if [ -e $file ]; then
			echo "Uploading $file"

			curl --form package=@$file --form channel=$DISTRO --form branch=$BRANCH $PACKAGESERVER
		fi
	done
fi


text:
Imports MySql.Data
Imports MySql.Data.MySqlClient

Public Class formlaporretur
    Dim clasq As New publicQuery
    Dim clasg As New gridQueries
    Dim clasgrid As New setDefaultGrid
    Dim clasc As New autoComplete
    Dim dt As DataTable
    Dim dr As MySqlDataReader
    Dim param As String = ""
    Dim param1 As String = ""
    Dim kueri As String = ""
    Private Sub formlaporretur_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        loadSize()
    End Sub
    Private Sub loadcom()

        For Each a As String In clasc.retComplete(kueri)
            txnama.AutoCompleteCustomSource.Add(a)
        Next
    End Sub
    Private Sub loadSize()
        dt = clasgrid.setSize()
        dGridSize.DataSource = dt
        dGridSize.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
        dGridSize.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    End Sub
    Private Sub loadGrid()
        Dim tempdt1, tempdt2 As DataTable
        tempdt1 = clasg.loadFilteredDataTable("select a.kodeItem as ItemCode, b.nama,b.color, b.kodeSize as Kode ,a.qty as qtyTotal, b.hargaPokok, b.hargaJual, b.status" & _
                                              " from tb_produk b, tb_returndetail a where a.kodeitem=b.kodeitem and b.status <> '' group by a.kodeitem")

        tempdt2 = clasg.loadFilteredDataTable("SELECT kodeitem,value,sum(qty) as qty from tb_returndetail inner join tb_return" & _
                                              " on tb_returndetail.kode = tb_return.kode " & param & _
                                              " group by kodeitem,value ")
        dt = clasgrid.loadFilterData(tempdt1, tempdt2, "Kode", "")

        'MsgBox(dt(0)(0))
        For a As Integer = 0 To dt.Rows.Count - 1
            Dim cek As Boolean = False
            If dGridAll.Rows.Count = 0 Then
                initGrid(dt(a))
                rowTotalUpdate(dt(a), "0")
            Else
                For x As Integer = 0 To dGridAll.Rows.Count - 1
                    If dGridAll.Rows(x).Cells(0).Value = dt(a)(0).ToString Then
                        rowTotalUpdate(dt(a), x)
                        cek = True
                    End If
                Next
                If cek = False Then
                    initGrid(dt(a))
                    rowTotalUpdate(dt(a), dGridAll.Rows.Count - 1)
                End If
            End If
        Next

    End Sub
    Private Sub initGrid(dr As DataRow)
        Dim rows As String() = {dr(0).ToString, dr(1).ToString, dr(2).ToString, dr(3).ToString, _
                                    "0", "0", "0", "0", "0", "0", "0", "0", "0", dr(14).ToString, "0", "0"}
        dGridAll.Rows.Add(rows)

        ' txGrandtotal1.Visible = False
        'txGrandtotal2.Visible = True

    End Sub
    Private Sub rowTotalUpdate(value As DataRow, row As String)
        Dim subtotal As Integer = 0
        Dim suntotalformat As Integer

        For x As Integer = 4 To 11
            dGridAll.Rows(row).Cells(x).Value = (Integer.Parse(dGridAll.Rows(row).Cells(x).Value) + Integer.Parse(value(x))).ToString
            '(Integer.Parse(dGridAll.Rows(row).Cells(3 + b).Value) + Integer.Parse(value(0)(b + 3))).ToString
            subtotal += Integer.Parse(dGridAll.Rows(row).Cells(x).Value)
        Next
        dGridAll.Rows(row).Cells(12).Value = Format(subtotal, "#,#0.00")
        suntotalformat = (Integer.Parse(dGridAll.Rows(row).Cells(13).Value) * subtotal)
        dGridAll.Rows(row).Cells(14).Value = Format(suntotalformat, "#,#0.00")

        updateGrand()
    End Sub
    Private Sub updateGrand()
        'MsgBox(DataGridView1.Rows(0).Cells(1).Value)
        DataGridView1.Rows.Clear()
        DataGridView1.Rows.Insert(0, "", "0", "0", "0", "0", "0", "0", "0", "0")
        DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
        DataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

        For b As Integer = 1 To 8
            Dim gt1 As Double = 0
            Dim gt2 As Double = 0
            Dim gt3 As Double = 0
            For a As Integer = 0 To dGridAll.Rows.Count - 1
                gt1 += Double.Parse(dGridAll.Rows(a).Cells(b + 3).Value)
                gt2 += Double.Parse(dGridAll.Rows(a).Cells(12).Value)
                gt3 += Double.Parse(dGridAll.Rows(a).Cells(14).Value)
            Next
            DataGridView1.Rows(0).Cells(b).Value = gt1.ToString
            txtotQty.Text = Format(gt2, "#,#0.00")
            '   If Label2.Text = "Penjualan Toko" Or Label2.Text = "Pengiriman" Then
            txGrandtotal1.Text = Format(gt3, "#,#0.00")
            'Else
            'txGrandtotal1.Text = gt3.ToString
            'End If
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim tanggal As DateTime = DateTimePicker1.Value.Date
        Dim tanggal1 As DateTime = DateTimePicker2.Value.Date
        If cbfaktur.Checked = True Then
            param = " where tb_returndetail.kode = '" & txfaktur.Text & "'"
        ElseIf cbkategori.Checked = True Then
            If cmbcatjual.Text = "" Then
                MsgBox("Nama Toko Masih Kosong")
            Else
                param = " where tb_return.status = '" & cmbcatjual.Text & "' and tb_return.nama = '" & txnama.Text & "' and " & _
                    "tgl between '" & tanggal.ToMySql & "' and '" & tanggal1.Year & "-" & _
                    tanggal1.Month & "-" & tanggal1.Day & " 23:59:59' "
            End If
        End If
        dGridAll.Rows.Clear()
        loadGrid()
    End Sub

    Private Sub cmbcatjual_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbcatjual.SelectedIndexChanged
        If cmbcatjual.SelectedItem = "Store" Then
            lblnama.Text = "Store"
            kueri = "select namatoko from tb_stores"
            loadcom()

        Else
            lblnama.Text = "Warehouse"
            kueri = "select namagarmen from tb_garment"
            loadcom()

        End If
    End Sub

    Private Sub PrintToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PrintToolStripMenuItem.Click
        Print()
    End Sub
    Private Sub print()
        Dim tgl As String = Now.ToShortDateString
        Dim dt As New DataTable
        Dim dt2 As New DataTable
        Dim rpt As New rpttrans
        Dim rpt1 As New rptkirim
        Dim rpt2 As New rptukuran
        Dim kategori As String = Me.Text
        With dt
            .Columns.Add("tanggal")
            .Columns.Add("bill")
            .Columns.Add("nama") 'nama garmen / toko
            .Columns.Add("kategori")
            .Columns.Add("statretur")
            .Columns.Add("kode")
            .Columns.Add("produk")
            .Columns.Add("warna")
            .Columns.Add("size")
            .Columns.Add("s1")
            .Columns.Add("s2")
            .Columns.Add("s3")
            .Columns.Add("s4")
            .Columns.Add("s5")
            .Columns.Add("s6")
            .Columns.Add("s7")
            .Columns.Add("s8")
            .Columns.Add("ttlqty")
            .Columns.Add("hrg")
            .Columns.Add("cons")
            .Columns.Add("total")
            .Columns.Add("tot1")
            .Columns.Add("tot2")
            .Columns.Add("tot3")
            .Columns.Add("tot4")
            .Columns.Add("tot5")
            .Columns.Add("tot6")
            .Columns.Add("tot7")
            .Columns.Add("tot8")
            .Columns.Add("totqty")
            .Columns.Add("grand")
        End With

        With dt2
            .Columns.Add("s1")
            .Columns.Add("s2")
            .Columns.Add("s3")
            .Columns.Add("s4")
            .Columns.Add("s5")
            .Columns.Add("s6")
            .Columns.Add("s7")
            .Columns.Add("s8")
        End With

        For Each dr As DataGridViewRow In Me.dGridAll.Rows
            dt.Rows.Add(tgl, txfaktur.Text, txnama.Text, kategori, txnama.Text, dr.Cells(0).Value, dr.Cells(1).Value, dr.Cells(2).Value, _
                        dr.Cells(3).Value, dr.Cells(4).Value, dr.Cells(5).Value, dr.Cells(6).Value, dr.Cells(7).Value, dr.Cells(8).Value, dr.Cells(9).Value, _
                        dr.Cells(10).Value, dr.Cells(11).Value, dr.Cells(12).Value, dr.Cells(13).Value, dr.Cells(14).Value, dr.Cells(15).Value, _
                        DataGridView1.Rows(0).Cells(1).Value, DataGridView1.Rows(0).Cells(2).Value, DataGridView1.Rows(0).Cells(3).Value, _
                        DataGridView1.Rows(0).Cells(4).Value, DataGridView1.Rows(0).Cells(5).Value, DataGridView1.Rows(0).Cells(6).Value, _
                        DataGridView1.Rows(0).Cells(7).Value, DataGridView1.Rows(0).Cells(8).Value, txtotQty.Text, txGrandtotal1.Text)
        Next
        For Each dr2 As DataGridViewRow In Me.dGridSize.Rows
            dt2.Rows.Add(dr2.Cells(1).Value, dr2.Cells(2).Value, dr2.Cells(3).Value, dr2.Cells(4).Value, dr2.Cells(5).Value, _
            dr2.Cells(6).Value, dr2.Cells(7).Value, dr2.Cells(8).Value)
        Next

            rpt.SetDataSource(dt)
            'rpt2.SetDataSource(dt2)
            rpt.Subreports("rptukuran.rpt").SetDataSource(dt2)
            viewreport.CrystalReportViewer1.ReportSource = rpt

        viewreport.ShowDialog()

    End Sub
End Class


text:
module Fog
  module Parsers
    module AWS
      module Elasticache
        require 'fog/aws/parsers/elasticache/base'

        class ParameterGroupParser < Base
          def reset
            super
            reset_parameter_group
          end

          def reset_parameter_group
            @parameter_group = {}
          end

          def end_element(name)
            case name
            when 'Description', 'CacheParameterGroupName', 'CacheParameterGroupFamily'
              @parameter_group[name] = value
            else
              super
            end
          end
        end
      end
    end
  end
end


text:
import hammerhead from '../deps/hammerhead';
import delay from './delay';
import * as domUtils from './dom';

const Promise       = hammerhead.Promise;
const nativeMethods = hammerhead.nativeMethods;
const listeners     = hammerhead.eventSandbox.listeners;

export const RECORDING_LISTENED_EVENTS = [
    'click', 'mousedown', 'mouseup', 'dblclick', 'contextmenu', 'mousemove', 'mouseover', 'mouseout',
    'touchstart', 'touchmove', 'touchend', 'keydown', 'keypress', 'input', 'keyup', 'change', 'focus', 'blur',
    'MSPointerDown', 'MSPointerMove', 'MSPointerOver', 'MSPointerOut', 'MSPointerUp', 'pointerdown',
    'pointermove', 'pointerover', 'pointerout', 'pointerup'];

// Imported form the hammerhead
export const BUTTON            = hammerhead.utils.event.BUTTON;
export const BUTTONS_PARAMETER = hammerhead.utils.event.BUTTONS_PARAMETER;
export const DOM_EVENTS        = hammerhead.utils.event.DOM_EVENTS;
export const WHICH_PARAMETER   = hammerhead.utils.event.WHICH_PARAMETER;

export const preventDefault = hammerhead.utils.event.preventDefault;

export function bind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowAddEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.addEventListener.call(el, event, handler, useCapture);
}

export function unbind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowRemoveEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.removeEventListener.call(el, event, handler, useCapture);
}

// Document ready
const waitForDomContentLoaded = () => {
    // NOTE: We can't use a regular Promise here, because window.load event can happen in the same event loop pass
    // The default Promise will call resolve handlers in the next pass, and load event will be lost.
    const resolveHandlers = [];

    function createPromiseResolver (resolveHandler) {
        return new Promise(resolve => resolveHandlers.push(() => resolve(resolveHandler())));
    }

    let isReady = false;

    function ready () {
        if (isReady)
            return;

        if (!document.body) {
            nativeMethods.setTimeout.call(window, ready, 1);
            return;
        }

        isReady = true;

        resolveHandlers.forEach(handler => handler());
    }

    function onContentLoaded () {
        if (!domUtils.isIFrameWindowInDOM(window) && !domUtils.isTopWindow(window))
            return;

        unbind(document, 'DOMContentLoaded', onContentLoaded);
        ready();
    }

    if (document.readyState === 'complete')
        nativeMethods.setTimeout.call(window, onContentLoaded, 1);
    else
        bind(document, 'DOMContentLoaded', onContentLoaded);

    return { then: handler => createPromiseResolver(handler) };
};

const waitForWindowLoad = () => new Promise(resolve => bind(window, 'load', resolve));

export function documentReady (pageLoadTimeout = 0) {
    return waitForDomContentLoaded()
        .then(() => {
            if (!listeners.getEventListeners(window, 'load').length)
                return null;

            return Promise.race([waitForWindowLoad(), delay(pageLoadTimeout)]);
        });
}


text:
<?php

namespace MwBundle\Report;

use AppBundle\Report\AbstractReport;
use AppBundle\Report\Grid;
use InloopBundle\Entity\Locatie;
use MwBundle\Service\VerslagDao;

class ZonderZorg extends AbstractReport
{

    protected $title = 'Zonder zorg';

    protected $xPath = 'type';

    protected $yPath = 'label';

//    protected $nPath = 'aantal';

    protected $columns = [
        'Klanten'=>'numContacten',
        ];

    protected $yDescription = 'Aantal contacten';

    protected $zonderzorg_locaties = [];

    protected $tables = [];

    /**
     * @var Locatie
     */
    private $locatie;

    public function __construct(VerslagDao $dao, $zonderzorg_locaties)
    {
        $this->zonderzorg_locaties = $zonderzorg_locaties;
        $this->dao = $dao;
    }

    public function setFilter(array $filter)
    {
        if (array_key_exists('startdatum', $filter)) {
            $this->startDate = $filter['startdatum'];
        }

        if (array_key_exists('einddatum', $filter)) {
            $this->endDate = $filter['einddatum'];
        }

        return $this;
    }

    protected function init()
    {
        $result = $this->dao->countKlantenZonderZorg($this->startDate, $this->endDate, $this->zonderzorg_locaties);
//        $sql = $this->getFullSQL($query);
        $rows = $result->fetchAllAssociative();
//        foreach($rows as $row)
//        {
//
//            $d[] = ['Aantal'=> $row['numContacten']];
//        }
        $this->result = $rows;

    }

    protected function build()
    {

        $table = new Grid($this->result, $this->columns,$this->yPath);
        $table
            ->setStartDate($this->startDate)
            ->setEndDate($this->endDate)
            ->setYSort(false)
            ->setYTotals(true)
        ;
         $report = [
            'title' => 'Zonder zorg (face-to-face)',
            'xDescription' => $this->xDescription,
            'yDescription' => $this->yDescription,
            'data' => $table->render(),
        ];

        $this->reports[] = $report;
    }
}


text:
Cannery is a client-side and / or server-side ORM for JavaScript that is designed to abstract away the complexities of complex relationships, data fetching, caching, cache invalidation and managing data-sources.

Cannery builds up a tree of related models that can be accessed through their relationships to other models. Cannery is completely synchronous by design, which means you can query all of your data without worrying whether or not it has been fetched yet. Internally, Cannery will check if the model has been fetched yet on demand and trigger an change event that bubbles up to the root of your models once the data is available.

## Table Of Contents
* What Is Cannery?
    * [Data Source Agnostic](#data-source-agnostic)
    * [Asynchronous](#asynchronous)
    * [Predictable](#predictable)
* What Isn't Cannery?
    * [A Framework](#a-framework)
    * [An App State Container](#an-app-state-container)
    * [Purely Functional](#purely-functional)

## What Is Cannery?

#### Data Source Agnostic

95% of your Cannery code will not be aware where the data is coming from or where it is going. You can provide an adapter on a per-application or even per-model basis that handles all of the interactions with whatever datasource you are interacting with.

Your models, and your components will never know or care what the datasource is, so you can easily switch it out if you need to.

**[⬆ back to top](#table-of-contents)**

#### Asynchronous

There are no callbacks or promises, you just render your tree of data. When new data comes in, a change event will be triggered so you can re-render the tree. This makes Cannery much easier to reason about.

**[⬆ back to top](#table-of-contents)**

#### Predictable

You can get all of your models by their complex relationships. As long as your models are defined, every object, array and simple data type will be stubbed out so you can proactively render data before it arrives without needing to check whether objects or arrays are there.

**[⬆ back to top](#table-of-contents)**

## What Isn't Cannery?

#### A Framework

Cannery is not a full framework. It is only an answer to managing data relationships and synchronizing data with a backend (whether that be a REST API, a database or something else.)

**[⬆ back to top](#table-of-contents)**

#### An App State Container

Cannery is not a place to store your app state. While it can be used for that if you create an adapter that writes to memory or even sessionStorage, setting up models and relationships is a little tedious because you have to declare a type for everything you will be storing. If you need to keep app state, we recommend supplementing Cannery with something like [Redux](http://redux.js.org). It won't hurt our feelings if you don't use Cannery for everything you do.

**[⬆ back to top](#table-of-contents)**

#### Purely Functional

Cannery takes an object oriented approach to most of what it is doing behind the scenes. It turns out that it was much easier to create models with rich relationships and easy inheritance using classical inheritance. One place this will show through is when you create your models, you will use the ES2015 `class` syntax.

Once you are working in your components, however, you will barely notice you are working with classes. Most apps will just require you to use the `new` keyword once at the root of your app. From that point on, you'll feel like you're writing functional code.

**[⬆ back to top](#table-of-contents)**


text:
Ionic Chat App using Sails as backend

## How to run

### Requirements
- [Node](nodejs.org)
- [Sails](http://sailsjs.org/)
- [MongoDB](https://www.mongodb.org/)

### Server
- Install server dependencies `npm install`
- Run MongoDB `mongod`
- Run Sails `sails lift`

### App
- Install app dependencies `npm install` and `bower install`
- Run app on browser `ionic serve`


text:
'use strict';
const mongoose = require('mongoose');
//used to delete the database
const deleteDb = () => {
  return mongoose.connection.db.dropDatabase();
};
module.exports = {deleteDb};