text:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;

namespace Vestris.ResourceLib
{
    /// <summary>
    /// This structure depicts the organization of data in a hardware-independent icon resource.
    /// </summary>
    internal class DirectoryResource<ImageResourceType> : Resource
        where ImageResourceType : IconImageResource, new()
    {
        internal Kernel32.GRPICONDIR _header = new Kernel32.GRPICONDIR();
        List<ImageResourceType> _icons = new List<ImageResourceType>();

        /// <summary>
        /// Returns the type of the resource in this group.
        /// </summary>
        internal Kernel32.ResourceTypes ResourceType
        {
            get
            {
                switch (_header.wType)
                {
                    case 1:
                        return Kernel32.ResourceTypes.RT_ICON;
                    case 2:
                        return Kernel32.ResourceTypes.RT_CURSOR;
                    default:
                        throw new NotSupportedException();
                }
            }
        }

        /// <summary>
        /// Icons contained in this hardware-independent icon resource.
        /// </summary>
        internal List<ImageResourceType> Icons
        {
            get
            {
                return _icons;
            }
            set
            {
                _icons = value;
            }
        }

        /// <summary>
        /// A hardware-independent icon resource.
        /// </summary>
        /// <param name="hModule">Module handle.</param>
        /// <param name="hResource">Resource ID.</param>
        /// <param name="type">Resource type.</param>
        /// <param name="name">Resource name.</param>
        /// <param name="language">Language ID.</param>
        /// <param name="size">Resource size.</param>
        internal DirectoryResource(IntPtr hModule, IntPtr hResource, ResourceId type, ResourceId name, UInt16 language, int size)
            : base(hModule, hResource, type, name, language, size)
        {

        }

        /// <summary>
        /// A new hardware-independent icon resource.
        /// </summary>
        internal DirectoryResource(Kernel32.ResourceTypes resourceType)
            : base(IntPtr.Zero,
                IntPtr.Zero,
                new ResourceId(resourceType),
                new ResourceId(1),
                ResourceUtil.NEUTRALLANGID,
                Marshal.SizeOf(typeof(Kernel32.GRPICONDIR)))
        {
            switch(resourceType)
            {
                case Kernel32.ResourceTypes.RT_GROUP_CURSOR:
                    _header.wType = 2;
                    break;
                case Kernel32.ResourceTypes.RT_GROUP_ICON:
                    _header.wType = 1;
                    break;
                default:
                    throw new NotSupportedException();
            }
        }

        /// <summary>
        /// Save a hardware-independent icon resource to an executable file.
        /// </summary>
        /// <param name="filename">Name of an executable file (.exe or .dll).</param>
        internal override void SaveTo(string filename)
        {
            base.SaveTo(filename);

            foreach (ImageResourceType icon in _icons)
            {
                icon.SaveIconTo(filename);
            }
        }

        /// <summary>
        /// Read a hardware-independent icon resource from a loaded module.
        /// </summary>
        /// <param name="hModule">Loaded executable module.</param>
        /// <param name="lpRes">Pointer to the beginning of a hardware-independent icon resource.</param>
        /// <returns>Pointer to the end of the hardware-independent icon resource.</returns>
        internal override IntPtr Read(IntPtr hModule, IntPtr lpRes)
        {
            _icons.Clear();

            _header = (Kernel32.GRPICONDIR)Marshal.PtrToStructure(
                lpRes, typeof(Kernel32.GRPICONDIR));

            IntPtr pEntry = new IntPtr(lpRes.ToInt32() + Marshal.SizeOf(_header));

            for (UInt16 i = 0; i < _header.wImageCount; i++)
            {
                ImageResourceType iconImageResource = new ImageResourceType();
                pEntry = iconImageResource.Read(hModule, pEntry);
                _icons.Add(iconImageResource);
            }

            return pEntry;
        }

        /// <summary>
        /// Write a hardware-independent icon resource to a binary stream.
        /// </summary>
        /// <param name="w">Binary stream.</param>
        internal override void Write(BinaryWriter w)
        {
            w.Write((UInt16)_header.wReserved);
            w.Write((UInt16)_header.wType);
            w.Write((UInt16)_icons.Count);
            ResourceUtil.PadToWORD(w);
            foreach (ImageResourceType icon in _icons)
            {
                icon.Write(w);
            }
        }
    }
}


text:
//
//  GDRSImageCache.h
//  GADRSImageCache
//
//  Created by Gabriel Radu on 17/04/2014.
//  Copyright (c) 2014 Gabriel Adrian Radu. All rights reserved.
//

#import "UIImage+GDRSResizing.h"

/**
 *  Callback which transforms an image to another image. It is normally
 *  used to filter the image fetched over the network into one that is
 *  cached.
 *
 *  @param sourceImage The source image.
 *
 *  @return The filtered (transformed) image.
 */
typedef UIImage*(^GDRSImageCacheImageFilter)(UIImage *sourceImage);

/**
 *  Callback called when an image has been fetched.
 *
 *  @param image The image fetched and some time processed (e.g.
 *               through a filter).
 *  @param error Points to an error if one has occurred during fetching
 *               otherwise nil.
 */
typedef void(^GDRSImageCacheFetchCompletionHandler)(UIImage *image, NSError *error);

/**
 *  Memory based cache for UIImage objects.
 *
 *  A typical usage example of this class is:
 *  @code
         UIImageView *anImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];

         // create the cache
         GDRSImageCache *cache = [[GDRSImageCache alloc] initWithCachedImageFilter:^UIImage *(UIImage *sourceImage) {

             // resize the image to the image view size and round the image corners;
             // this is called by the cache on a background thread
             return [sourceImage gdrs_resizedImageToAspectFitSize:anImageView.bounds.size cornerRadius:10];

         }];

         // set the default image, which will be returned from
         // fetchImageWithURL:completionHandler: if an image coresponding to the
         // requested url is not cached yet.
         cache.defaultImage = [UIImage imageNamed:<#place holder image name#>];

         NSURL *imageUrl = <#an url to a image#>;

         // fetch an image; the call returns imidiatly and the callback handler
         // is called when the image is fetched over the network
         anImageView.image = [cache fetchImageWithURL:imageUrl completionHandler:^(UIImage *image, NSError *error) {
             anImageView.image = image;
         }];
 *  @endcode
 */
@interface GDRSImageCache : NSObject

/**
 *  Temporary image which is returned for convenience when the requested
 *  image is not found in the cache. This image can be used until the
 *  requested image is fetched over the network.
 */
@property (nonatomic) UIImage *defaultImage;

/**
 *  Filter applied strait after the image has been fetch. Usually such a
 *  filter is used to resize the image in order to fit the a certain
 *  UIImageView. This filter is called on a background thread before the
 *  image is cached.
 */
@property (nonatomic, readonly, copy) GDRSImageCacheImageFilter imageFilter;

/**
 *  Initializes the cache with an image filter.
 *
 *  @param imageFilter Filter applied strait after the image has been fetch.
 *                     Usually such a filter is used to resize the image in
 *                     order to fit the a certain UIImageView. This filter is
 *                     called on a background thread before the image is cached.
 *
 *  @return The initialized instance.
 */
- (instancetype)initWithCachedImageFilter:(GDRSImageCacheImageFilter)imageFilter;

/**
 *  Initiates an image fetch over the network and returns the cached image if
 *  one is already cached, or the defaultImage if a cached image is not found.
 *
 *  @param imageURL          The url where the image must be fetched from.
 *  @param completionHandler Called when the image has been fetched. It is not
 *                           called back if the image is not fetched from over
 *                           the network for some reason.
 *
 *  @return The cached image or the defaultImage if the image has not been
 *          cached yet.
 */
- (UIImage *)fetchImageWithURL:(NSURL *)imageURL completionHandler:(GDRSImageCacheFetchCompletionHandler)completionHandler;

@end

redpajama_set_name: RedPajamaGithub


text:
const extend = require('deep-extend')

function addAuthorData (files = {}, context) {
  extend(files.pkg, {
    author: {
      name: context.props.projectauthor,
      email: context.props.projectmail,
      url: context.props.projecturl
    }
  })
}

module.exports = addAuthorData


text:
-- Add/modify columns
alter table INSTRUCTIONAL_OFFERING add external_uid varchar2(40);
alter table CLASS_ add external_uid varchar2(40);
/*
 * Update database version
 */

update application_config set value='21' where name='tmtbl.db.version';

commit;


text:
package jacoblo.dataStructure;

import jacoblo.dataStructure.UnionFind.UnionFind;
import jacoblo.dataStructure.UnionFind.UnionFindVertex;
import org.junit.jupiter.api.Test;

public class UnionFindTest {
  @Test
  void testUnionFind() {
    UnionFindVertex<Integer> au = new UnionFindVertex("a",0,0);
    UnionFindVertex<Integer> bu = new UnionFindVertex("b",0,1);
    UnionFindVertex<Integer> cu = new UnionFindVertex("c",1,1);
    UnionFindVertex<Integer> du = new UnionFindVertex("d",1,0);
    UnionFindVertex<Integer> eu = new UnionFindVertex("e",2,2);

    UnionFind.union(au, bu);
    UnionFind.union(cu, du);
    UnionFind.union(au, eu);
    UnionFind.union(au, cu);

    System.out.println(au.equals(bu));

    System.out.println(au);
    System.out.println(bu);
    System.out.println(cu);
    System.out.println(du);
    System.out.println(eu);
  }

}


text:
package com.onplan.persistence;

import com.onplan.domain.persistent.AlertEventHistory;

public interface AlertEventHistoryDao extends GenericDao<AlertEventHistory> {
}


text:
package info.monitorenter.cpdetector.io;

import info.monitorenter.cpdetector.util.collections.ITreeNode;
import info.monitorenter.cpdetector.util.collections.TreeNodeUniqueChildren;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * A jar file that pretends to be a simple file by extending {@link java.io.File}.
 *

 *
 * @author Achim Westermann
 *
 */
public class JarArchive extends File {

    protected JarFile jar;

    protected Set childs = new TreeSet();

    /**
     * @param pathname
     * @throws java.io.IOException
     */
    public JarArchive(String pathname)
    throws IOException {

        super(pathname);
        this.jar = new JarFile(pathname);
        ITreeNode root = this.parseTree();
        System.out.println("tree:");
        System.out.println(root.toString() + '\n');
        this.buildTree(root, this);
    }

    /**
     * Only for the subclass to avoid double-parsing.
     */
    private JarArchive(File f) {

        super(f.getAbsolutePath());
    }

    /**
     * Build a Tree from the entries.
     *
     */
    private ITreeNode parseTree() {

        ITreeNode root = new TreeNodeUniqueChildren();
        ITreeNode newnode, oldnode;
        Enumeration entries = this.jar.entries();
        String entry;
        while (entries.hasMoreElements()) {
            newnode = root;
            oldnode = root;
            entry = ((JarEntry)entries.nextElement()).getName();
            System.out.println("Entry: " + entry);
            StringTokenizer tokenizer = new StringTokenizer(entry, "/");
            while (tokenizer.hasMoreElements()) {
                String path = tokenizer.nextToken();
                newnode = new TreeNodeUniqueChildren(path);
                oldnode.addChildNode(newnode);
                oldnode = newnode;
            }
        }
        return root;
    }

    protected void buildTree(ITreeNode node, JarArchive element) throws IOException {

        List childNodes = node.getAllChildren();
        Iterator childNodesIt = childNodes.iterator();
        ITreeNode childNode;
        JarElement child;
        JarEntry entry;
        String search;
        while (childNodesIt.hasNext()) {
            childNode = (ITreeNode)childNodesIt.next();
            search = getSearchPath(childNode);
            System.out.println("Searching for: " + search);
            entry = this.jar.getJarEntry(search);
            if (entry == null) {
                System.err.println("Entry for " + search + " (" + this.jar.getName() + ")is null!!!");
            } else {
                System.out.println("Entry: " + entry.toString());
                child = new JarElement(entry, this);
                child.buildTree(childNode, this);
                this.childs.add(child);
            }

        }
        System.out.println(this + " has finished building...");
    }

    /**
     * Little helper that transforms (back) the nodes of the tree that was parsed from the entries during initialization
     * to canonical strings for entries.
     */
    private String getSearchPath(ITreeNode node) {

        List l = new LinkedList();
        node.getUserObjectPathFromRoot(l);
        Iterator it = l.iterator();
        StringBuffer ret = new StringBuffer();
        int i = 0;
        String token;
        while (it.hasNext()) {
            // avoid the "root" token.
            token = it.next().toString();
            if (i != 0) {
                ret.append(token);
                if (it.hasNext()) {
                    ret.append('/');
                }
            }

            i++;
        }
        return ret.toString();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#canRead()
     */
    public boolean canRead() {

        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#canWrite()
     */
    public boolean canWrite() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#compareTo(java.io.File)
     */
    public int compareTo(File pathname) {

        return super.compareTo(pathname);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#createNewFile()
     */
    public boolean createNewFile() throws IOException {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#delete()
     */
    public boolean delete() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#deleteOnExit()
     */
    public void deleteOnExit() {

    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {

        return super.equals(obj);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#exists()
     */
    public boolean exists() {

        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getAbsoluteFile()
     */
    public File getAbsoluteFile() {

        return super.getAbsoluteFile();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getAbsolutePath()
     */
    public String getAbsolutePath() {

        String ret = super.getAbsolutePath();
        return ret;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getCanonicalFile()
     */
    public File getCanonicalFile() throws IOException {

        return super.getCanonicalFile();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getCanonicalPath()
     */
    public String getCanonicalPath() throws IOException {

        return super.getCanonicalPath();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getName()
     */
    public String getName() {

        return super.getName();

    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getParent()
     */
    public String getParent() {

        return super.getParent();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getParentFile()
     */
    public File getParentFile() {

        return super.getParentFile();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#getPath()
     */
    public String getPath() {

        return super.getPath();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {

        return super.hashCode();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#isAbsolute()
     */
    public boolean isAbsolute() {

        return super.isAbsolute();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#isDirectory()
     */
    public boolean isDirectory() {

        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#isFile()
     */
    public boolean isFile() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#isHidden()
     */
    public boolean isHidden() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#lastModified()
     */
    public long lastModified() {

        return super.lastModified();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#length()
     */
    public long length() {

        return super.length();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#list()
     */
    public String[] list() {

        String[] ret = new String[this.childs.size()];
        Iterator it = this.childs.iterator();
        for (int i = 0; it.hasNext(); i++) {
            ret[i] = it.next().toString();
        }
        return ret;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#list(java.io.FilenameFilter)
     */
    public String[] list(FilenameFilter filter) {

        List ret = new LinkedList();
        Iterator it = this.childs.iterator();
        File next;
        while (it.hasNext()) {
            next = (File)it.next();
            if (filter.accept(next.getParentFile(), next.getName())) {
                ret.add(next.toString());
            }
        }
        return (String[])ret.toArray(new String[ret.size()]);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#listFiles()
     */
    public File[] listFiles() {

        File[] ret = new File[this.childs.size()];
        Iterator it = this.childs.iterator();
        for (int i = 0; it.hasNext(); i++) {
            ret[i] = (File)it.next();
        }
        return ret;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#listFiles(java.io.FileFilter)
     */
    public File[] listFiles(FileFilter filter) {

        List ret = new LinkedList();
        Iterator it = this.childs.iterator();
        File next;
        while (it.hasNext()) {
            next = (File)it.next();
            if (filter.accept(next)) {
                ret.add(next);
            }
        }
        return (File[])ret.toArray(new File[ret.size()]);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#listFiles(java.io.FilenameFilter)
     */
    public File[] listFiles(FilenameFilter filter) {

        List ret = new LinkedList();
        Iterator it = this.childs.iterator();
        File next;
        while (it.hasNext()) {
            next = (File)it.next();
            if (filter.accept(next.getParentFile(), next.getName())) {
                ret.add(next);
            }
        }
        return (File[])ret.toArray(new File[ret.size()]);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#mkdir()
     */
    public boolean mkdir() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#mkdirs()
     */
    public boolean mkdirs() {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#renameTo(java.io.File)
     */
    public boolean renameTo(File dest) {

        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#setLastModified(long)
     */
    public boolean setLastModified(long time) {

        return super.setLastModified(time);
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#setReadOnly()
     */
    public boolean setReadOnly() {

        return super.setReadOnly();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    public String toString() {

        return super.toString();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#toURI()
     */
    public URI toURI() {

        return super.toURI();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.io.File#toURL()
     */
    public URL toURL() throws MalformedURLException {

        return super.toURL();
    }

    class JarElement extends JarArchive {

        private File m_parent;

        private JarEntry m_entry;

        /**
         * Creates an element with the given entry and parent file.

         *
         * @param entry the contained entry.
         *
         * @param parent the parent file.
         *
         * @throws java.io.IOException if sth goes wrong.
         */
        JarElement(JarEntry entry, File parent)
        throws IOException {

            super(new File(JarArchive.this.jar.getName()));
            this.m_parent = parent;
            if (entry == null) {
                System.err.println("Entry is null.");
            }
            this.m_entry = entry;
            this.jar = JarArchive.this.jar;
        }

        /*
         * protected void buildTree(ITreeNode node,JarArchive element) throws IOException{ List childNodes =
         * node.getAllChildren(); Iterator childNodesIt = childNodes.iterator(); ITreeNode childNode; JarElement child;
         * JarEntry entry; String search; while(childNodesIt.hasNext()){ childNode = (ITreeNode)childNodesIt.next();
         * search = this.entry.getName()+"/"+childNode.getUserObject().toString(); entry = this.jar.getJarEntry(search);
         * child = new JarElement( entry, this ); this.childs.add(child); child.buildTree(childNode,this); } }
         *
         */
        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getAbsoluteFile()
         */
        public File getAbsoluteFile() {

            return this;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getAbsolutePath()
         */
        public String getAbsolutePath() {

            String prefix = JarArchive.this.jar.getName();
            String postfix = this.m_entry.getName();
            return prefix + "/" + postfix;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getName()
         */
        public String getName() {

            return this.m_entry.getName();
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getParent()
         */
        public String getParent() {

            return this.m_parent.getAbsolutePath();
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getParentFile()
         */
        public File getParentFile() {

            return this.m_parent;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#isDirectory()
         */
        public boolean isDirectory() {

            // would not work, don't know why (false, even if is a dir):
            // this.entry.isDirectory();
            return this.childs.size() != 0;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#isFile()
         */
        public boolean isFile() {

            return !this.isDirectory();
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#lastModified()
         */
        public long lastModified() {

            return this.m_entry.getTime();
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#length()
         */
        public long length() {

            return this.m_entry.getSize();
        }

        public String toString() {

            return this.m_entry.toString();
        }

        /*
         * (non-Javadoc)
         *
         * @see java.io.File#getPath()
         */
        public String getPath() {

            return this.m_entry.getName();
        }
    }

}


text:
package org.socraticgrid.hl7.services.orders.model.status;

public enum CreateStatus {

	Sucessful, NotAllowed, Failed, Invalid
}


text:
'use strict';

//Start by defining the main module and adding the module dependencies
/* jshint ignore:start */
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
/* jshint ignore:end */

// Setting HTML5 Location Mode
/* jshint ignore:start */
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
  function($locationProvider) {
    $locationProvider.hashPrefix('!');
  }
]);
/* jshint ignore:end */

//Then define the init function for starting up the application
window.auth = {};
window.auth.keycloakUrl = 'http://multivadelsur.ddns.net:8080/auth';
window.auth.keycloakRealm = 'SISTEMA_FINANCIERO';
window.auth.keycloakClientId = 'SISTCOOP_APP';
//window.auth.rrhhUrl = 'http://multivadelsur.ddns.net:8080/SISTCOOP_REST/rest';
window.auth.rrhhUrl = 'http://192.168.1.90:8080/SISTCOOP_REST/rest';

window.auth.empresa = 'MULTIVALORES DEL SUR';
window.auth.printer = 'EPSON TM-U220';

//Then define the init function for starting up the application
angular.element(document).ready(function () {
  //Fixing facebook bug with redirect
  if (window.location.hash && window.location.hash === '#_=_') {
    if (window.history && history.pushState) {
      window.history.pushState('', document.title, window.location.pathname);
    } else {
      // Prevent scrolling by storing the page's current scroll offset
      var scroll = {
        top: document.body.scrollTop,
        left: document.body.scrollLeft
      };
      window.location.hash = '';
      // Restore the scroll offset, should be flicker free
      document.body.scrollTop = scroll.top;
      document.body.scrollLeft = scroll.left;
    }
  }

  var keycloakUrl = window.auth.keycloakUrl;
  var keycloakRealm = window.auth.keycloakRealm;
  var keycloakClientId = window.auth.keycloakClientId;

  var rrhhUrl = window.auth.rrhhUrl;

  /* jshint ignore:start */
  var keycloak = new Keycloak({
    url: keycloakUrl,
    realm: keycloakRealm,
    clientId: keycloakClientId
  });
  /* jshint ignore:end */

  /* jshint ignore:start */
  keycloak.init({onLoad: 'login-required'}).success(function () {
    var sistcoop = new Sistcoop({
      url: rrhhUrl,
      authenticatedToken: keycloak.token
    });

    sistcoop.init({onLoad: 'login-required'}).success(function () {
      window.auth.authz = keycloak;
      angular.module('mean').factory('Auth', function () {
        return window.auth;
      });

      angular.module('mean').constant('REALM', {name: keycloakRealm, authServerUrl: keycloakUrl});
      angular.module('mean').constant('AGENCIA', sistcoop.agencia);
      angular.module('mean').constant('CAJA', sistcoop.caja);
      angular.module('mean').constant('PERSONA', sistcoop.persona);

      angular.module('mean').constant('EMPRESA', window.auth.empresa);
      angular.module('mean').constant('PRINTER', window.auth.printer);

      if(keycloak.realmAccess.roles.indexOf('ADMIN') !== -1) {
        //Then init the app
        angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
      } else {
        alert('Usuario no tiene el Rol ADMIN');
      }
    }).error(function () {
      alert('No se pudo verificar el origen de sucursal y agencia para el usuario');
    });
  }).error(function () {
    window.location.reload();
  });
  /* jshint ignore:end */

});

angular.module('mean').controller('KeycloakController',
  function ($scope, Auth, CAJA, AGENCIA, PERSONA) {

    $scope.logout = function () {
      Auth.authz.logout();
    };
    $scope.accountManagement = function () {
      Auth.authz.accountManagement();
    };

    $scope.user = {
      username: Auth.authz.idTokenParsed.preferred_username,
      roles: []
    };

    $scope.loadRoles = function () {
      if (!angular.isUndefined(Auth.authz.realmAccess)) {
        var realmRoles = Auth.authz.realmAccess.roles;
        for (var i = 0; i < realmRoles.length; i++) {
          $scope.user.roles.push(realmRoles[i]);
        }
      }
    };
    $scope.loadRoles();

    $scope.session = {};
    $scope.session.caja = CAJA;
    $scope.session.agencia = AGENCIA;
    $scope.session.persona = PERSONA;
  }
);

var resourceRequests = 0;
var loadingTimer = -1;

angular.module('mean').factory('authInterceptor', function ($q, Auth) {
  return {
    request: function (config) {
      if (!config.url.match(/.html$/)) {
        var deferred = $q.defer();
        if (Auth.authz.token) {
          Auth.authz.updateToken(5).success(function () {
            config.headers = config.headers || {};
            config.headers.Authorization = 'Bearer ' + Auth.authz.token;

            deferred.resolve(config);
          }).error(function () {
            location.reload();
          });
        }
        return deferred.promise;
      } else {
        return config;
      }
    }
  };
});

angular.module('mean').factory('spinnerInterceptor', function ($q, $window, $rootScope, $location) {
  return function (promise) {
    return promise.then(function (response) {
      resourceRequests--;
      if (resourceRequests === 0) {
        if (loadingTimer !== -1) {
          window.clearTimeout(loadingTimer);
          loadingTimer = -1;
        }
        //$('#loading').hide();
      }
      return response;
    }, function (response) {
      resourceRequests--;
      if (resourceRequests === 0) {
        if (loadingTimer !== -1) {
          window.clearTimeout(loadingTimer);
          loadingTimer = -1;
        }
        //$('#loading').hide();
      }
      return $q.reject(response);
    });
  };
});

angular.module('mean').factory('errorInterceptor', function ($q, $window, $rootScope, $location, Auth) {
  return function (promise) {
    return promise.then(function (response) {
      return response;
    }, function (response) {
      if (response.status === 401) {
        Auth.authz.logout();
      } else if (response.status === 403) {
        $location.path('/forbidden');
      } else if (response.status === 404) {
        $location.path('/notfound');
      } else if (response.status) {
        if (response.data && response.data.errorMessage) {
          alert(response.data.errorMessage);
        } else {
          alert.error("An unexpected server error has occurred");
        }
      }
      return $q.reject(response);
    });
  };
});

angular.module('mean').config(function ($httpProvider) {
  $httpProvider.interceptors.push('errorInterceptor');
  var spinnerFunction = function (data, headersGetter) {
    if (resourceRequests === 0) {
      loadingTimer = window.setTimeout(function () {
        //$('#loading').show();
        loadingTimer = -1;
      }, 500);
    }
    resourceRequests++;
    return data;
  };
  $httpProvider.defaults.transformRequest.push(spinnerFunction);
  $httpProvider.interceptors.push('spinnerInterceptor');
  $httpProvider.interceptors.push('authInterceptor');
});

angular.module('mean').provider('sgKeycloak', function () {

  this.restUrl = 'http://localhost';

  this.$get = function () {
    var restUrl = this.restUrl;
    return {
      getRestUrl: function () {
        return restUrl;
      }
    };
  };

  this.setRestUrl = function (restUrl) {
    this.restUrl = restUrl;
  };
});

angular.module('mean').factory('KeycloakRestangular', ['Restangular', 'sgKeycloak', function (Restangular, sgKeycloak) {
  return Restangular.withConfig(function (RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(sgKeycloak.getRestUrl());
  });
}]);

angular.module('mean').config(function ($provide, sgKeycloakProvider, REALM) {
  sgKeycloakProvider.restUrl = REALM.authServerUrl + '/admin/realms/' + REALM.name;
});

angular.module('mean').factory('SGUsuarioKeycloak', ['KeycloakRestangular', 'REALM', function (KeycloakRestangular, REALM) {

  var url = 'users';

  var modelMethos = {
    $find: function (id) {
      return KeycloakRestangular.one(url, id).get();
    },
    $search: function (queryParams) {
      return KeycloakRestangular.all(url).getList(queryParams);
    },
    $roleMappings: function (username) {
      return KeycloakRestangular.one(url + '/' + username + '/role-mappings').get();
    },
    $realmRoles: function (username) {
      return KeycloakRestangular.one(url + '/' + username + '/role-mappings/realm').get();
    },

    $getRealmLevelRoles: function () {
      return KeycloakRestangular.all('roles').getList();
    },
    $getCreateRealmUserUrl: function () {
      return REALM.authServerUrl + '/admin/' + REALM.name + '/console/#/create/user/' + REALM.name;
    }

  };

  return modelMethos;

}]);

/* jshint ignore:start */
angular.module('mean').config(['RestangularProvider', 'PRINTER',
  function (RestangularProvider, PRINTER) {
    //RestangularProvider.setBaseUrl('http://localhost:8080/SistCoopREST/rest');
    //RestangularProvider.setBaseUrl('http://multivadelsur.ddns.net:8080/SISTCOOP_REST/rest');
    RestangularProvider.setBaseUrl(window.auth.rrhhUrl);

    /*if(isLoaded()){
      findPrinter(PRINTER);
      return;
    }*/
  }
]);
/* jshint ignore:end */


text:
local M = {}
local fx = require "com.ponywolf.ponyfx"

function M.new(instance)

  if not instance then error("ERROR: Expected display object") end

  if instance.decorType == "bounce" then
    fx.bounce(instance, instance.intensity, instance.time, instance.rnd)
  elseif instance.decorType == "bounce3D" then
    fx.bounce3D(instance, instance.intensity, instance.time, instance.rnd)
  elseif instance.decorType == "breath" then
    fx.breath(instance, instance.intensity, instance.time, instance.rnd)
  elseif instance.decorType == "float" then
    fx.float(instance, instance.intensity, instance.time, instance.rnd)
  elseif instance.decorType == "sway" then
    fx.sway(instance, instance.intensity, instance.time, instance.rnd)
  elseif instance.decorType == "spin" then
    instance.rotation = 0
    transition.to (instance, {time = instance.time or 6000, rotation = 360, iterations =-1})
  end

  return instance
end

return M


text:
@implementation TOTOParagraph
-(NSString*)indentTabs
{
    NSMutableString* string = [NSMutableString string];
    for (int it=0; it<self.indent; it++) {
        [string appendString:@"\t"];
    }
    return string;
}
@end


text:
import invariant from 'invariant';
import { has } from './_';
import React from 'react';

const localePropType = React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.func
      ])

const REQUIRED_NUMBER_FORMATS = [ 'default' ];

const REQUIRED_DATE_FORMATS = [
      'default',
      'date',
      'time',
      'header',
      'footer',
      'dayOfMonth',
      'month',
      'year',
      'decade',
      'century'
    ];

function _format(localizer, formatter, value, format, culture) {
  let result = typeof format === 'function'
    ? format(value, culture, localizer)
    : formatter.call(localizer, value, format, culture)

  invariant(result == null || typeof result === 'string'
    , '`localizer format(..)` must return a string, null, or undefined')

  return result
}

function checkFormats(requiredFormats, formats){
  if( process.env.NODE_ENV !== 'production' )
    requiredFormats.forEach(
      f => invariant(has(formats, f), 'localizer missing required format: `%s`', f ))
}

let _numberLocalizer = createWrapper('NumberPicker')

export function setNumber({ format, parse, precision = () => null, formats, propType }) {
  invariant(typeof format === 'function'
    , 'number localizer `format(..)` must be a function')
  invariant(typeof parse === 'function'
    , 'number localizer `parse(..)` must be a function')

  checkFormats(REQUIRED_NUMBER_FORMATS, formats)

  _numberLocalizer = {
    formats,
    precision,
    propType: propType || localePropType,

    format(value, str, culture){
      return _format(this, format, value, str, culture)
    },

    parse(value, culture) {
      let result = parse.call(this, value, culture)
      invariant(result == null || typeof result === 'number'
        , 'number localizer `parse(..)` must return a number, null, or undefined')
      return result
    }
  }
}

let _dateLocalizer = createWrapper('DateTimePicker')

export function setDate(spec) {
  invariant(typeof spec.format === 'function'
    , 'date localizer `format(..)` must be a function')
  invariant(typeof spec.parse === 'function'
    , 'date localizer `parse(..)` must be a function')
  invariant(typeof spec.firstOfWeek === 'function'
    , 'date localizer `firstOfWeek(..)` must be a function')
  checkFormats(REQUIRED_DATE_FORMATS, spec.formats)

  _dateLocalizer = {
    formats: spec.formats,
    propType: spec.propType || localePropType,
    startOfWeek: spec.firstOfWeek,
    format(value, str, culture){
      return _format(this, spec.format, value, str, culture)
    },
    parse(value, culture) {
      let result = spec.parse.call(this, value, culture)
      invariant(result == null
        || (result instanceof Date && !isNaN(result.getTime()))
        , 'date localizer `parse(..)` must return a valid Date, null, or undefined')
      return result
    }
  }
}

export let number = {
  propType(...args){ return _numberLocalizer.propType(...args) },
  getFormat(key, format){
    return format || _numberLocalizer.formats[key]
  },
  parse(...args){
    return _numberLocalizer.parse(...args)
  },
  format(...args){
    return _numberLocalizer.format(...args)
  },
  precision(...args){
    return _numberLocalizer.precision(...args)
  }
}

export let date = {
  propType(...args){ return _dateLocalizer.propType(...args) },
  getFormat(key, format){
    return format || _dateLocalizer.formats[key]
  },
  parse(...args){
    return _dateLocalizer.parse(...args)
  },
  format(...args){
    return _dateLocalizer.format(...args)
  },
  startOfWeek(...args){
    return _dateLocalizer.startOfWeek(...args)
  }
}

export default { number, date }

function createWrapper(){
  let dummy = {};

  ['formats', 'parse', 'format', 'firstOfWeek', 'precision']
    .forEach(name => Object.defineProperty(dummy, name, {
      enumerable: true,
      get(){
        throw new Error(
          '[React Widgets] You are attempting to use a widget that requires localization ' +
          '(Calendar, DateTimePicker, NumberPicker). ' +
          'However there is no localizer set. Please configure a localizer. \n\n' +
          'see http://jquense.github.io/react-widgets/docs/#/i18n for more info.')
      }
    }))
  return dummy
}


text:
require('rc-slider/assets/index.less');

const React = require('react');
const ReactDOM = require('react-dom');
const Slider = require('rc-slider');

const style = { float: 'left', width: 160, height: 400, marginBottom: 160, marginLeft: 50 };
const parentStyle = { overflow: 'hidden' };

const marks = {
  '-10': '-10°C',
  0: 0°C,
  26: '26°C',
  37: '37°C',
  50: '50°C',
  100: {
    style: {
      color: 'red',
    },
    label: 100°C,
  },
};

function log(value) {
  console.log(value); //eslint-disable-line
}

ReactDOM.render(

Slider with marks, `step=null`

      <Slider vertical min={-10} marks={marks} step={null} onChange={log} defaultValue={20} />

Slider with marks and steps

      <Slider vertical dots min={-10} marks={marks} step={10} onChange={log} defaultValue={20} />

Slider with marks, `included=false`

      <Slider vertical min={-10} marks={marks} included={false} defaultValue={20} />

Slider with marks and steps, `included=false`

      <Slider vertical min={-10} marks={marks} step={10} included={false} defaultValue={20} />

Range with marks

      <Slider.Range vertical min={-10} marks={marks} onChange={log} defaultValue={[20, 40]} />

Range with marks and steps

      <Slider.Range vertical min={-10} marks={marks} step={10}
        onChange={log} defaultValue={[20, 40]}
      />

  , document.getElementById('__react-content'));


text:
import { assert, JSData } from '../../_setup'

describe('Container#find', function () {
  it('should be an instance method', function () {
    const Container = JSData.Container
    const store = new Container()
    assert.equal(typeof store.updateMany, 'function')
    assert.strictEqual(store.updateMany, Container.prototype.updateMany)
  })
  it('should work')
})


text:
<?php

namespace ZendTest\Filter\Compress;

use Zend\Filter\Compress\Gz as GzCompression;

/**
 * @group      Zend_Filter
 */
class GzTest extends \PHPUnit_Framework_TestCase
{
    public $target;

    public function setUp()
    {
        if (!extension_loaded('zlib')) {
            $this->markTestSkipped('This adapter needs the zlib extension');
        }

        $this->target = sprintf('%s/%s.gz', sys_get_temp_dir(), uniqid('zfilter'));
    }

    public function tearDown()
    {
        if (file_exists($this->target)) {
            unlink($this->target);
        }
    }

    /**
     * Basic usage
     *
     * @return void
     */
    public function testBasicUsage()
    {
        $filter  = new GzCompression();

        $content = $filter->compress('compress me');
        $this->assertNotEquals('compress me', $content);

        $content = $filter->decompress($content);
        $this->assertEquals('compress me', $content);
    }

    /**
     * Setting Options
     *
     * @return void
     */
    public function testGzGetSetOptions()
    {
        $filter = new GzCompression();
        $this->assertEquals(['mode' => 'compress', 'level' => 9, 'archive' => null], $filter->getOptions());

        $this->assertEquals(9, $filter->getOptions('level'));

        $this->assertNull($filter->getOptions('nooption'));
        $filter->setOptions(['nooption' => 'foo']);
        $this->assertNull($filter->getOptions('nooption'));

        $filter->setOptions(['level' => 6]);
        $this->assertEquals(6, $filter->getOptions('level'));

        $filter->setOptions(['mode' => 'deflate']);
        $this->assertEquals('deflate', $filter->getOptions('mode'));

        $filter->setOptions(['archive' => 'test.txt']);
        $this->assertEquals('test.txt', $filter->getOptions('archive'));
    }

    /**
     * Setting Options through constructor
     *
     * @return void
     */
    public function testGzGetSetOptionsInConstructor()
    {
        $filter2= new GzCompression(['level' => 8]);
        $this->assertEquals(['mode' => 'compress', 'level' => 8, 'archive' => null], $filter2->getOptions());
    }

    /**
     * Setting Level
     *
     * @return void
     */
    public function testGzGetSetLevel()
    {
        $filter = new GzCompression();
        $this->assertEquals(9, $filter->getLevel());
        $filter->setLevel(6);
        $this->assertEquals(6, $filter->getOptions('level'));

        $this->setExpectedException('Zend\Filter\Exception\InvalidArgumentException', 'must be between');
        $filter->setLevel(15);
    }

    /**
     * Setting Mode
     *
     * @return void
     */
    public function testGzGetSetMode()
    {
        $filter = new GzCompression();
        $this->assertEquals('compress', $filter->getMode());
        $filter->setMode('deflate');
        $this->assertEquals('deflate', $filter->getOptions('mode'));

        $this->setExpectedException('Zend\Filter\Exception\InvalidArgumentException', 'mode not supported');
        $filter->setMode('unknown');
    }

    /**
     * Setting Archive
     *
     * @return void
     */
    public function testGzGetSetArchive()
    {
        $filter = new GzCompression();
        $this->assertEquals(null, $filter->getArchive());
        $filter->setArchive('Testfile.txt');
        $this->assertEquals('Testfile.txt', $filter->getArchive());
        $this->assertEquals('Testfile.txt', $filter->getOptions('archive'));
    }

    /**
     * Setting Archive
     *
     * @return void
     */
    public function testGzCompressToFile()
    {
        $filter   = new GzCompression();
        $archive = $this->target;
        $filter->setArchive($archive);

        $content = $filter->compress('compress me');
        $this->assertTrue($content);

        $filter2  = new GzCompression();
        $content2 = $filter2->decompress($archive);
        $this->assertEquals('compress me', $content2);

        $filter3 = new GzCompression();
        $filter3->setArchive($archive);
        $content3 = $filter3->decompress(null);
        $this->assertEquals('compress me', $content3);
    }

    /**
     * Test deflate
     *
     * @return void
     */
    public function testGzDeflate()
    {
        $filter  = new GzCompression(['mode' => 'deflate']);

        $content = $filter->compress('compress me');
        $this->assertNotEquals('compress me', $content);

        $content = $filter->decompress($content);
        $this->assertEquals('compress me', $content);
    }

    /**
     * testing toString
     *
     * @return void
     */
    public function testGzToString()
    {
        $filter = new GzCompression();
        $this->assertEquals('Gz', $filter->toString());
    }
}


text:
var path = require('path');
var ncp = require('ncp').ncp;
var main = require('./main');
var Spike = require('./spike');

module.exports = function (spikeName, destinationName) {
  var spike = new Spike(spikeName, destinationName);

  ncp(spike.sourcePath(), spike.destinationPath(), function (err) {
    if (err) return main.error(err);
    main.log("Created '" + path.basename(spike.destinationName) + "'");
  });
};


text:
{% load placeholder_admin_tags i18n %}{% comment %}
This is the base template to render a ContentPlugin model.
The template can be replaced by defining ``admin_form_template`` in the plugin class.

The before_fieldsets and after_fieldsets blocks are added on purpose,
to allow plugins to easily extend this file.
{% endcomment %}
        {% block before_fieldsets %}{% endblock %}
        {% block plugin-message %}
          {% if inline_admin_form|has_no_visible_fields %}

{% trans "There are no options to configure for this element." %}

          {% endif %}
        {% endblock %}
        {% block fieldsets %}
          {% for fieldset in inline_admin_form %}
            {% include "admin/fluent_contents/fieldset.html" %}{# a admin/includes/fieldset.html that supports hidden fields #}
          {% endfor %}
        {% endblock %}
        {% block after_fieldsets %}{% endblock %}


text:
__author__ = 'Matt David'

import json
import time
from base64 import b64decode, b64encode
from datetime import datetime, timedelta
from hashlib import sha256
from time import mktime
from redis import Redis
from uuid import uuid4

from BaseResolver import BaseResolver
from addressimo.config import config
from addressimo.data import IdObject
from addressimo.util import LogUtil, CustomJSONEncoder
from addressimo.paymentprotocol.paymentrequest_pb2 import ProtocolMessage, EncryptedProtocolMessage, ProtocolMessageType

log = LogUtil.setup_logging()

class RedisResolver(BaseResolver):
    @classmethod
    def get_plugin_name(cls):
        return 'REDIS'

    @classmethod
    def generate_unique_id(cls, redis_conn, uuid_multiple=1):
        while True:
            id = ''.join([uuid4().hex for _ in range(uuid_multiple)])
            try:
                if not redis_conn.exists(id):
                    return id
            except:
                log.warn("Unable to Generate New, Unused ID [REDIS: %s]" % redis_conn.info())
                return None

    def __init__(self):

        self.tx_client = Redis.from_url(config.redis_tx_uri)
        self.tx_map_client = Redis.from_url(config.redis_tx_map_uri)

    def get_all_keys(self):
        redis_client = Redis.from_url(config.redis_id_obj_uri)
        return redis_client.keys('*')

    def get_id_obj(self, id):

        redis_client = Redis.from_url(config.redis_id_obj_uri)
        try:
            result = redis_client.get(id)
            if not result:
                log.info('Unable to Get id obj data [ID: %s]' % id)
                return None

        except Exception as e:
            log.info('Unable to Get id obj data [ID: %s]: %s' % (id, str(e)))
            return None

        id_obj = IdObject(id)
        for key, value in json.loads(result).items():
            id_obj[key] = value
        return id_obj

    def get_branches(self, id):

        redis_client = Redis.from_url(config.redis_address_branch_uri)

        try:
            result = redis_client.hkeys(id)

            if not result:
                log.info('No branches are present [ID: %s]' % id)
                return []

            result = map(int, result)
        except Exception as e:
            log.error('Exception retrieving branches [ID: %s]: %s' % (id, str(e)))
            return []

        return result

    def get_lg_index(self, id, branch):

        lg_index = 0
        redis_client = Redis.from_url(config.redis_address_branch_uri)

        try:
            lg_index = redis_client.hget(id, branch)
        except Exception as e:
            log.error('Exception retrieving lg_index from Redis [ID: %s | Branch: %s]: %s' % (id, branch, str(e)))

        return int(lg_index) if lg_index else 0

    def set_lg_index(self, id, branch, index):

        redis_client = Redis.from_url(config.redis_address_branch_uri)

        try:
            result = redis_client.hset(id, branch, index)
        except Exception as e:
            log.error('Exception setting lg_index in Redis [ID: %s | Branch: %s] %s' % (id, branch, str(e)))
            return None

        return result

    def save(self, id_obj):

        redis_client = Redis.from_url(config.redis_id_obj_uri)
        if not id_obj.id:
            id_obj.id = RedisResolver.generate_unique_id(redis_client, 1)

        try:
            result = redis_client.set(id_obj.id, json.dumps(id_obj, cls=CustomJSONEncoder))
            log.info('Saved IdObject to Redis [ID: %s]' % id_obj.id)
            return result
        except Exception as e:
            log.info('Unable to Save IdObject to Redis [ID: %s]: %s' % (id, str(e)))
            raise

    def delete(self, id_obj):

        redis_client = Redis.from_url(config.redis_id_obj_uri)

        try:
            result = redis_client.delete(id_obj.id)
            log.info('Deleted IdObject to Redis [ID: %s]' % id_obj.id)
            return result
        except Exception as e:
            log.info('Unable to Delete IdObject to Redis [ID: %s]: %s' % (id_obj.id, str(e)))
            raise

    #########################################
    # Payment Protocol Data Handling
    #########################################
    def get_paymentprotocol_messages(self, id=None, tx_id=None):

        txs_data = {}
        tx_ids = [tx_id]
        if id:
            tx_count = self.tx_map_client.llen(id)
            if not tx_count:
                return txs_data

            tx_ids = self.tx_map_client.lrange(id, 0, tx_count-1)

        for transaction_id in tx_ids:
            tx = self.tx_client.hgetall(transaction_id)
            if not tx:
                continue

            decoded_messages = [b64decode(x) for x in json.loads(tx.get('messages', '[]'))]
            tx['messages'] = decoded_messages
            txs_data[transaction_id] = tx

        return txs_data

    def add_paymentprotocol_message(self, message, id=None, tx_id=None):

        possible_tx_ids = [tx_id]
        if id:
            possible_tx_id_count = self.tx_map_client.llen(id)
            possible_tx_ids = self.tx_map_client.lrange(id, 0, possible_tx_id_count - 1)

        found_tx = found_tx_id = None
        for possible_tx_id in possible_tx_ids:
            if message.identifier == self.tx_client.hget(possible_tx_id, 'identifier'):
                found_tx = self.tx_client.hgetall(possible_tx_id)
                found_tx_id = possible_tx_id
                break

        # Create New TX
        if not found_tx and id and message.message_type == ProtocolMessageType.Value('INVOICE_REQUEST'):
            new_data = {
                'messages': json.dumps([b64encode(message.SerializeToString())]),
                'receiver': id,
                'identifier': message.identifier,
                'last_updated': datetime.utcnow().strftime('%s'),
            }
            if isinstance(message, EncryptedProtocolMessage):
                new_data['last_nonce'] = message.nonce

            new_id = RedisResolver.generate_unique_id(self.tx_client, 3)
            self.tx_client.hmset(new_id, new_data)
            self.tx_map_client.rpush(id, new_id)
            return new_id
        elif not found_tx:
            return None

        found_tx['messages'] = json.loads(found_tx['messages'])
        found_tx['messages'].append(b64encode(message.SerializeToString()))
        found_tx['messages'] = json.dumps(found_tx['messages'])
        found_tx['last_updated'] = datetime.utcnow().strftime('%s')

        if isinstance(message, EncryptedProtocolMessage):
            found_tx['last_nonce'] = message.nonce

        self.tx_client.hmset(found_tx_id, found_tx)
        return found_tx_id

    def delete_paymentprotocol_message(self, tx_identifier, type, id=None, tx_id=None):

        messages = self.get_paymentprotocol_messages(id, tx_id)

        for tx_id, msg in messages.iteritems():

            msg_updated = False
            for pp_message in msg.get('messages', []):

                try:
                    protobuf_message = EncryptedProtocolMessage()
                    protobuf_message.ParseFromString(pp_message)
                    protobuf_message.SerializeToString() # Verify this is an EncryptedProtocolMessage
                except:
                    try:
                        protobuf_message = ProtocolMessage()
                        protobuf_message.ParseFromString(pp_message)
                        protobuf_message.SerializeToString() # Verify this is an ProtocolMessage
                    except:
                        log.error('Unable to Parse Protobuf Message [ID: %s | TX_ID: %s]' % (id, tx_id))
                        continue

                if type.upper() == ProtocolMessageType.Name(protobuf_message.message_type) and tx_identifier == protobuf_message.identifier:
                    msg['messages'] = [x for x in msg.get('messages', []) if x != pp_message]
                    msg_updated = True
                    break

            if not msg_updated:
                continue

            if not msg.get('messages', []):
                self.tx_client.delete(tx_id)
                receiver_id = id if id else msg.get('receiver', '')
                self.tx_map_client.lrem(receiver_id, tx_id, 0)
            else:
                msg['messages'] = json.dumps([b64encode(x) for x in msg.get('messages', [])])
                self.tx_client.hmset(tx_id, msg)

            return True

        return False

    def cleanup_stale_paymentprotocol_messages(self):

        delete_count = 0

        for tx_id in self.tx_client.scan_iter():
            tx = self.tx_client.hgetall(tx_id)
            last_updated = datetime.utcfromtimestamp(tx.get('last_updated', ''))
            if last_updated > datetime.utcnow() - timedelta(days=config.paymentprotocol_message_expiration_days):
                continue

            # Delete the TX
            delete_count += 1
            self.tx_client.delete(tx_id)

            # Delete TX ID from TX Receiver Map
            self.tx_map_client.lrem(tx.get('receiver'), tx_id)

        return delete_count

    def get_tx_last_nonce(self, message, id=None, tx_id=None):

        txs_data = self.get_paymentprotocol_messages(id, tx_id)
        if not txs_data:
            return None

        for tx_id, data in txs_data.items():
            if message.identifier == data['identifier']:
                return int(data.get('last_nonce'))

        return None

    # Payment Data Handling
    def get_payment_request_meta_data(self, uuid):

        redis_client = Redis.from_url(config.redis_pr_store)

        return redis_client.hgetall(uuid)

    def set_payment_request_meta_data(self, expiration_date, wallet_addr, amount):

        redis_client = Redis.from_url(config.redis_pr_store)
        payment_url_uuid = RedisResolver.generate_unique_id(redis_client, 2)

        payment_addresses = {
            wallet_addr: amount
        }

        try:
            redis_client.hmset(payment_url_uuid, {
                'expiration_date': expiration_date,
                'payment_validation_data': json.dumps(payment_addresses)
            })

        except Exception as e:
            log.info('Exception Saving PaymentRequest Meta Data: %s' % str(e))
            raise

        return payment_url_uuid

    def cleanup_stale_payment_request_meta_data(self):

        redis_client = Redis.from_url(config.redis_pr_store)

        payment_request_keys = redis_client.keys()
        log.info('Found %d Payment Request Meta Data Keys' % len(payment_request_keys))

        for key in payment_request_keys:
            try:
                payment_request = redis_client.hgetall(key)
                if datetime.utcnow() > datetime.fromtimestamp(int(payment_request.get('expiration_date'))):
                    log.info('Deleting Stale Payment Request [UUID: %s]' % key)
                    redis_client.delete(key)
            except Exception as e:
                log.error('Exception Occurred Cleaning Up Stale Payment Request Meta Data [UUID: %s]: %s' % (key, str(e)))

    def set_payment_meta_data(self, tx_hash, memo, refund_address):

        redis_client = Redis.from_url(config.redis_payment_store)

        try:
            redis_client.hmset(tx_hash, {
                'memo': memo,
                'refund_to': refund_address,
                'expiration_date': int(
                    mktime((datetime.utcnow() + timedelta(days=config.bip70_payment_expiration_days)).timetuple())
                )
            })

        except Exception as e:
            log.info('Exception Saving Payment Meta Data: %s' % str(e))
            raise

    def cleanup_stale_payment_meta_data(self):

        redis_client = Redis.from_url(config.redis_payment_store)

        payment_keys = redis_client.keys()
        log.info('Found %d Payment Meta Data Keys' % len(payment_keys))

        for key in payment_keys:
            try:
                payment = redis_client.hgetall(key)
                if datetime.utcnow() > datetime.fromtimestamp(int(payment.get('expiration_date'))):
                    log.info('Deleting Stale Payment [UUID: %s]' % key)
                    redis_client.delete(key)
            except Exception as e:
                log.error('Exception Occurred Cleaning Up Stale Payment Meta Data [UUID: %s]: %s' % (key, str(e)))


text:
install python-numpy
install python-collections
install python-sys
install python-glob
install python-Sos
install python-codec
# install python-timeit
#END

# proper permission
chmod a+x ./src/words_tweeted_median_unique.py

(

    Directory=./tweet_input

    # FAQ doesn't explicitly mention if wc_input exists
    if [ -d "$Directory" ];
    then
	# execute programs - provide correct arguments

    # open combined program
    python ./src/words_tweeted_median_unique.py ./tweet_input ./tweet_output/ft1.txt ./tweet_output/ft2.txt

        else
            echo " tweet_input directory does not exist. "
    fi
)


text:
'use strict'

const PassThrough = require('stream').PassThrough
const pumpify = require('pumpify')
const transforms = require('./transforms')

module.exports = Transform

function Transform (app) {
  if (!app.transforms || !app.transforms.length) return new PassThrough()
  const transformStreams = app.transforms.map((t) => transforms[t](app))
  return app.transforms.length > 1
    ? pumpify.apply(null, transformStreams)
    : transformStreams[0]
}


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

namespace OCM.API.Common.Model
{
    public class UserSubscription
    {
        public int ID { get; set; }

        public int UserID { get; set; }

        [DisplayName("Subscription Title"), Required]
        public string Title { get; set; }

        [DisplayName("Country")]
        public Nullable<int> CountryID { get; set; }

        public Country Country { get; set; }

        [Range(-90, 90)]
        public Nullable<double> Latitude { get; set; }

        [Range(-180, 180)]
        public Nullable<double> Longitude { get; set; }

        [Range(0, 100000)]
        [DisplayName("Distance (KM)")]
        public Nullable<double> DistanceKM { get; set; }

        public UserSubscriptionFilter FilterSettings { get; set; }

        [DisplayName("Date Last Notified")]
        public Nullable<System.DateTime> DateLastNotified { get; set; }

        [DisplayName("Enable This Subscription"), Required]
        public bool IsEnabled { get; set; }

        [DisplayName("Date Created")]
        public System.DateTime DateCreated { get; set; }

        [DisplayName("New locations are added"), Required]
        public bool NotifyPOIAdditions { get; set; }

        [DisplayName("Locations edits are awaiting approval"), Required]
        public bool NotifyPOIEdits { get; set; }

        [DisplayName("Locations updates are published"), Required]
        public bool NotifyPOIUpdates { get; set; }

        [DisplayName("New comments/check-ins are added"), Required]
        public bool NotifyComments { get; set; }

        [DisplayName("New photos/media items added"), Required]
        public bool NotifyMedia { get; set; }

        [DisplayName("Emergency charging requested in area"), Required]
        public bool NotifyEmergencyChargingRequests { get; set; }

        [DisplayName("General charging requested in area"), Required]
        public bool NotifyGeneralChargingRequests { get; set; }

        [DisplayName("Notification Frequency"), Required]
        public int NotificationFrequencyMins { get; set; }
    }

    public class UserSubscriptionFilter
    {
        public List<int> ConnectionTypeIDs { get; set; }

        public List<int> OperatorIDs { get; set; }

        public List<int> LevelIDs { get; set; }

        public List<int> UsageTypeIDs { get; set; }

        public List<int> StatusTypeIDs { get; set; }

        public UserSubscriptionFilter()
        {
            ConnectionTypeIDs = new List<int>();
            OperatorIDs = new List<int>();
            LevelIDs = new List<int>();
            UsageTypeIDs = new List<int>();
            StatusTypeIDs = new List<int>();
        }
    }

}


text:
package org.apereo.cas;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.CoreAuthenticationUtils;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.EncodingUtils;
import org.apereo.cas.util.junit.EnabledIfPortOpen;

import lombok.val;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link PersonDirectoryPrincipalResolverActiveDirectoryTests}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@SpringBootTest(classes = BasePrincipalAttributeRepositoryTests.SharedTestConfiguration.class, properties = {
    "cas.authn.attribute-repository.ldap[0].bind-dn=Administrator@cas.example.org",
    "cas.authn.attribute-repository.ldap[0].bind-credential=" + PersonDirectoryPrincipalResolverActiveDirectoryTests.AD_ADMIN_PASSWORD,
    "cas.authn.attribute-repository.ldap[0].ldap-url=" + PersonDirectoryPrincipalResolverActiveDirectoryTests.AD_LDAP_URL,
    "cas.authn.attribute-repository.ldap[0].use-start-tls=true",
    "cas.authn.attribute-repository.ldap[0].base-dn=dc=cas,dc=example,dc=org",
    "cas.authn.attribute-repository.ldap[0].search-filter=(sAMAccountName={user})",
    "cas.authn.attribute-repository.ldap[0].trust-store=" + PersonDirectoryPrincipalResolverActiveDirectoryTests.AD_TRUST_STORE,
    "cas.authn.attribute-repository.ldap[0].trust-store-type=JKS",
    "cas.authn.attribute-repository.ldap[0].trust-manager=ANY",
    "cas.authn.attribute-repository.ldap[0].trust-store-password=changeit",
    "cas.authn.attribute-repository.ldap[0].attributes.displayName=description",
    "cas.authn.attribute-repository.ldap[0].attributes.objectGUID=objectGUID",
    "cas.authn.attribute-repository.ldap[0].attributes.objectSid=objectSid"
})
@EnabledIfPortOpen(port = 10390)
@Tag("Ldap")
public class PersonDirectoryPrincipalResolverActiveDirectoryTests {
    public static final String AD_TRUST_STORE = "file:/tmp/adcacerts.jks";

    public static final String AD_ADMIN_PASSWORD = "M3110nM3110n#1";

    public static final String AD_LDAP_URL = "ldap://localhost:10390";

    @Autowired
    @Qualifier(PrincipalResolver.BEAN_NAME_ATTRIBUTE_REPOSITORY)
    private IPersonAttributeDao attributeRepository;

    @Autowired
    private CasConfigurationProperties casProperties;

    @Test
    public void verifyResolver() {
        val resolver = CoreAuthenticationUtils.newPersonDirectoryPrincipalResolver(PrincipalFactoryUtils.newPrincipalFactory(),
            this.attributeRepository,
            CoreAuthenticationUtils.getAttributeMerger(casProperties.getAuthn().getAttributeRepository().getCore().getMerger()),
            casProperties.getPersonDirectory());
        val p = resolver.resolve(new UsernamePasswordCredential("admin", "P@ssw0rd"),
            Optional.of(CoreAuthenticationTestUtils.getPrincipal()),
            Optional.of(new SimpleTestUsernamePasswordAuthenticationHandler()));
        assertNotNull(p);
        assertTrue(p.getAttributes().containsKey("description"));
        assertTrue(p.getAttributes().containsKey("objectGUID"));
        assertTrue(p.getAttributes().containsKey("objectSid"));
        CollectionUtils.firstElement(p.getAttributes().get("objectGUID"))
            .ifPresent(value -> assertNotNull(EncodingUtils.decodeBase64(value.toString())));
        CollectionUtils.firstElement(p.getAttributes().get("objectSid"))
            .ifPresent(value -> assertNotNull(EncodingUtils.decodeBase64(value.toString())));
    }
}


text:
<?php

namespace tests\codeception\frontend\unit;

/**
 * Class DbTestCase
 *
 * @package tests\codeception\frontend\unit
 */
class DbTestCase extends \yii\codeception\DbTestCase
{
    public $appConfig = '@tests/codeception/config/frontend/unit.php';
}


text:
package marketdata
import akka.actor.ActorRef
import scala.{ Enumeration }
import marketdata.MarketDataTypes.{MarketDataType}
import marketdata.MarketDataTypes.{TradeDataType,TickDataType,DepthDataType,OrderBookDataType}

/** market data events : technical events **/
abstract trait MarketEvent {
  def exchange: String
  val timestamp: Long = System.currentTimeMillis();
}

case class Connect(val exchange: String) extends MarketEvent
case class Disconnect(val exchange: String) extends MarketEvent
case class SystemMessage(val exchange: String, val message: Exception) extends MarketEvent

/** market data events**/
object MarketDataTypes extends Enumeration {
  type MarketDataType = Value
  val TickDataType = Value("Tick")
  val TradeDataType = Value("Trade")
  val DepthDataType = Value("Depth")
  val OrderBookDataType = Value("OrderBook")
}

abstract trait MarketDataEvent extends MarketEvent {
  def instrument: String
}

case class Tick(val exchange: String, val instrument: String, val price: BigDecimal) extends MarketDataEvent
case class Trade(val exchange: String, val instrument: String, val price: BigDecimal, val quantity: BigDecimal) extends MarketDataEvent
//case class Depth
//case class OrderBook

/**subscription to market data gateways**/
abstract trait Command
case class SubscribeListenerRequest(val subscriber: ActorRef, val subject: String, val topics: Option[Iterable[MarketDataType]]) extends Command
case class SubscribeListenerResponse(val subject: String, val subscribed: Boolean, val publisher: ActorRef) extends Command

/**Internal events to polling mechanism**/
abstract trait MarketDataPollCommand
object MarketDataPollCommandEnum extends Enumeration {
  case class EnumVal(val dataType: MarketDataType) extends super.Val(nextId, dataType.toString()) with MarketDataPollCommand
  val TickPollCommand =  EnumVal(TickDataType)
  val TradePollCommand = EnumVal(TradeDataType)
  val DepthPollCommand = EnumVal(DepthDataType)
  val OrderBookDataPollCommand = EnumVal(OrderBookDataType)
}


text:
package balancedbinarytree;

import java.util.HashMap;
import java.util.Map;

public class Solution {
	Map<TreeNode, Integer> nodeDepths = new HashMap<TreeNode, Integer>();

	public boolean isBalanced(TreeNode root) {
		if (root == null) {
			return true;
		}
		if (isBalanced(root.left) && isBalanced(root.right)) {
			int leftDepth = depth(root.left);
			int rightDepth = depth(root.right);
			return (Math.abs(leftDepth - rightDepth) < 2);
		} else {
			return false;
		}
	}

	private int depth(TreeNode root) {
		if (root == null) {
			return 0;
		}
		if (nodeDepths.containsKey(root)) {
			return nodeDepths.get(root);
		}
		int depth = 1;
		if (root.left != null) {
			depth = Math.max(depth, 1 + depth(root.left));
		}
		if (root.right != null) {
			depth = Math.max(depth, 1 + depth(root.right));
		}
		nodeDepths.put(root, depth);
		return depth;
	}
}

class TreeNode {
	public int val;
	public TreeNode left;
	public TreeNode right;

	public TreeNode(int x) {
		val = x;
	}
}


text:
from .base import BaseType

class ParseJobList(BaseType):

    _soap_tag = 'parse_jobs'

    def __init__(self):
        BaseType.__init__(
            self,
            simple_properties={},
            complex_properties={},
            list_properties={'parse_job': ParseJob},
        )

        self.parse_job = []

from parse_job import ParseJob


text:
Orders Data Table

			<form class="form-inline">

							<button type="button" class="btn btn-default dropdown-toggle first-dropdown" dropdown-toggle>{{ search.filter.name }}

							</button>

Anything

Order

Party

Menu Item

Modifiers

Seat

Notes

							<button type="button" class="btn btn-default dropdown-toggle second-dropdown" dropdown-toggle>{{ search.equivalencyType }}

							</button>

Equal to

Less than

Greater than

						<input type="text" class="form-control" placeholder="Search term" ng-model="search.value" size="28">

					from
					<input type="date" class="form-control start-date" datepicker-popup ng-model="startDate" max-date="OrdersDataTableCtrl.maxDate" date-disabled="disabled(date, mode)" close-text="Close" ng-change="startDateChange(this.startDate)" />
					to
					<input type="date" class="form-control end-date" datepicker-popup ng-model="endDate" max-date="maxDate" date-disabled="disabled(date, mode)" close-text="Close" ng-change="endDateChange(this.endDate)" />

						<button type="button" class="btn btn-default dropdown-toggle" ng-disabled="true" class="btn btn-default">Export </button>

				      <button type="button" class="btn btn-default dropdown-toggle" dropdown-toggle ng-disabled="!(selectedArray.length > 0)">
				        Export
				      </button>

To CSV

			</form>

					<input type="checkbox" ng-model="selectedAll" ng-click="OrdersDataTableCtrl.checkAll()">
					Order

					Party

					Menu Item

					Modifiers

					Seat

					Notes

					Date

						<input type="checkbox" ng-model="orders.value">
						{{ orders.id }}
						{{ orders.party.id }}
						{{ orders.menuItem.name }}
						{{ orders.menuItemModifiers }}
						{{ orders.seat }}
						{{ orders.notes }}
						{{ orders.createdAt | date: 'short' }}

Total results: {{ filteredOrders.length }}

 0"> | Selected results: {{ selectedArray.length }}

Show
				<select class="form-control entry-select" ng-model="numEntries">
					<option>10</option>
					<option>25</option>
					<option>50</option>
					<option>100</option>
				</select>
				entries

				<dir-pagination-controls></dir-pagination-controls>


text:
import requests
from time import sleep

def get_receipt_nalogru(fn, fd, fpd, login, password, deviceid, deviceos):
    url = "".join(["http://proverkacheka.nalog.ru:8888/v1/inns/*/kkts/*",
                   "/fss/{0}/tickets/{1}/?fiscalSign={2}&sendToEmail=no"])\
                   .format(str(fn), str(fd).lstrip("0"), str(fpd))
    headers = {"Device-Id": str(deviceid),
               "Device-OS": str(deviceos)
    }
    s = requests.Session()
    response = s.get(url, headers = headers,
                     auth = (login, password),)
    if (response.status_code == 202):
        sleep(5)
        response = s.get(url, headers = headers,
                     auth = (login, password))
    if (response.status_code == 202):
        raise requests.RequestException("Timed out")
    if (not response.ok):
        response.raise_for_status()
    return(response.json()["document"]["receipt"])

def verify_receipt_nalogru(fn,fd,fpd,paid_sum,date,optype):
        s = requests.Session()
        url = "".join(
            [
                "http://proverkacheka.nalog.ru:8888/v1/ofds/*/inns/*/",
                "fss/{0}/operations/{1}/tickets/{2}?fiscalSign={3}",
                "&date={4}&sum={5}"
            ]).format(
                str(fn),
                str(optype),
                str(fd).lstrip("0"),
                str(fpd),
                date.strftime("%Y-%m-%dT%H:%M:%S"),
                str(int(paid_sum)*100)
        )
        response = s.get(url)
        if (response.status_code == 204):
            return True
        else:
            return False


text:
Me learning Haskell. The model here is "progress every day."

## Content

The HaskellBook folder is me going through the [Haskell Book](http://haskellbook.com/)

Other stuff is from [Real World Haskell](http://book.realworldhaskell.org/),
but is also from before I realized I needed to step back from that and learn
the fundamentals of Haskell from the ground up, from a "can actually do things"
perspective rather than the "I read [LYAH](http://learnyouahaskell.com/)"
and think I know things perspective.

## Notes to Haskell Novices

Haskell has many features not found in other languages and for
that reason and others requires a much firmer learning approach
than other languages seem to require.

Examples:

* Haskell Language Extensions change the syntax of the file
  you are looking at making it tough to figure out the syntax you
  know from the syntax the extension has introduced. Worse, "modern"
  Haskell involves having a [working knowledge of more extensions
  than one might imagine](http://dev.stephendiehl.com/hask/#the-benign).
* Like many Functional languages, Haskell reading requires working
  familiarity with a basic set of functions before you can even
  tell yourself basic stories about what some code is doing. Examples
  of this include functions like '$', '.', along with data constructors,
  type constructors, tuple constructors, matching etc.
* Thinking that "Haskell is a Lazy language" really misses the
  reality that instead of being "eager" or "lazy" Haskell really
  is giving the programmer a much more nuanced and rich control
  over evaluation techniques than is typically enjoyed in other
  languages.
* Mathematical concepts, usually hidden in other languages, are
  not only prominent in Haskell, but are extremely valuable so as to
  be unavoidable in practice. Examples: the Lambda Calculus, functions,
  Monoid, Functor, Applicative, Monad and many more.
* Haskell the language and Haskell the culture places a huge amount
  of emphasis on abstraction. The result of this is that both commonly
  discuss and implement levels of abstraction unheard of in other
  languages or communities. Examples of this are the abstraction
  ladder from value to function and then Functor, Applicative and Monad,
  and things like Kinds.
* In my experience, getting into Haskell with previous language experience did not prepare me for the abstractions, correctness and re-usability the language and libraries commonly express.

By keeping the above in mind, and working on Haskell every single
day I could, and by subscribing to every [Haskell mailing-list](https://www.haskell.org/mailing-lists), [podcast](https://www.haskellcast.com/) and
social-media feed, I have begun my journey in a way that I feel
will lead to Haskell in production.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
//   Copyright (c) 2013 Microsoft Corporation
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using Microsoft.Research.DataOnboarding.DomainModel;
using Microsoft.Research.DataOnboarding.FileService.Interface;
using Microsoft.Research.DataOnboarding.RepositoriesService.Interface;
using Microsoft.Research.DataOnboarding.Utilities;
using Microsoft.Research.DataOnboarding.Utilities.Enums;
using Microsoft.Research.DataOnboarding.Utilities.Model;
using System;

namespace Microsoft.Research.DataOnboarding.QueueService
{
    /// <summary>
    /// Serves as base class for QueueService.
    /// </summary>
    public abstract class BaseQueueService
    {
        /// <summary>
        /// Constant for RetryCount configuration.
        /// </summary>
        protected const string MaxRetry_Count = "RetryCount";

        /// <summary>
        /// Constant for VerifyFileInterval Configuration.
        /// </summary>
        protected const string VerifyFile_Interval = "VerifyFileInterval";

        /// <summary>
        /// Constant for PublishInterval Configuration.
        /// </summary>
        protected const string Publish_Interval = "PublishInterval";

        /// <summary>
        /// Gets or sets FileService.
        /// </summary>
        protected IFileService FileService { get; set; }

        /// <summary>
        /// Gets or sets MazRetryCount.
        /// </summary>
        protected int MaxRetryCount { get; set; }

        /// <summary>
        /// Gets or sets VerifyFileInterval.
        /// </summary>
        protected int VerifyFileInterval { get; set; }

        /// <summary>
        /// Gets or sets QueueRepository.
        /// </summary>
        protected IQueueRepository QueueRepository { get; set; }

        /// <summary>
        /// Gets or sets RepositoryService.
        /// </summary>
        protected IRepositoryService RepositoryService { get; set; }

        /// <summary>
        /// Gets or sets Diagnostics.
        /// </summary>
        protected DiagnosticsProvider Diagnostics { get; set; }

        /// <summary>
        /// Updates the retry count and updates the Message in the queue queue
        /// if the retry count is greater then the max retry count updates the file status as error and deletes the message from queue
        /// </summary>
        /// <param name="message">BaseMessage instance.</param>
        /// <param name="intervalInminutes">Interval In Minutes.</param>
        protected void UpdateMessageInQueue(BaseMessage message, int interval)
        {
            if (message.RetryCount < MaxRetryCount - 1)
            {
                message.RetryCount += 1;
                message.ProcessOn = DateTime.UtcNow.AddSeconds(interval);
                this.QueueRepository.UpdateMessage(message);
                this.Diagnostics.WriteInformationTrace(TraceEventId.Flow, string.Format("Adding the message back to the queue, after exception. RetryCount: {0}", message.RetryCount));
            }
            else
            {
                this.Diagnostics.WriteInformationTrace(TraceEventId.Flow, string.Format("Exceeded Max no of allowed Retries: {0}", message.RetryCount));
                UpdateFileStatusAsError(message);
            }
        }

        /// <summary>
        /// Updates the file status as error.
        /// </summary>
        /// <param name="message">BaseMessage instance.</param>
        protected void UpdateFileStatusAsError(BaseMessage message)
        {
            File file = this.FileService.GetFileByFileId(message.FileId);
            file.RepositoryId = message.RepositoryId;
            file.ModifiedOn = DateTime.UtcNow;
            file.Status = FileStatus.Error.ToString();
            this.FileService.UpdateFile(file);
            this.QueueRepository.DeleteFromQueue(message);
        }
    }
}


text:
package com.thinkbiganalytics.nifi.provenance.reporting;

import org.apache.nifi.reporting.ReportingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class NodeIdStrategyV1 implements NodeIdStrategy {

    private static final Logger log = LoggerFactory.getLogger(NodeIdStrategyV1.class);

    @Override
    public String getNodeId(ReportingContext context) {
        final boolean isClustered = context.isClustered();
        final String nodeId = isClustered ? context.getClusterNodeIdentifier() : "non-clustered-node-id";
        if (nodeId == null) {
            log.info("This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. "
                     + "Will wait for Node Identifier to be established.");
        }
        return nodeId;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke

        android:dashGap="0dp"
        android:width="1sp"
        android:color="@android:color/black" />
</shape>


text:
import unittest

import bslint.constants as const
from tests.resources.common.test_methods import CommonMethods as Common

class TestIfParse(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.common = Common()

    def test_if_with_function_call_and_value_id(self):
        self.common.match_statement(const.IF_STMT, "if func_name(msg) = \"roVideoPlayerEvent\"")

    def test_if_with_var_as_id(self):
        self.common.match_statement(const.IF_STMT, "if x = 3")

    def test_if_with_function_call_id(self):
        self.common.match_statement(const.IF_STMT, "if test(param)")

    def test_if_with_complex_function_call(self):
        self.common.match_statement(const.IF_STMT, "if msg.isFullResult()")

    def test_if_with_value(self):
        self.common.match_statement(const.IF_STMT, "if msg.isFullResult()")

    def test_if_with_value_equals_value(self):
        self.common.match_statement(const.IF_STMT, "if 3 = 3")

    def test_if_with_value_equals_id(self):
        self.common.match_statement(const.IF_STMT, "if 3 = x")

    def test_if_with_value_equals_function_call(self):
        self.common.match_statement(const.IF_STMT, "if 3 = test()")

    def test_if_with_numeric_value(self):
        self.common.match_statement(const.IF_STMT, "if 3")

    def test_if_with_id(self):
        self.common.match_statement(const.IF_STMT, "if x")

    def test_if_with_function_call_and_value_id_then(self):
        self.common.match_statement(const.IF_STMT, "if func_name(msg) = \"roVideoPlayerEvent\" then")

    def test_if_with_var_as_id_then(self):
        self.common.match_statement(const.IF_STMT, "if x = 3 then")

    def test_else_if_with_value_equals_id(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if 3 = x")

    def test_else_if_with_numeric_value(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if 3")

    def test_else_if_with_id(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if x")

    def test_if_with_value_equals_value_then(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if 3 = 3 then")

    def test_if_with_value_equals_id_then(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if 3 = x then")

    def test_if_with_numeric_value_then(self):
        self.common.match_statement(const.ELSE_IF_STMT, "else if 3 then")

    def test_if_then_no_end_if_func_call(self):
        self.common.match_statement(const.IF_BLOCK, "if requiresUpdate then showRequiresUpdateScreen()")

    def test_else_if_then_no_end_if_func_call(self):
        self.common.match_statement(const.ELSE_IF_BLOCK, "elseif requiresUpdate then showRequiresUpdateScreen()")

    def test_else_if_then_no_end_if_var_as(self):
        self.common.match_statement(const.ELSE_IF_BLOCK, "elseif requiresUpdate then c = 3")

    def test_if_then_no_end_if_var_as(self):
        self.common.match_statement(const.IF_BLOCK, "if requiresUpdate then c = 3")

    def test_else(self):
        self.common.match_statement(const.ELSE_STMT, "else")

    def test_if_condition_in_brackets(self):
        self.common.match_statement(const.IF_STMT, "if (x > 3)")

    def test_if_function_call_then_function_call(self):
        self.common.match_statement(const.IF_BLOCK, "if requiresUpdate() then showRequiresUpdateScreen()")

    def test_if_condition_and_condition(self):
        self.common.match_statement(const.IF_STMT, "if x > 3 and y < 5")

    def test_if_withminus_after_operator(self):
        self.common.match_statement(const.IF_STMT, "if x > -3")

    def test_if_plus_or_minus_after_operator_with_function_call(self):
        self.common.match_statement(const.IF_STMT, "if x > -test()")

    def test_if_condition_or_condition(self):
        self.common.match_statement(const.IF_STMT, "if x > 3 or y < 5")

    def test_if_condition_and_var_as(self):
        self.common.match_statement(const.IF_STMT, "if x > 3 and y = 5")

    def test_if_condition_or_var_as(self):
        self.common.match_statement(const.IF_STMT, "if x > 3 or y = 5")

    def test_if_var_as_and_condition(self):
        self.common.match_statement(const.IF_STMT, "if x = 3 and y < 5")

    def test_if_var_as_or_condition(self):
        self.common.match_statement(const.IF_STMT, "if x = 3 or y < 5")

    def test_if_function_call_or_condition(self):
        self.common.match_statement(const.IF_STMT, "if x() or y < 5")

    def test_if_function_call_and_condition(self):
        self.common.match_statement(const.IF_STMT, "if x() and y < 5")

    def test_if_condition_and_function_call(self):
        self.common.match_statement(const.IF_STMT, "if y < 5 and X()")

    def test_if_condition_or_function_call(self):
        self.common.match_statement(const.IF_STMT, "if y < 5 or X()")

    def test_if_function_call_and_function_call(self):
        self.common.match_statement(const.IF_STMT, "if y() and X()")

    def test_if_function_call_or_function_call(self):
        self.common.match_statement(const.IF_STMT, "if y() or X()")

    def test_if_var_as_then_var_as(self):
        self.common.match_statement(const.IF_BLOCK, "if x=3 then y=5")

    def test_if_with_function_declaration_fails(self):
        self.common.status_error("if function x()")

    def test_if_with_print_fails(self):
        self.common.status_error("if print x")

    def test_else_if_operator(self):
        self.common.status_error("else if + ")

    def test_else_if_with_print_fails(self):
        self.common.status_error("else if = ")


text:
import React from 'react';
import PropTypes from 'prop-types';
import { LinkContainer } from 'react-router-bootstrap';
import { Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import Icon from '../Icon/Icon'
import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';

const userName = () => {
  const user = Meteor.user();
  const name = user && user.profile ? user.profile.name : '';
  return user ? `${name.first} ${name.last}` : '';
};

const isInRole = (user , userRoles , group) => {
  if ( Roles.userIsInRole(user, [userRoles], group) ){
    return true
  }{
    return false
  }
}

const AuthenticatedNavigation = ({ userId , name , unReadCount }) => (

  {isInRole(userId , 'user' , 'author') ?

      <LinkContainer to="/authors_dashboard" exact>
        <NavItem eventKey={ 2 } href="/authors_dashboard">Dashboard</NavItem>
      </LinkContainer>

  : ''}

  {isInRole(userId , 'user' , 'author') ?

    <LinkContainer to="/submit_paper/new" exact>
      <NavItem eventKey={ 3 } href="/submit_paper/new">
      <Icon icon="book" /> Submit Paper
      </NavItem>
    </LinkContainer>

: ''}

{isInRole(userId , 'user' , 'author') ?

  <LinkContainer to="/certificate_downloads" exact>
    <NavItem eventKey={ 4 } href="/certificate_downloads">
    <Icon icon="certificate" /> Certificate Downloads
    </NavItem>
  </LinkContainer>

  : ''}

{isInRole(userId , 'user' , 'author') ?

  <NavDropdown eventKey={5} title="Transaction" id="user-nav-dropdown">
    <LinkContainer to="/view_my_transactions" exact>
     <NavItem eventKey={ 5.1 } href="/view_my_transactions">My Transactions</NavItem>
    </LinkContainer>
   <LinkContainer to="/view_transaction_status" exact>
     <NavItem eventKey={ 5.2 } href="/view_transaction_status">Check Transactions Status</NavItem>
   </LinkContainer>
  </NavDropdown>

: ''}

{/*  start of system admin role  */}

{/*  end of system admin role  */}

{/*  Admin Routes starts here     */}

{isInRole(userId , 'super-admin' , Roles.GLOBAL_GROUP) ?

   <LinkContainer to="/admin/dashboard" exact>
     <NavItem eventKey={ 3 } href="/admin/dashboard">Dashboard</NavItem>
   </LinkContainer>

: ''}

{isInRole(userId , 'super-admin' , Roles.GLOBAL_GROUP) ?

  <NavDropdown eventKey={7} title="Paper Management" id="user-nav-dropdown">
    <LinkContainer to="/upload/approved_papers/doc_to_pdf" exact>
      <NavItem eventKey={7.1} href="/upload/approved_papers/doc_to_pdf">Upload Pdf</NavItem>
    </LinkContainer>
  </NavDropdown>

: ''}

{isInRole(userId , 'super-admin' , Roles.GLOBAL_GROUP) ?

  <NavDropdown eventKey={8} title="Journal Management" id="user-nav-dropdown">
    <LinkContainer to="/admin/create_journal_account" exact>
      <NavItem eventKey={ 8.1 } href="/admin/create_journal_account">Create Journal Account</NavItem>
    </LinkContainer>
    <LinkContainer to="/dashboard/new_journal" exact>
    <NavItem eventKey={ 8.2 } href="/dashboard/new_journal">New Journal</NavItem>
   </LinkContainer>
   <LinkContainer to="/submit_paper_for_author" exact>
    <NavItem eventKey={ 8.3 } href="/submit_paper_for_author">Submit Paper For Authors</NavItem>
  </LinkContainer>
   <LinkContainer to="/admin/journal_stats" exact>
    <NavItem eventKey={8.3} href="/admin/journal_stats">Journal Stats</NavItem>
   </LinkContainer>
  </NavDropdown>

: ''}

{isInRole(userId , 'super-admin' , Roles.GLOBAL_GROUP) ?

  <NavDropdown eventKey={8} title="Transaction" id="user-nav-dropdown">
    <LinkContainer to="/view_all_transactions" exact>
     <NavItem eventKey={ 8.2 } href="/view_all_transactions">All Transactions</NavItem>
    </LinkContainer>
   <LinkContainer to="/check_payment_status" exact>
     <NavItem eventKey={ 8.3 } href="/check_payment_status">Check Transactions Status</NavItem>
   </LinkContainer>
   <LinkContainer to="/transaction_report" exact>
     <NavItem eventKey={8.1} href="/transaction_report">Transaction Report</NavItem>
    </LinkContainer>
  </NavDropdown>

 : ''}

{isInRole(userId , 'super-admin' , Roles.GLOBAL_GROUP) ?

  <NavDropdown eventKey={9} title="Email Functions" id="user-nav-dropdown">
  <LinkContainer to="/admin/email_template_builder" exact>
     <NavItem eventKey={ 9.1 } href="/admin/email_template_builder">Create Email Template</NavItem>
   </LinkContainer>
    <LinkContainer to="/create_mailing_list" exact>
      <NavItem eventKey={ 9.2 } href="/create_mailing_list">Create Mail List</NavItem>
    </LinkContainer>
    <LinkContainer to="/send_bulk_email" exact>
    <NavItem eventKey={ 9.3 } href="/send_bulk_email">Send Bulk Mail</NavItem>
   </LinkContainer>
  </NavDropdown>

: ''}

{/* staff member route starts here*/}

{isInRole(userId , 'staffMember'  , 'staff') ?

  <LinkContainer to="/archives" exact>
    <NavItem eventKey={5} href="/send_message">
    <Icon icon="archive" /> Archives Paper
    </NavItem>
  </LinkContainer>

 : ''}

{isInRole(userId , 'staffMember'  , 'staff') ?

 <LinkContainer to="/submit_paper_for_author" exact>
    <NavItem eventKey={ 6 } href="/submit_paper_for_author">
    <Icon icon="book" /> Submit Paper For Authors</NavItem>
 </LinkContainer>

 : ''}

{/* staff member route ends here */}

{/* editor in cheif route starts here */}

{isInRole(userId , 'journalowner' , 'owners') ?

    <LinkContainer to="/dashboard/journal_owner" exact>
      <NavItem eventKey={ 6 } href="/dashboard/journal_owner">Dashboard</NavItem>
    </LinkContainer>

 : ''}

{isInRole(userId , 'journalowner' , 'owners') ?

  <NavDropdown eventKey={8} title="Manage Papers" id="editor-papers">
     <LinkContainer to="/assign_paper_to_reviewer" exact>
       <NavItem eventKey={ 8.1 } href="/assign_paper_to_reviewer">Assign Paper To Reviewer</NavItem>
     </LinkContainer>
     <LinkContainer to="/review_uploaded_papers" exact>
       <NavItem eventKey={ 8.2 } href="/review_uploaded_papers">Papers Reviewed By Reviewers</NavItem>
     </LinkContainer>
     <LinkContainer to="/view_resubmitted_papers" exact>
     <NavItem eventKey={ 8.3 } href="/view_resubmitted_papers">Resubmitted / Corrected Papers</NavItem>
   </LinkContainer>
   <LinkContainer to="/submit_paper_for_author" exact>
    <NavItem eventKey={ 8.4 } href="/submit_paper_for_author">Submit Paper For Authors</NavItem>
 </LinkContainer>

  </NavDropdown>

: ''}

{isInRole(userId , 'journalowner' , 'owners') ?

  <NavDropdown eventKey={9} title="Journal" id="editor-journal">
    <LinkContainer to="/manage_journal" exact>
      <NavItem eventKey={ 9.1 } href="/manage_journal">Manage Journal</NavItem>
    </LinkContainer>
    <LinkContainer to="/add_paper_journal_edition" exact>
      <NavItem eventKey={9.2} href="/add_paper_journal_edition">Add Paper To Journal</NavItem>
    </LinkContainer>
    <LinkContainer to="/add_edit_new_journal_edition" exact>
      <NavItem eventKey={9.3} href="/add_paper_journal_edition">New / Edit Journal Edition</NavItem>
    </LinkContainer>
    <LinkContainer to="/call_for_papers" exact>
      <NavItem eventKey={9.4} href="/call_for_papers">Call For Papers</NavItem>
    </LinkContainer>
    <LinkContainer to="/page_email_builder" exact>
      <NavItem eventKey={9.5} href="/page_email_builder">Page / Email Builder</NavItem>
    </LinkContainer>
    <LinkContainer to="/upload/doc_to_pdf" exact>
    <NavItem eventKey={ 9.5 } href="/upload/doc_to_pdf">Upload Pdf Copy</NavItem>
   </LinkContainer>
   <LinkContainer to="/archives" exact>
    <NavItem eventKey={ 9.7 } href="/archives">Archives</NavItem>
   </LinkContainer>
  </NavDropdown>

: ''}

{isInRole(userId , 'journalowner' , 'owners') ?

    <LinkContainer to="/journal_financial_transactions" exact>
      <NavItem eventKey={ 7 } href="/journal_financial_transactions">
      <Icon icon="money" /> Transactions</NavItem>
    </LinkContainer>

: ''}
{/* editor in chief route ends here}

{/*  Admin Routes ends here     */}

  {/* Editor Routes starts here*/}
  {isInRole(userId , 'editor' , 'editors' ) ?

        <LinkContainer to="/dashboard/editors_home" exact>
          <NavItem eventKey={ 3 } href="/dashboard/editors_home">Dashboard</NavItem>
        </LinkContainer>

    : ''}

   {isInRole(userId , 'reviewer' , 'editors' ) ?

        <LinkContainer to="/dashboard/reviewers_home" exact>
          <NavItem eventKey={ 3 } href="/dashboard/reviewers_home">Dashboard</NavItem>
        </LinkContainer>

    : ''}

{isInRole(userId , 'reviewer' , 'editors' ) ?

    <LinkContainer to="/submit_paper/new" exact>
    <NavItem eventKey={ 6 } href="/submit_paper/new">Submit Paper</NavItem>
    </LinkContainer>

 : ''}
  {/* Editor Routes ends here*/}

{/* Authenticated Routes for everyone starts here*/}

    <LinkContainer to="/check_notification_messages" exact>
      <NavItem eventKey={ 5 } href="/check_notification_messages">
       <Icon icon="bell" /> Notification({unReadCount})</NavItem>
    </LinkContainer>

  <LinkContainer to="/contact" exact>
    <NavItem eventKey={5} href="/contact">
    <Icon icon="address-book-o" /> Contact Us</NavItem>
  </LinkContainer>

  <NavDropdown eventKey={2} title={ {name} } id="user-nav-dropdown">

    <LinkContainer to="/profile" exact>
      <NavItem eventKey={2.1} href="/profile">Profile</NavItem>
    </LinkContainer>
    <MenuItem divider />
    <MenuItem eventKey={2.2} onClick={() => Meteor.logout()}>Logout</MenuItem>
  </NavDropdown>

  {/* Authenticated Routes for everyone ends here*/}

);

AuthenticatedNavigation.propTypes = {
name: PropTypes.string.isRequired,
};

export default AuthenticatedNavigation;


text:
namespace base {
class FilePath;
}

namespace installer {

// Deletes files that belong to old versions of Chrome. chrome.exe,
// new_chrome.exe and their associated version directories are never deleted.
// Also, no file is deleted for a given version if a .exe or .dll file for that
// version is in use. Returns true if no files that belong to an old version of
// Chrome remain.
bool DeleteOldVersions(const base::FilePath& install_dir);

}  // namespace installer

#endif  // CHROME_INSTALLER_UTIL_DELETE_OLD_VERSIONS_H_


text:
module DNS
  class Zone
    # Version number (major.minor.tiny)
    Version = '0.3.1'
  end
end