text:
namespace lld {
namespace elf {
class Symbol;
class InputSection;
class InputSectionBase;
class OutputSection;
class SectionBase;

// Represents a relocation type, such as R_X86_64_PC32 or R_ARM_THM_CALL.
typedef uint32_t RelType;

// List of target-independent relocation types. Relocations read
// from files are converted to these types so that the main code
// doesn't have to know about architecture-specific details.
enum RelExpr {
  R_INVALID,
  R_ABS,
  R_ADDEND,
  R_ARM_SBREL,
  R_GOT,
  R_GOTONLY_PC,
  R_GOTONLY_PC_FROM_END,
  R_GOTREL,
  R_GOTREL_FROM_END,
  R_GOT_FROM_END,
  R_GOT_OFF,
  R_GOT_PAGE_PC,
  R_GOT_PC,
  R_HINT,
  R_MIPS_GOTREL,
  R_MIPS_GOT_GP,
  R_MIPS_GOT_GP_PC,
  R_MIPS_GOT_LOCAL_PAGE,
  R_MIPS_GOT_OFF,
  R_MIPS_GOT_OFF32,
  R_MIPS_TLSGD,
  R_MIPS_TLSLD,
  R_NEG_TLS,
  R_NONE,
  R_PAGE_PC,
  R_PC,
  R_PLT,
  R_PLT_PAGE_PC,
  R_PLT_PC,
  R_PPC_CALL,
  R_PPC_CALL_PLT,
  R_PPC_TOC,
  R_RELAX_GOT_PC,
  R_RELAX_GOT_PC_NOPIC,
  R_RELAX_TLS_GD_TO_IE,
  R_RELAX_TLS_GD_TO_IE_ABS,
  R_RELAX_TLS_GD_TO_IE_END,
  R_RELAX_TLS_GD_TO_IE_GOT_OFF,
  R_RELAX_TLS_GD_TO_IE_PAGE_PC,
  R_RELAX_TLS_GD_TO_LE,
  R_RELAX_TLS_GD_TO_LE_NEG,
  R_RELAX_TLS_IE_TO_LE,
  R_RELAX_TLS_LD_TO_LE,
  R_RELAX_TLS_LD_TO_LE_ABS,
  R_SIZE,
  R_TLS,
  R_TLSDESC,
  R_TLSDESC_CALL,
  R_TLSDESC_PAGE,
  R_TLSGD_GOT,
  R_TLSGD_GOT_FROM_END,
  R_TLSGD_PC,
  R_TLSLD_GOT,
  R_TLSLD_GOT_FROM_END,
  R_TLSLD_GOT_OFF,
  R_TLSLD_HINT,
  R_TLSLD_PC,
};

// Build a bitmask with one bit set for each RelExpr.
//
// Constexpr function arguments can't be used in static asserts, so we
// use template arguments to build the mask.
// But function template partial specializations don't exist (needed
// for base case of the recursion), so we need a dummy struct.
template <RelExpr... Exprs> struct RelExprMaskBuilder {
  static inline uint64_t build() { return 0; }
};

// Specialization for recursive case.
template <RelExpr Head, RelExpr... Tail>
struct RelExprMaskBuilder<Head, Tail...> {
  static inline uint64_t build() {
    static_assert(0 <= Head && Head < 64,
                  "RelExpr is too large for 64-bit mask!");
    return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build();
  }
};

// Return true if `Expr` is one of `Exprs`.
// There are fewer than 64 RelExpr's, so we can represent any set of
// RelExpr's as a constant bit mask and test for membership with a
// couple cheap bitwise operations.
template <RelExpr... Exprs> bool isRelExprOneOf(RelExpr Expr) {
  assert(0 <= Expr && (int)Expr < 64 &&
         "RelExpr is too large for 64-bit mask!");
  return (uint64_t(1) << Expr) & RelExprMaskBuilder<Exprs...>::build();
}

// Architecture-neutral representation of relocation.
struct Relocation {
  RelExpr Expr;
  RelType Type;
  uint64_t Offset;
  int64_t Addend;
  Symbol *Sym;
};

template <class ELFT> void scanRelocations(InputSectionBase &);

class ThunkSection;
class Thunk;
struct InputSectionDescription;

class ThunkCreator {
public:
  // Return true if Thunks have been added to OutputSections
  bool createThunks(ArrayRef<OutputSection *> OutputSections);

  // The number of completed passes of createThunks this permits us
  // to do one time initialization on Pass 0 and put a limit on the
  // number of times it can be called to prevent infinite loops.
  uint32_t Pass = 0;

private:
  void mergeThunks(ArrayRef<OutputSection *> OutputSections);

  ThunkSection *getISDThunkSec(OutputSection *OS, InputSection *IS,
                               InputSectionDescription *ISD, uint32_t Type,
                               uint64_t Src);

  ThunkSection *getISThunkSec(InputSection *IS);

  void createInitialThunkSections(ArrayRef<OutputSection *> OutputSections);

  void forEachInputSectionDescription(
      ArrayRef<OutputSection *> OutputSections,
      llvm::function_ref<void(OutputSection *, InputSectionDescription *)> Fn);

  std::pair<Thunk *, bool> getThunk(Symbol &Sym, RelType Type, uint64_t Src);

  ThunkSection *addThunkSection(OutputSection *OS, InputSectionDescription *,
                                uint64_t Off);

  bool normalizeExistingThunk(Relocation &Rel, uint64_t Src);

  // Record all the available Thunks for a Symbol
  llvm::DenseMap<std::pair<SectionBase *, uint64_t>, std::vector<Thunk *>>
      ThunkedSymbolsBySection;
  llvm::DenseMap<Symbol *, std::vector<Thunk *>> ThunkedSymbols;

  // Find a Thunk from the Thunks symbol definition, we can use this to find
  // the Thunk from a relocation to the Thunks symbol definition.
  llvm::DenseMap<Symbol *, Thunk *> Thunks;

  // Track InputSections that have an inline ThunkSection placed in front
  // an inline ThunkSection may have control fall through to the section below
  // so we need to make sure that there is only one of them.
  // The Mips LA25 Thunk is an example of an inline ThunkSection.
  llvm::DenseMap<InputSection *, ThunkSection *> ThunkedSections;
};

// Return a int64_t to make sure we get the sign extension out of the way as
// early as possible.
template <class ELFT>
static inline int64_t getAddend(const typename ELFT::Rel &Rel) {
  return 0;
}
template <class ELFT>
static inline int64_t getAddend(const typename ELFT::Rela &Rel) {
  return Rel.r_addend;
}
} // namespace elf
} // namespace lld

#endif


text:
//
//  KINWebBrowserViewController.h
//
//  KINWebBrowser
//
//  Created by David F. Muir V
//  dfmuir@gmail.com
//  Co-Founder & Engineer at Kinwa, Inc.
//  http://www.kinwa.co
//
//  The MIT License (MIT)
//
//  Copyright (c) 2014 David Muir
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>

@class KINWebBrowserViewController;

/*

 UINavigationController+KINWebBrowserWrapper category enables access to casted KINWebBroswerViewController when set as rootViewController of UINavigationController

 */
@interface UINavigationController(KINWebBrowser)

// Returns rootViewController casted as KINWebBrowserViewController
- (KINWebBrowserViewController *)rootWebBrowser;

@end

@protocol KINWebBrowserDelegate <NSObject>
@optional
- (void)webBrowser:(KINWebBrowserViewController *)webBrowser didStartLoadingURL:(NSURL *)URL;
- (void)webBrowser:(KINWebBrowserViewController *)webBrowser didFinishLoadingURL:(NSURL *)URL;
- (void)webBrowser:(KINWebBrowserViewController *)webBrowser didFailToLoadURL:(NSURL *)URL error:(NSError *)error;
- (void)webBrowserViewControllerWillDismiss:(KINWebBrowserViewController*)viewController;
@end

/*

 KINWebBrowserViewController is designed to be used inside of a UINavigationController.
 For convenience, two sets of static initializers are available.

 */
@interface KINWebBrowserViewController : UIViewController <WKNavigationDelegate, UIWebViewDelegate>

#pragma mark - Public Properties

@property (nonatomic, weak) id <KINWebBrowserDelegate> delegate;

// The main and only UIProgressView
@property (nonatomic, strong) UIProgressView *progressView;

// The web views
// Depending on the version of iOS, one of these will be set
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIWebView *uiWebView;

- (id)initWithConfiguration:(WKWebViewConfiguration *)configuration NS_AVAILABLE_IOS(8_0);

#pragma mark - Static Initializers

/*
 Initialize a basic KINWebBrowserViewController instance for push onto navigation stack

 Ideal for use with UINavigationController pushViewController:animated: or initWithRootViewController:

 Optionally specify KINWebBrowser options or WKWebConfiguration
 */

+ (KINWebBrowserViewController *)webBrowser;
+ (KINWebBrowserViewController *)webBrowserWithConfiguration:(WKWebViewConfiguration *)configuration NS_AVAILABLE_IOS(8_0);

/*
 Initialize a UINavigationController with a KINWebBrowserViewController for modal presentation.

 Ideal for use with presentViewController:animated:

 Optionally specify KINWebBrowser options or WKWebConfiguration
 */

+ (UINavigationController *)navigationControllerWithWebBrowser;
+ (UINavigationController *)navigationControllerWithWebBrowserWithConfiguration:(WKWebViewConfiguration *)configuration NS_AVAILABLE_IOS(8_0);

@property (nonatomic, strong) UIColor *tintColor;
@property (nonatomic, strong) UIColor *barTintColor;
@property (nonatomic, assign) BOOL actionButtonHidden;
@property (nonatomic, assign) BOOL showsURLInNavigationBar;
@property (nonatomic, assign) BOOL showsPageTitleInNavigationBar;

//Allow for custom activities in the browser by populating this optional array
@property (nonatomic, strong) NSArray *customActivityItems;

#pragma mark - Public Interface

// Load a NSURL to webView
// Can be called any time after initialization
- (void)loadURL:(NSURL *)URL;

// Loads a URL as NSString to webView
// Can be called any time after initialization
- (void)loadURLString:(NSString *)URLString;

// Load a NSURLRequest
// Can be called any time after initialization
- (void)loadRequest:(NSURLRequest *)request;

@end

redpajama_set_name: RedPajamaGithub


text:
import Immutable from 'immutable';

export default function (state = Immutable.Map({}), action) {
    let relationships;

    switch (action.type) {
    case 'PAGE_ADD':
        relationships = state.get(action.data.id) || Immutable.Map({});
        return state.set(action.data.id, relationships);

    case 'PAGE_REMOVE':
        return state.delete(action.data.id);

    case 'RELATIONSHIP_ADD':
        relationships = state.get(action.data.proposer_id) || Immutable.Map({});
        return state.set(action.data.proposer_id, relationships.set(action.data.id, action.data));

    case 'RELATIONSHIP_REMOVE':
        relationships = state.get(action.data.proposer_id) || Immutable.Map({});
        return state.set(action.data.proposer_id, relationships.delete(action.data.id));

    default:
        return state;
    }
}


text:
"""Send e-mail notification to system administrators."""

import email
import smtplib
import socket
import subprocess

def notify(subject, whom, what):
    """Send email notification.

    Try to notify the addressee (``whom``) by e-mail, with Subject:
    defined by ``subject`` and message body by ``what``.

    """
    msg = email.message_from_string(what)
    msg.add_header("From", "Certbot renewal agent <root>")
    msg.add_header("To", whom)
    msg.add_header("Subject", subject)
    msg = msg.as_string()
    try:
        lmtp = smtplib.LMTP()
        lmtp.connect()
        lmtp.sendmail("root", [whom], msg)
    except (smtplib.SMTPHeloError, smtplib.SMTPRecipientsRefused,
            smtplib.SMTPSenderRefused, smtplib.SMTPDataError, socket.error):
        # We should try using /usr/sbin/sendmail in this case
        try:
            proc = subprocess.Popen(["/usr/sbin/sendmail", "-t"],
                                    stdin=subprocess.PIPE)
            proc.communicate(msg)
        except OSError:
            return False
    return True


text:
package org.unicef.gis.ui;

import org.unicef.gis.R;
import org.unicef.gis.infrastructure.Network;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class FetchTagsActivity extends Activity {
	private ProgressBar progress;
	private TextView feedback;
	private Button goToNetworkSettings;
	private Button retry;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fetch_tags);

		loadControls();

		goToNetworkSettings.setText(R.string.go_to_network_settings);
		retry.setText(R.string.retry);
	}

	@Override
	protected void onResume() {
		super.onResume();
		checkConnectivity();
	}

	public void editNetworkSettings(View view){
		startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
	}

	public void retry(View view) {
		checkConnectivity();
	}

	private void checkConnectivity() {
		Network network = new Network(this);
		if (!network.connected()) {
			feedback.setText(R.string.fetch_tags_not_connected);
			progress.setVisibility(View.GONE);
			goToNetworkSettings.setVisibility(View.VISIBLE);
			retry.setVisibility(View.GONE);
		} else {
			feedback.setText(R.string.wait_configuring);
			progress.setVisibility(View.VISIBLE);
			goToNetworkSettings.setVisibility(View.GONE);
			retry.setVisibility(View.GONE);

			//If connectivity is alright, fetch the tags
			fetchTags();
		}
	}

	private void fetchTags() {
		FetchTagsTask fetchTagsTask = new FetchTagsTask(this);
		fetchTagsTask.execute();
	}

	private void loadControls() {
		progress = (ProgressBar) findViewById(R.id.fetch_tags_activity_progress);
		feedback = (TextView) findViewById(R.id.fetch_tags_feedback);
		goToNetworkSettings = (Button) findViewById(R.id.fetch_tags_go_to_network_settings);
		retry = (Button) findViewById(R.id.fetch_tags_retry);
	}

	public void onFetchTagsResult(Integer result) {
		if (result == FetchTagsTask.RESULT_SUCCESS){
			startActivity(new Intent(this, MyReportsActivity.class));
		} else if (result == FetchTagsTask.SERVER_URL_PREFERENCE_NOT_SET) {
			startActivity(new Intent(this, ConfigureServerUrlActivity.class));
		}
		else {
			feedback.setText(R.string.something_wrong_fetching_tags);
			progress.setVisibility(View.GONE);
			goToNetworkSettings.setVisibility(View.GONE);
			retry.setVisibility(View.VISIBLE);
		}
	}
}


text:
"""Nikola -- a modular, fast, simple, static website generator."""

from __future__ import absolute_import
import os

__version__ = "7.6.4"
DEBUG = bool(os.getenv('NIKOLA_DEBUG'))

from .nikola import Nikola  # NOQA
from . import plugins  # NOQA


text:
import constants from './constants'
import stylus from 'stylus'
import nib from 'nib'

const use = (app) => {
  const middleware = stylus.middleware({
    src: constants.stylesDir,
    dest: constants.staticStylesDir,
    compile: function (str, path) {
      return stylus(str)
      .set('filename', path)
      .use(nib())
      .import('nib');
    }
  });
  app.get(`/${constants.appCSS}`, middleware);
}

export default { use };


text:
package de.tuberlin.dima.ti.pcb;

import org.apache.flink.api.common.functions.FlatJoinFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * creates two-leg flights by joining non-stop flights and pruning the result
 */
public class FilteringConnectionJoiner implements FlatJoinFunction<Flight, Flight, Tuple2<Flight, Flight>> {

    private final String exceptionsGeneral = "ABHIMTDEG";
    private final String exceptionsInternational = "NOQW";
    private final String exceptionsDomestic = "C";

    @Override
    public void join(Flight in1, Flight in2, Collector<Tuple2<Flight, Flight>> out)
            throws Exception {
        // sanity check
        if (!in1.getDestinationCity().equals(in2.getOriginCity())) {
            throw new Exception("Hub city mismatch: " + in1.toString() + " / " + in2.toString());
        }
        long hubTime = in2.getDepartureTimestamp() - in1.getArrivalTimestamp();
        long travelTime = in2.getArrivalTimestamp() - in1.getDepartureTimestamp();
        if (hubTime <= 0L) {
            // arrival before departure
            return;
        }
        if (hubTime < (CBUtil.computeMinCT() * 60L * 1000L)) {
            return;
        }
        double ODDistance = CBUtil.dist(in1.getOriginLatitude(), in1.getOriginLongitude(), in2.getDestinationLatitude(), in2.getDestinationLongitude());
        if (hubTime > ((CBUtil.computeMaxCT(ODDistance)) * 60L * 1000L)) {
            return;
        }
        if (in1.getOriginAirport().equals(in2.getDestinationAirport())) {
            // some multi-leg flights are circular
            return;
        }
        if (in1.getAirline().equals(in2.getAirline()) &&
            in1.getFlightNumber().equals(in2.getFlightNumber()) &&
            in1.getAircraftType().equals(in2.getAircraftType())) {
            // multi-leg flight connections have already been built
            return;
        }
        // check traffic restrictions
        if ((exceptionsGeneral.indexOf(in1.getTrafficRestriction()) >= 0) ||
                (exceptionsGeneral.indexOf(in2.getTrafficRestriction()) >= 0)) {
            return;
        } else if (!CBUtil.isDomestic(in2) && exceptionsDomestic.indexOf(in1.getTrafficRestriction()) >= 0) {
            return;
        } else if (!CBUtil.isDomestic(in1) && exceptionsDomestic.indexOf(in2.getTrafficRestriction()) >= 0) {
            return;
        } else if (CBUtil.isDomestic(in2) && exceptionsInternational.indexOf(in1.getTrafficRestriction()) >= 0) {
            return;
        } else if (CBUtil.isDomestic(in1) && exceptionsInternational.indexOf(in2.getTrafficRestriction()) >= 0) {
            return;
        }
        if (CBUtil.isODDomestic(in1, in2)) {
            if (!CBUtil.isDomestic(in1)) {
                if (hubTime > 240L * 60L * 1000L ||
                    !CBUtil.geoDetourAcceptable(in1.getOriginLatitude(), in1.getOriginLongitude(),
                                in1.getDestinationLatitude(), in1.getDestinationLongitude(),
                                in2.getDestinationLatitude(), in2.getDestinationLongitude())) {
                    // for domestic connections with the hub in another country the MaxCT is 240 min
                    // and geoDetour applies
                    return;
                }
            } else {
                if (travelTime > (CBUtil.travelTimeAt100kphInMinutes(ODDistance) * 60L * 1000L)) {
                    // if on a domestic flight we are faster than 100 km/h in a straight line between
                    // origin and destination the connection is built even if geoDetour is exceeded
                    // this is to preserve connection via domestic hubs like TLS-ORY-NCE
                    return;
                }
            }
        } else {
            if (!CBUtil.geoDetourAcceptable(in1.getOriginLatitude(), in1.getOriginLongitude(),
                    in1.getDestinationLatitude(), in1.getDestinationLongitude(),
                    in2.getDestinationLatitude(), in2.getDestinationLongitude())) {
                return;
            }
        }
        if (in1.getAirline().equals(in2.getAirline())) {
            // same airline
            out.collect(new Tuple2<Flight, Flight>(in1, in2));
        } else if (in1.getCodeShareInfo().isEmpty() && in2.getCodeShareInfo().isEmpty()) {
            // not the same airline and no codeshare information
            return;
        } else {
            // check if a connection can be made via codeshares
            String[] codeshareAirlines1 = null;
            if (!in1.getCodeShareInfo().isEmpty()) {
                String[] codeshareInfo1 = in1.getCodeShareInfo().split("/");
                codeshareAirlines1 = new String[codeshareInfo1.length + 1];
                for (int i = 0; i < codeshareInfo1.length; i++) {
                    codeshareAirlines1[i] = codeshareInfo1[i].substring(0, 2);
                }
                codeshareAirlines1[codeshareAirlines1.length - 1] = in1.getAirline();
            } else {
                codeshareAirlines1 = new String[]{in1.getAirline()};
            }
            String[] codeshareAirlines2 = null;
            if (!in2.getCodeShareInfo().isEmpty()) {
                String[] codeshareInfo2 = in2.getCodeShareInfo().split("/");
                codeshareAirlines2 = new String[codeshareInfo2.length + 1];
                for (int i = 0; i < codeshareInfo2.length; i++) {
                    codeshareAirlines2[i] = codeshareInfo2[i].substring(0, 2);
                }
                codeshareAirlines2[codeshareAirlines2.length - 1] = in2.getAirline();
            } else {
                codeshareAirlines2 = new String[]{in2.getAirline()};
            }
            for (int i = 0; i < codeshareAirlines1.length; i++) {
                for (int j = 0; j < codeshareAirlines2.length; j++) {
                    if (codeshareAirlines1[i].equals(codeshareAirlines2[j])) {
                        out.collect(new Tuple2<Flight, Flight>(in1, in2));
                        return;
                    }
                }
            }
        }
    }

}


text:
package org.apache.felix.webconsole.internal.configuration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.apache.felix.webconsole.spi.ConfigurationHandler;
import org.apache.felix.webconsole.spi.ValidationException;
import org.junit.Test;

public class ConfigJsonSupportTest {

    @Test public void testGetPropertyNamesForFormNoHandler() throws IOException {
        final ConfigJsonSupport support = new ConfigJsonSupport(null, null, null, Collections.emptyList());

        final Dictionary<String, Object> dict = new Hashtable<>();
        dict.put("a", "1");
        dict.put("b", "2");

        support.filterConfigurationProperties("f", "p", dict);

        assertEquals(2, dict.size());
        assertEquals("1", dict.get("a"));
        assertEquals("2", dict.get("b"));
    }

    @Test public void testGetPropertyNamesForFormHandlerNoFiltering() throws IOException {
        final ConfigurationHandler handler = new ConfigurationHandler() {

            @Override
            public void createConfiguration(String pid) throws ValidationException, IOException {
            }

            @Override
            public void createFactoryConfiguration(String factoryPid, String name)
                    throws ValidationException, IOException {
            }

            @Override
            public void deleteConfiguration(String factoryPid, String pid) throws ValidationException, IOException {
            }

            @Override
            public void updateConfiguration(String factoryPid, String pid, Dictionary<String, Object> props)
                    throws ValidationException, IOException {
            }

        };
        final ConfigJsonSupport support = new ConfigJsonSupport(null, null, null, Collections.singletonList(handler));

        final Dictionary<String, Object> dict = new Hashtable<>();
        dict.put("a", "1");
        dict.put("b", "2");

        support.filterConfigurationProperties("f", "p", dict);

        assertEquals(2, dict.size());
        assertEquals("1", dict.get("a"));
        assertEquals("2", dict.get("b"));
    }

    @Test public void testGetPropertyNamesForFormHandlerFiltering() throws IOException {
        final ConfigurationHandler handler = new ConfigurationHandler() {

            @Override
            public void createConfiguration(String pid) throws ValidationException, IOException {
            }

            @Override
            public void createFactoryConfiguration(String factoryPid, String name)
                    throws ValidationException, IOException {
            }

            @Override
            public void deleteConfiguration(String factoryPid, String pid) throws ValidationException, IOException {
            }

            @Override
            public void updateConfiguration(String factoryPid, String pid, Dictionary<String, Object> props)
                    throws ValidationException, IOException {
            }

            @Override
            public void filterProperties(String factoryPid, String pid, Collection<String> propertyNames)
                    throws IOException {
                propertyNames.remove("b");
                propertyNames.remove("c");
            }

        };
        final ConfigJsonSupport support = new ConfigJsonSupport(null, null, null, Collections.singletonList(handler));

        final Dictionary<String, Object> dict = new Hashtable<>();
        dict.put("a", "1");
        dict.put("b", "2");

        support.filterConfigurationProperties("f", "p", dict);

        assertEquals(1, dict.size());
        assertEquals("1", dict.get("a"));
    }
}


text:
if(!dojo._hasResource["dijit.form.Slider"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form.Slider"] = true;
dojo.provide("dijit.form.Slider");

dojo.deprecated("Call require() for HorizontalSlider / VerticalRule, explicitly rather than 'dijit.form.Slider' itself", "", "2.0");

// For back-compat, remove for 2.0
dojo.require("dijit.form.HorizontalSlider");
dojo.require("dijit.form.VerticalSlider");
dojo.require("dijit.form.HorizontalRule");
dojo.require("dijit.form.VerticalRule");
dojo.require("dijit.form.HorizontalRuleLabels");
dojo.require("dijit.form.VerticalRuleLabels");

}


text:
<?php

namespace Nim\Bundle\WorkerBundle\Form\Type\Filter;

use Nim\Bundle\WorkerBundle\Model\Worker\WorkerTypes;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class WorkerType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('lastname', null, array(
                'label' => 'worker.field.name.label',
            ))
            ->add('type', 'choice', array(
                'label' => 'worker.field.type.label',
                'choices' => WorkerTypes::getTypes('worker.field.type.option'),
            ))
            ->add('arrivedAt', 'date', array(
                'label' => 'worker.field.arrivedAt.label',
            ))
            ->add('basedAt', 'entity', array(
                'label' => 'worker.field.basedAt.label',
                'class' => 'Nim\Bundle\WorkerBundle\Model\Agency',
                'property' => 'name',
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection' => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'nim_filter_worker';
    }
}


text:
'use strict'

var config = require('configg')(__dirname)

var M = function () {
  return {
    c: config
  }
}

module.exports = M

if (module === require.main) {
  console.log(JSON.stringify(M(), null, 2))
}


text:
Asian Americans in New York Summer Seminar Website
==================================================

The project website for the NEH funded Asian Americans in New York: Literature & Film summer seminar.

Built using [yeoman](http://yeoman.io/), [grunt](http://gruntjs.com/), and [bower](http://bower.io/).

Bootstrapped using the Yeoman [bootstrap-less generator](https://github.com/Thomas-Lebeau/generator-bootstrap-less).

Themed using the [Start Bootstrap](http://startbootstrap.com) [Agency Template](http://startbootstrap.com/template-overviews/agency/).

Utilizes the following libraries:
- [Bootstrap](getbootstrap.com) frontend framework
- [jquery](http://jquery.com/)
- [jquery-ui](http://jqueryui.com/)
- [modernizr](http://modernizr.com/)

Installation
------------
###Check for and install required tools
Make sure your system has [Node.js](http://nodejs.org/download/), [grunt](http://gruntjs.com/), and [bower](http://bower.io/) already installed.
Entering the command `$ node -v` at the command line should return something like `v0.10.32`. If not, you need to install Node.js by following the link above.
Entering the command `$ which grunt` at the command line should return something like `grunt: aliased to grunt --stack`. If not, install grunt (full directions at the above link) using the following command at the command line (you may need to use sudo on OS X and *nix):
```
$ npm install -g grunt-cli
```
Entering the command `$ bower -v` at the command line should return something like `1.3.12`. If not, install bower (full directions at the above link) using the following command at the command line:
```
$ npm install -g bower
```

###Clone the GitHub repository
Enter the following command at the command line:
```
$ git clone git://github.com/kaymmm/AsAminNYC.git
```

###Initialize the Git Repo Using Bower and NPM
Enter the following command at the command line:
```
$ npm install
$ bower install
$ cd test
$ bower install
$ cd ..
```
This will download all of the required bower and npm dependencies, as well as the dependencies for the mocha test suite (grunt will fail otherwise).

###Grunt the project
Once all of the required tools are installed, you can test the site using the following commands:
```
$ cd AsAminNYC
$ grunt serve
```
A browser window should open a "live view" of the site. To quit grunt at the command line, hit ctrl-c (^c)

Compiling
---------
To compile the site, just type `$ grunt` at the command line. The "dist" folder should be updated with the compiled files.


text:
package org.openkilda.northbound.dto.v2.yflows;

import org.openkilda.northbound.dto.v2.flows.FlowPatchEndpoint;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
@AllArgsConstructor
@JsonNaming(value = SnakeCaseStrategy.class)
public class SubFlowPatchPayload {
    String flowId;
    FlowPatchEndpoint endpoint;
    YFlowPatchSharedEndpointEncapsulation sharedEndpoint;
    String description;
}


text:
@interface DetailVC ()

@end

@implementation DetailVC

- (void)viewDidLoad {
    [super viewDidLoad];

  self.titleLabel.text = self.t;
  self.detailLabel.text = self.c;
}
@end


text:
template <typename Geometry>
void test_linestring()
{
    BOOST_CONCEPT_ASSERT( (bg::concept::Linestring<Geometry>) );
    BOOST_CONCEPT_ASSERT( (bg::concept::ConstLinestring<Geometry>) );

    Geometry geometry;
    typedef typename bg::point_type<Geometry>::type P;

    bg::clear(geometry);
    BOOST_CHECK_EQUAL(boost::size(geometry), 0u);

    bg::append(geometry, bg::make<P>(1, 2));
    BOOST_CHECK_EQUAL(boost::size(geometry), 1u);

    bg::append(geometry, bg::make<P>(3, 4));
    BOOST_CHECK_EQUAL(boost::size(geometry), 2u);

    bg::traits::resize<Geometry>::apply(geometry, 1);
    BOOST_CHECK_EQUAL(boost::size(geometry), 1u);

    //std::cout << bg::dsv(geometry) << std::endl;
    P p = *boost::begin(geometry);
    //std::cout << bg::dsv(p) << std::endl;
    BOOST_CHECK_EQUAL(bg::get<0>(p), 1);
    BOOST_CHECK_EQUAL(bg::get<1>(p), 2);

    bg::clear(geometry);
    BOOST_CHECK_EQUAL(boost::size(geometry), 0u);
}

template <typename Point>
void test_all()
{
    test_linestring<bg::model::linestring<Point> >();
    test_linestring<test::wrapped_boost_array<Point, 10> >();
    test_linestring<all_custom_linestring<Point> >();
}

int test_main(int, char* [])
{
    test_all<bg::model::point<int, 2, bg::cs::cartesian> >();
    test_all<bg::model::point<float, 2, bg::cs::cartesian> >();
    test_all<bg::model::point<double, 2, bg::cs::cartesian> >();

    return 0;
}


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.query2.engine;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.Argument;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.ArgumentType;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.QueryFunction;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Implementation of the allpaths() function.
 */
public class AllPathsFunction implements QueryFunction {
  AllPathsFunction() {
  }

  @Override
  public String getName() {
    return "allpaths";
  }

  @Override
  public int getMandatoryArguments() {
    return 2;
  }

  @Override
  public List<ArgumentType> getArgumentTypes() {
    return ImmutableList.of(ArgumentType.EXPRESSION, ArgumentType.EXPRESSION);
  }

  @Override
  public <T> Set<T> eval(QueryEnvironment<T> env, QueryExpression expression, List<Argument> args)
      throws QueryException {
    QueryExpression from = args.get(0).getExpression();
    QueryExpression to = args.get(1).getExpression();

    Set<T> fromValue = from.eval(env);
    Set<T> toValue = to.eval(env);

    // Algorithm: compute "reachableFromX", the forward transitive closure of
    // the "from" set, then find the intersection of "reachableFromX" with the
    // reverse transitive closure of the "to" set.  The reverse transitive
    // closure and intersection operations are interleaved for efficiency.
    // "result" holds the intersection.

    env.buildTransitiveClosure(expression, fromValue, Integer.MAX_VALUE);

    Set<T> reachableFromX = env.getTransitiveClosure(fromValue);
    Set<T> result = intersection(reachableFromX, toValue);
    Collection<T> worklist = result;
    while (!worklist.isEmpty()) {
      Collection<T> reverseDeps = env.getReverseDeps(worklist);
      worklist = new ArrayList<>();
      for (T np : reverseDeps) {
        if (reachableFromX.contains(np)) {
          if (result.add(np)) {
            worklist.add(np);
          }
        }
      }
    }
    return result;
  }

  /**
   * Returns a (new, mutable, unordered) set containing the intersection of the
   * two specified sets.
   */
  private static <T> Set<T> intersection(Set<T> x, Set<T> y) {
    Set<T> result = new HashSet<>();
    if (x.size() > y.size()) {
      Sets.intersection(y, x).copyInto(result);
    } else {
      Sets.intersection(x, y).copyInto(result);
    }
    return result;
  }
}


text:
:- module(logicmoo_planner,[load_planner_api/0]).

:- style_check(-singleton).

:- use_module(library(prolog_pack)).

:- if( \+ prolog_pack:current_pack(logicmoo_ec)).
:- add_absolute_search_folder(pack,'../../').
:- attach_packs.
:- initialization(attach_packs).
:- endif.

%:-  add_absolute_search_folder(ext,('../ext/')).
:-  add_absolute_search_folder(ext,library('../ext/')).
%:-  add_absolute_search_folder(pack,library('../prolog/../..')).

:- if( \+  user:file_search_path(pddl,_) ).

:-  add_absolute_search_folder(pddl,library('../test/pddl_tests/')),
    add_absolute_search_folder(pddl,library('../test/pddl_reader/')),
    add_absolute_search_folder(pddl,library('../test/uw-yale-pddl/strict-domains/')),
    add_absolute_search_folder(pddl,library('../test/uw-yale-pddl/domains/')),
    !.

:- endif.

:- module_transparent(export_transparent/1).
export_transparent(P):-
  export(P),
  module_transparent(P).

% [Required] Load the Logicmoo Library Utils
% :- ensure_loaded(library(logicmoo_hyhtn)).
%
% load_planner_api:- ensure_loaded(library(rsasak_forward_wa_star_h_add)).
%:- initialization(load_planner, program).
load_planner_api.

test_all:-test_all(7).

test_all(N):- must_filematch_list(pddl('orig_pddl_parser/test/?*?/domain*.pddl'),RList),RList\=[],!,reverse(RList,List),
  forall(member(E,List),once(test_domain(E,N))).

test_all(N):-
  must_filematch(pddl('orig_pddl_parser/test/?*?/domain*.pddl'),_),!,
  (forall(must_filematch(pddl('orig_pddl_parser/test/?*?/domain*.pddl'),E),
                                                 once(test_domain(E,N)))).

:- thread_local(t_l:loading_files/0).

test_domain(DP):- t_l:loading_files,!,must(test_domain(DP)).
test_domain(DP):- test_domain(DP,12).

min_sas(A,B,A):-A =< B,!.
min_sas(_,A,A).

test_domain(DP,Num):- \+ atom(DP),forall((filematch_smart(DP,FOUND),exists_file(FOUND)),test_domain(FOUND,Num)),!.
test_domain(DP,Num):- \+ exists_file(DP),!, forall(must_filematch(DP,MATCH),(exists_file(MATCH),test_domain(MATCH,Num))).
test_domain(DP,Num):-
   format('~q.~n',[test_domain(DP)]),
  directory_file_path(D,_,DP),directory_files(D,RList),reverse(RList,ListR),
   sort(ListR,ListS),length(ListR,PosNum),min_sas(PosNum,Num,MinNum),length(List,MinNum),append(List,_,ListS),!,
   test_domain_num(DP,List,Num).

test_domain_num(DP,List,Num):-
  directory_file_path(D,_,DP),
  forall(member(T,List),ignore((directory_file_path(D,T,TP),exists_file(TP),not(same_file(DP,TP)),
  planner_solve_files(DP,TP)))).

% planner_solve_files(+DomainFile, +ProblemFile)
%
%   Reads files and set timelimit for planner
%
planner_solve_files(DomainFile, ProblemFile):-
 forall(must(must_filematch(DomainFile,DomainFile0)),
   forall(must(must_filematch(ProblemFile,ProblemFile0)),
     (time(show_call(planner_solve_abs_file(DomainFile0, ProblemFile0)))))),!.

% Reads files and set timelimit for planner
planner_solve_abs_file(DomainFile, ProblemFile):-
       update_changed_files,
       directory_file_path(_,File,ProblemFile),
       wdmsg(planner_solve_files(DomainFile, ProblemFile)),
       planner_solve_abs_file(DomainFile, ProblemFile, File),!.

planner_solve_abs_file(DomainFile, ProblemFile, File):- slow_on(File),!,wdmsg(slow_on(DomainFile, ProblemFile)).
planner_solve_abs_file(DomainFile, ProblemFile, File):-
                nop(time((test_solve_files(DomainFile, ProblemFile)))),
                (time(show_call(logicmoo_ocl_and_pddl:solve_files_w_ocl(DomainFile, ProblemFile)))),
                nop(time(show_call(solve_files_w_lps(DomainFile, ProblemFile)))),
                !.

test_solve_files(D,P):- call(call,solve_files,D,P).

test_dir_sas(DirIn):-forall(must_filematch(DirIn,DirInM),test_dir_m(DirInM)).
test_dir_m(DIR):-
  working_directory(WAS,WAS),
     call_cleanup((
        cd(DIR),
        wdmsg(test_dir_files_sas(DIR)),
	%write('Testing ':DIR), nl,
	test_dir_files_sas(DIR)),
        cd(WAS)).

test_dir_files_sas(PDDLDir,D,P):- filematch_smart(PDDLDir,Dir),
        directory_file_path(Dir,D,DF),
        directory_file_path(Dir,P,PF),
        nop((test_parse_file(DF),test_parse_file(PF))),
        planner_solve_files(DF,PF),!.

test_dir_files_sas(Dir):-
	test_dir_files_sas(Dir,'p01-domain.pddl','p01.pddl'),
	test_dir_files_sas(Dir,'p02-domain.pddl','p02.pddl'),
	test_dir_files_sas(Dir,'p03-domain.pddl','p03.pddl'),
	test_dir_files_sas(Dir,'p04-domain.pddl','p04.pddl'),
	test_dir_files_sas(Dir,'p05-domain.pddl','p05.pddl'),
	test_dir_files_sas(Dir,'p06-domain.pddl','p06.pddl'),
	test_dir_files_sas(Dir,'p07-domain.pddl','p07.pddl'),
	test_dir_files_sas(Dir,'p08-domain.pddl','p08.pddl'),
	test_dir_files_sas(Dir,'p09-domain.pddl','p09.pddl'),
	test_dir_files_sas(Dir,'p10-domain.pddl','p10.pddl'),
	test_dir_files_sas(Dir,'p11-domain.pddl','p11.pddl'),
	test_dir_files_sas(Dir,'p12-domain.pddl','p12.pddl'),
	test_dir_files_sas(Dir,'p13-domain.pddl','p13.pddl'),
	test_dir_files_sas(Dir,'p14-domain.pddl','p14.pddl'),
	test_dir_files_sas(Dir,'p15-domain.pddl','p15.pddl'),
	test_dir_files_sas(Dir,'p16-domain.pddl','p16.pddl'),
	test_dir_files_sas(Dir,'p17-domain.pddl','p17.pddl'),
	test_dir_files_sas(Dir,'p18-domain.pddl','p18.pddl'),
	test_dir_files_sas(Dir,'p19-domain.pddl','p19.pddl'),
	test_dir_files_sas(Dir,'p20-domain.pddl','p20.pddl'),
	test_dir_files_sas(Dir,'p21-domain.pddl','p21.pddl'),
	test_dir_files_sas(Dir,'p22-domain.pddl','p22.pddl'),
	test_dir_files_sas(Dir,'p23-domain.pddl','p23.pddl'),
	test_dir_files_sas(Dir,'p24-domain.pddl','p24.pddl'),
	test_dir_files_sas(Dir,'p25-domain.pddl','p25.pddl'),
	test_dir_files_sas(Dir,'p26-domain.pddl','p26.pddl'),
	test_dir_files_sas(Dir,'p27-domain.pddl','p27.pddl'),
	test_dir_files_sas(Dir,'p28-domain.pddl','p28.pddl'),
	test_dir_files_sas(Dir,'p29-domain.pddl','p29.pddl'),
	test_dir_files_sas(Dir,'p30-domain.pddl','p30.pddl').

twhy
  :- show_call(record_time(forall(between(1,1000000,_),forall(get_action_bb(_),true)),_Time1)),
   show_call(record_time(forall(between(1,1000000,_),forall(actn(_,_),true)),_Time2)).

slow_on('blocks-07-0.pddl').
slow_on('blocks-08-0.pddl').
slow_on('blocks-09-0.pddl').
slow_on('hanoi7.pddl').
slow_on('hanoi8.pddl').

test_blocks:- time(notrace(test_blocks0)).

test_blocks0:- planner_solve_files(pddl('orig_pddl_parser/test/blocks/domain-blocks.pddl'),
   pddl('orig_pddl_parser/test/blocks/blocks-03-0.pddl')), fail.
test_blocks0:- fail, must_filematch_list(pddl('orig_pddl_parser/test/blocks/domain*.pddl'),RList),reverse(RList,List),
        forall(member(E,List),once(test_domain(E))),fail.
test_blocks0:- must_filematch_list(pddl('orig_pddl_parser/test/?*?/domain*.pddl'),RList),reverse(RList,List),
        forall(member(E,List),once(test_domain(E))),fail.
test_blocks0:- !.

:- dynamic(pddl_test_unit/1).
:- multifile(pddl_test_unit/1).
:- discontiguous(pddl_test_unit/1).
pddl_test_unit(blocks) :- test_blocks.

:- fixup_exports.

pddl_test_unit(test_sas):-
      test_dir_sas('ipc2008-no-cybersec/seq-sat/elevators-strips/'),!, % NO FIRST ANSWER
      !.

pddl_test_unit(test_sas_sanity):-
      test_dir_sas('ipc2008-no-cybersec/seq-opt/openstacks-strips/'), %PASSES BUT RUNS SLOW
       test_dir_sas('ipc2008-no-cybersec/seq-opt/transport-strips/'), %PASSES BUT RUNS
      test_dir_sas('ipc2008-no-cybersec/netben-opt/elevators-strips/'), % FAIL ALL
      !.

pddl_test_unit(test_rest):-
	test_dir_sas('ipc2008-no-cybersec/seq-opt/parcprinter-strips/'),
	test_dir_sas('ipc2008-no-cybersec/seq-opt/pegsol-strips/'),
	test_dir_sas('ipc2008-no-cybersec/seq-opt/scanalyzer-strips/'),
	test_dir_sas('ipc2008-no-cybersec/seq-opt/sokoban-strips/'),  % NO FIRST ANSWER

	test_dir_sas('ipc2008-no-cybersec/seq-opt/woodworking-strips/'),

        expand_file_name('ipc2008-no-cybersec/?*?/*/',O),
        forall(member(E,O),test_dir_sas(E)).

pddl_test_unit(frolog) :- test_dir_files_sas('frolog','p02-domain.pddl','p02.pddl'),
    test_dir_files_sas('frolog','tPddlAgent01-domain.pddl','tPddlAgent01.pddl'),
    !. % test_dir_files_sas('frolog','tPddlAgent02-domain.pddl','tPddlAgent02.pddl').

pddl_test_unit(mystery) :- planner_solve_files(pddl('benchmarks/mystery/domain.pddl'),pddl('benchmarks/mystery/prob01.pddl')).
pddl_test_unit(driverlog) :- test_domain(pddl('benchmarks/driverlog/domain.pddl'),4).
pddl_test_unit(woac) :- planner_solve_files(pddl('hsp2_1_0_pddl/parcprinter-strips/p01-domain-woac.pddl'),
               pddl('hsp2_1_0_pddl/parcprinter-strips/p01-woac.pddl')).

pddl_test_unit(chameleonWorld) :- test_domain(pddl('../domains_ocl/chameleonWorld/domain*')).

/*
:- if(current_predicate(pce_show_profile/0)).
:- pce_show_profile.
:- endif.
*/

% :- twhy.

% BAD
pddl_test_unit(elearning) :- test_domain(pddl('elearning/domain.pddl')).

pddl_test_unit(sat11) :- planner_solve_files(pddl('benchmarks/nomystery-sat11-strips/domain.pddl'),pddl('benchmarks/nomystery-sat11-strips/p01.pddl')).
pddl_test_unit(sat11_2) :- test_domain(pddl('benchmarks/nomystery-sat11-strips/domain.pddl')).
pddl_test_unit(toasterWorldv2) :- test_domain(pddl('../domains_ocl/toasterWorldv2/domain*')).
pddl_test_unit(rover) :- forall(must_filematch(pddl('rover/?*?/?*domain*.*'),E),once(test_domain(E))).
pddl_test_unit(hsp_pddl) :- forall(must_filematch(pddl('hsp-planners-master/?*?/pddl/?*?/?*domain*.*'),E),once(test_domain(E))).
pddl_test_unit(hsp_examples) :- forall(must_filematch(pddl('hsp-planners-master/?*?/examples/?*?/?*domain*.*'),E),once(test_domain(E))).
pddl_test_unit(primaryobjects_strips) :- forall(must_filematch(pddl('primaryobjects_strips/?*?/?*domain*.*'),E),once(test_domain(E))).
pddl_test_unit(monkey) :- planner_solve_files(pddl('hakank-pddl/monkey-domain.pddl'),pddl('hakank-pddl/monkey-prob01.pddl')).

:- fixup_exports.

:-thread_local(t_l:hyhtn_solve/1).
% t_l:other_planner(hyhtn_solve).

:- flag(time_used,_,0).
:- flag(time_used_other,_,0).

:- if(gethostname(c3po);gethostname(ubuntu);gethostname(titan)).
% :- debug,(must(test_blocks)).
% :- test_all(5). % should be 7
% :- test_all(7).
:- endif.
%:- show_call(flag(time_used_other,W,W)).
%:- show_call(flag(time_used,W,W)).

% :- xlisting(logicmoo_planner).
% :- xlisting(test).

:- fixup_exports.


text:
<?php
require_once "loxberry_io.php";
require_once "phpMQTT/phpMQTT.php";

$creds = mqtt_connectiondetails();

var_dump($creds);

?>


text: angular.module('config', []);


text:
/**
 * Created by cselvaraj on 4/29/14.
 */
'use strict';
// CONTROLLER
angular.module('searchblox.controller', []).controller('searchbloxController', [
    '$rootScope',
    '$scope',
    '$http',
    '$location',
    'searchbloxService',
    'searchbloxFactory',
    'facetFactory',
    '$q',
    '$timeout',
    '$modal',
    '$parse',
    '$filter',
    'uiGridExporterConstants',
    '$sce', function ($rootScope, $scope, $http, $location, searchbloxService, searchbloxFactory, facetFactory, $q, $timeout, $modal, $parse, $filter, uiGridExporterConstants, $sce) {

    var searchUrl = '/searchblox/servlet/SearchServlet';
    var autoSuggestUrl = '/searchblox/servlet/AutoSuggest';
    var reportServletUrl = '/searchblox/servlet/ReportServlet';

    // Hard coded these values. This needs to be dynamic
    //var facet = 'on';
    //var xsl = "json";
    $scope.facetFields = "";
    // var dateFacet = "";

    $scope.rangeFilter = "";
    $scope.filterFields = "";
    $scope.selectedItems = [];
    //$scope.sortDir = "desc";
    // $scope.sortVal = "";
    $scope.from = 0;
    $scope.page = 1;
    $scope.prevPage = 1;
    //$scope.pageSize = 10;
    $scope.noOfSuggests = 5;
    //$scope.showAutoSuggest = true;

    $scope.paginationHtml = "";
    $scope.tagHtml = "";
    $scope.topHtml = "";
    $scope.startedSearch = false;
    $scope.initResolved = false;
    $scope.initAds = 1;
    $scope.maxAdsLimit = 2;
    $scope.dataMap = {};
    $scope.inputClass = {};
    $scope.inputClass.name = "ngCustomInput col-sm-8 col-md-8 col-md-offset-2";
    $scope.gridColumns = [];

    // load autosuggest items
    $scope.loadItems = function (term) {
        var autoSuggestData = $q.defer();
        searchbloxFactory.getResponseData(autoSuggestUrl + '?limit=' + $scope.noOfSuggests + '&q=' + term).then(function (suggestionResults) {
            var suggtns = searchbloxService.parseAutoSuggestion(suggestionResults.data);
            $scope.timer = $timeout(function () {
                $rootScope.$apply(autoSuggestData.resolve(suggtns));
            }, 10);
        });
        return autoSuggestData.promise;
    };

    // Reads json data file and initializes the scope variables
    $scope.init = function () {
        facetFactory.get().$promise.then(function (data) {
            if (data !== null) {
                $scope.startedSearch = true;
                if (typeof($scope.dataMap['facetFields']) == "undefined" || $scope.dataMap['facetFields'] == null || $scope.dataMap['facetFields'] == "") {
                    $scope.dataMap['facetFields'] = searchbloxService.getFacetFields(data.facets);
                    $scope.facetMap = searchbloxService.facetFieldsMap;
                }

                if (typeof($scope.dataMap['sortVal']) == "undefined" || $scope.dataMap['sortVal'] == null || $scope.dataMap['sortVal'].trim() == "" || !searchbloxService.sortBtnExists($scope.dataMap['sortVal'].trim())) {
                    $scope.sortBtns = searchbloxService.getSortBtns(data.sortBtns);
                }

                if (typeof($scope.dataMap['collectionString']) == "undefined" || $scope.dataMap['collectionString'] == null || $scope.dataMap['collectionString'] === "") {
                    $scope.dataMap['collectionString'] = searchbloxService.getCollectionValues(data.collection);
                }

                if (typeof($scope.dataMap['collectionForAds']) == "undefined" || $scope.dataMap['collectionForAds'] == null || $scope.dataMap['collectionForAds'] === "") {
                    $scope.dataMap['collectionForAds'] = data.collectionForAds;
                }

                if (typeof($scope.dataMap['matchAny']) == "undefined" || $scope.dataMap['matchAny'] == null) {
                    $scope.dataMap['matchAny'] = data.matchAny;
                }

                if (typeof($scope.dataMap['sortDir']) == "undefined" || $scope.dataMap['sortDir'] == null) {
                    $scope.dataMap['sortDir'] = data.sortDir;
                }

                if (typeof($scope.dataMap['pageSize']) == "undefined" || $scope.dataMap['pageSize'] == null) {
                    $scope.dataMap['pageSize'] = data.pageSize;
                }

                if (typeof($scope.dataMap['filter']) == "undefined" || $scope.dataMap['filter'] == null) {
                    $scope.dataMap['filter'] = data.filter;
                }

                if (typeof($scope.dataMap['startDate']) == "undefined" || $scope.dataMap['startDate'] == null) {
                    if ((data.startDate !== undefined) && data.startDate !== null) {
                        $scope.dataMap['startDate'] = moment(data.startDate, 'MM-DD-YYYY').format("YYYYMMDDHHmmss");
                    }
                }

                if (typeof($scope.dataMap['endDate']) == "undefined" || $scope.dataMap['endDate'] == null) {
                    if ((data.endDate !== undefined) && data.endDate !== null) {
                        $scope.dataMap['endDate'] = moment(data.endDate, 'MM-DD-YYYY').format("YYYYMMDDHHmmss");
                    }
                }

                if (typeof($scope.showAutoSuggest) == "undefined" || $scope.showAutoSuggest == null) {
                    $scope.showAutoSuggest = data.showAutoSuggest;
                }

                if (typeof($scope.gridColumns) == "undefined" || $scope.gridColumns == null || $scope.gridColumns.length < 1) {
                    $scope.gridColumns = data.gridColumns;
                }

                $scope.dataMap['facet'] = 'on';
                $scope.dataMap['xsl'] = "json";

                $scope.gridInit();

                $scope.initResolved = true;
            }
        });
    };

    $scope.startSearch = function () {
        $scope.from = 0;
        $scope.page = 1;
        $scope.prevPage = 1;
        $scope.doSearch();
    };

    // Search function
    $scope.doSearch = function () {
        var urlParams = searchbloxService.getUrlParams(searchUrl, $scope.query,
            $scope.rangeFilter, $scope.filterFields, $scope.page, $scope.dataMap);
        searchbloxFactory.getResponseData(urlParams).then(function (searchResults) {
            $scope.parsedSearchResults = searchbloxService.parseResults(searchResults.data, $scope.facetMap, $scope.dataMap);
            $scope.bindGridSearchResults($scope.parsedSearchResults);
            $scope.parsedLinks = searchbloxService.parseLinks(searchResults.data, $scope.facetMap);
            $scope.startedSearch = true;
            $scope.inputClass.name = "ngCustomInput col-sm-6 col-md-6 col-md-offset-2";
        });
    };

    // Sort function
    $scope.doSort = function (sortVal) {
        $scope.dataMap['sortVal'] = sortVal;
        $scope.doSearch();
    };

    // Sort function
    $scope.doDirector = function (direction) {
        $scope.dataMap['sortDir'] = direction;
        $scope.doSearch();
    };

    // get tagcloud
    $scope.getTagCloud = function () {
        var taghtml = "
Most Used Tags

";
        if ($scope.parsedSearchResults.facets != undefined && $scope.parsedSearchResults.facets != null && $scope.parsedSearchResults.facets[2].keywords != undefined && $scope.parsedSearchResults.facets[2].keywords != null)
            for (var a in $scope.parsedSearchResults.facets[2].keywords[1]) {
                var value = $scope.parsedSearchResults.facets[2].keywords[1][a];
                taghtml += "" + value['@name'] + " ";
            }
        taghtml += "
";
        $scope.tagHtml = $sce.trustAsHtml(taghtml);
        var list = document.getElementById("facettagcloud");
        if (list != undefined && list.childNodes.length > 0) {
            shuffleNodes(list);
            $.fn.tagcloud.defaults = {
                size: {start: 14, end: 18, unit: 'pt'},
                color: {start: '#cde', end: '#f52'}
            };
            $(function () {
                $('#facettagcloud a').tagcloud();
            });
        }
    };

    // get top clicked function
    $scope.getTopClicked = function () {
        searchbloxFactory.getResponseData(reportServletUrl + '?&gettopclicks=yes&nodocs=5&query=' + $scope.query).then(function (topClickedResults) {
            topClickedResults = topClickedResults.data;
            var temphtml = "
Most Viewed

";
            if (topClickedResults != "nodocs" && topClickedResults != "queryerror" && topClickedResults != "")
                for (var x in topClickedResults)
                    for (var y in topClickedResults[x])
                        temphtml += topClickedResults[x][y];
            if (topClickedResults != "nodocs" && topClickedResults != "queryerror" && topClickedResults != "")
                $scope.topHtml = $sce.trustAsHtml(temphtml);
        });
    };

    // adjust how many results are shown
    $scope.howmany = function () {
        var newhowmany = prompt('Currently displaying ' + $scope.pageSize + ' results per page. How many would you like instead?');
        if (newhowmany) {
            $scope.pageSize = parseInt(newhowmany);
            $scope.from = 0;
            $scope.dosearch();
        }
    };

    // adjust how many suggestions are shown
    var howmanynofsuggest = function () {
        var newhowmany = prompt('Currently displaying ' + $scope.noOfSuggests + ' suggestions per page. How many would you like instead?');
        if (newhowmany) {
            $scope.noOfSuggests = parseInt(newhowmany);
            $scope.from = 0;
            $scope.dosearch();
        }
    };

    // Function for search by filter.
    $scope.doSearchByFilter = function (filter, facetName, rSlider) {
        $scope.page = 1;

        var filters = "",
            filterName = filter['@name'],
            filterRangeFrom = filter['@from'],
            filterRangeTo = filter['@to'],
            filterRangeCalendar = filter['@calendar'],
            filterRangeValue = filter['@value'],
            slider = filter['slider'] = (rSlider || false),
            searchReplacment = false,
            filter_index = -1,
            hasFilter = false;

        for (var i = 0, l = $scope.selectedItems.length; i < l; i++) {
            var obj = $scope.selectedItems[i];

            if (obj['filterRangeFrom'] !== undefined && obj['filterRangeTo'] !== undefined) {
                if (obj['facetName'] === facetName) {
                    if ((facetName === 'size' && obj['slider'] === slider) || facetName === 'lastmodified') {
                        searchReplacment = true;
                        filter_index = i;
                    }
                }

                if ((obj['filterName'] === filterName) && (obj['facetName'] === facetName)
                    && obj['filterRangeFrom'] === filterRangeFrom
                    && obj['filterRangeTo'] === filterRangeTo
                ) {
                    hasFilter = true;
                } else {
                    filters = filters + '&f.' + obj['facetName'] + '.filter=[' + obj['filterRangeFrom'] + 'TO' + obj['filterRangeTo'] + ']';
                }
            } else if (obj['filterRangeCalendar'] !== undefined && obj['filterRangeValue'] !== undefined) {
                if ((obj['filterName'] === filterName) && (obj['facetName'] === facetName)
                    && obj['filterRangeCalendar'] === filterRangeCalendar
                    && obj['filterRangeValue'] === filterRangeValue
                ) {
                    hasFilter = true;
                } else {
                    filters = filters + '&f.' + obj['facetName'] + '.filter=[' + moment().subtract(obj['filterRangeCalendar'], obj['filterRangeValue']).format("YYYY-MM-DDTHH:mm:ss") + 'TO*]';
                }
            } else {
                if ((obj['filterName'] === filterName) && (obj['facetName'] === facetName)) {
                    hasFilter = true;
                } else {
                    filters = filters + "&f." + obj['facetName'] + ".filter=" + obj['filterName'];
                }
            }
        }

        var newFilter = {};
        newFilter["id"] = $scope.selectedItems.size;
        newFilter['filterName'] = filterName;
        newFilter['facetName'] = facetName;
        newFilter['filterRangeFrom'] = filterRangeFrom;
        newFilter['filterRangeTo'] = filterRangeTo;
        newFilter['filterRangeCalendar'] = filterRangeCalendar;
        newFilter['filterRangeValue'] = filterRangeValue;
        newFilter['slider'] = slider;
        newFilter['pageNo'] = $scope.prevPage;
        $scope.prevPage = $scope.page;

        $scope.prepareFilters = function() {
            if (!hasFilter || searchReplacment === true) {
                if (filterRangeFrom !== undefined && filterRangeTo !== undefined) {
                    var rangeFilter = '';

                    if (searchReplacment) {
                        rangeFilter = '&f.' + facetName + '.filter=[' + filterRangeFrom + 'TO' + filterRangeTo + ']';
                    } else {
                        rangeFilter = filters + '&f.' + facetName + '.filter=[' + filterRangeFrom + 'TO' + filterRangeTo + ']';
                    }

                    $scope.filterFields = rangeFilter;
                } else if (filterRangeCalendar !== undefined && filterRangeValue !== undefined) {
                    $scope.filterFields = filters + '&f.' + facetName + '.filter=[' + moment().subtract(filterRangeCalendar, filterRangeValue).format("YYYY-MM-DDTHH:mm:ss") + 'TO*]';
                } else {
                    $scope.filterFields = filters + "&f." + facetName + ".filter=" + filterName;
                }

                $scope.showInput = true;
                if (searchReplacment === true && filter_index > -1) {
                    $scope.selectedItems[filter_index] = newFilter;
                } else {
                    $scope.selectedItems.push(newFilter);
                }
            }
        };

        $scope.prepareFilters();
        $scope.doSearch();
    };

    // Function for removing filter
    $scope.removeItem = function (index) {
        var selected_object = $scope.selectedItems[index];
        $scope.page = selected_object['pageNo'];
        $scope.selectedItems.splice(index, 1);
        var filters = "";
        for (var i = 0, l = $scope.selectedItems.length; i < l; i++) {
            var obj = $scope.selectedItems[i];
            if (obj['filterRangeFrom'] !== undefined && obj['filterRangeTo'] !== undefined) {
                filters = filters + '&f.' + obj['facetName'] + '.filter=[' + obj['filterRangeFrom'] + 'TO' + obj['filterRangeTo'] + ']';
            }
            else if (obj['filterRangeCalendar'] !== undefined && obj['filterRangeValue'] !== undefined) {
                filters = filters + '&f.' + obj['facetName'] + '.filter=[' + moment().subtract(obj['filterRangeCalendar'], obj['filterRangeValue']).format("YYYY-MM-DDTHH:mm:ss") + 'TO*]';
            }
            else {
                filters = filters + "&f." + obj['facetName'] + ".filter=" + obj['filterName'];
            }
        }
        $scope.filterFields = filters;
        $scope.doSearch();
    };

    // Function for fetch page results.
    $scope.fetchPage = function (pageNo) {
        $scope.page = pageNo;
        $scope.prevPage = pageNo;
        $scope.doSearch();
    };

    // check if there is atleast one filter in the facet
    $scope.hasFacets = function () {

        if ($scope.parsedSearchResults !== undefined && $scope.parsedSearchResults !== null
            && $scope.parsedSearchResults.facets !== null) {

            for (var i in $scope.parsedSearchResults.facets) {
                //for (var i = 0, l = $scope.parsedSearchResults.facets.length; i < l; i++) {
                var facet = $scope.parsedSearchResults.facets[i];
                if (facet[facet['name']] !== undefined && facet[facet['name']] !== null
                    && facet[facet['name']][1] !== undefined && facet[facet['name']][1] !== null
                    && facet[facet['name']][1][0] !== undefined && facet[facet['name']][1][0] !== null) {
                    return true;
                }
            }
        }
        return false;
    };

    // check if there is atleast one filter in the facet
    $scope.hasInitAds = function () {
        if ($scope.parsedSearchResults !== undefined && $scope.parsedSearchResults !== null
            && $scope.parsedSearchResults.showAds) {
            if ($scope.parsedSearchResults.ads !== null && typeof($scope.parsedSearchResults.ads) !== "undefined" &&
                $scope.parsedSearchResults.ads.length >= $scope.initAds) {
                return true;
            }
        }
        return false;
    };

    $scope.hasMoreAds = function () {
        if ($scope.parsedSearchResults !== undefined && $scope.parsedSearchResults !== null
            && $scope.parsedSearchResults.showAds) {
            if ($scope.parsedSearchResults.ads !== null && typeof($scope.parsedSearchResults.ads) !== "undefined" &&
                $scope.parsedSearchResults.ads.length > $scope.maxAdsLimit) {
                return true;
            }
        }
        return false;
    };

    /**
     * Grid options
     */
    $scope.gridInit = function() {
        var footerTemplate = '
' +
            '
' +
            '
Previous
' +
            '
Next
' +
            '
Page: {{ getExternalScopes().gridApi.pagination.getPage() }}
' +
            '
Total pages: {{ getExternalScopes().gridApi.pagination.getTotalPages() }}
' +
            '

';

        var modalTemplate = function (c) {

            var fields = $scope.gridColumns.map(function(v) { return v['field']; });
            var displayAs = $scope.gridColumns.map(function(v) { return v['name']; });

            var x = '

';

            fields.forEach(function(v, i) {
                var _c = c[v];

                if (_c == null && v.indexOf('.') > -1) {
                    _c = Object.resolve(v, c);
                }

                x += '
';
                x += '' + displayAs[i] + '	' + (_c?_c:'') + '	';
                x += '
';
            });
            x += '

';
            return x;
        };

        $scope.gridOptions = {
            data: 'gridResultsData',
            rowHeight: 60,
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            },
            showFooter: false,
            footerTemplate: footerTemplate
        };

        $scope.gridOptions.columnDefs = $scope.gridColumns;

        $scope.dUtils = {
            formatData: function (obj) {
                if (!angular.isArray(obj))
                    return [obj];
                else
                    return obj;
            },
            modal: function (field) {
                $modal({
                    title: field.title,
                    content: modalTemplate(field),
                    html: true
                })
            },
            gridApi: $scope.gridApi
        };

        $scope.dumpCSV = function() {
            var exporterElem = $('.custom-csv-link-location.hidden');
            $scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, exporterElem);
            return $timeout(function() {
                $scope.gridResultsDataCSV = exporterElem.find('a').attr('href').replace('data:text/csv;charset=UTF-8,', '');
            }, 0);
        };

        $scope.bindGridSearchResults = function (v) {
            $scope.gridResultsData = [];

            if (v == null || !angular.isObject(v.records)) {
                return false
            }

            $scope.gridResultsData = v.records;
        };

        $scope.openVisualBox = function () {
            if ($scope.gridResultsData.length) {
                $scope.gridResultsDataCSV = '';
                $scope.dumpCSV().then(function() {
                    var data = decodeURIComponent($scope.gridResultsDataCSV);
                    data = $filter('htmlToPlaintext')(data);
                    $modal({
                        title: 'New Visualization',
                        template: 'views/raw-chart.html',
                        content: data
                    });
                });
            } else {
                alert('No data inside grid');
            }
        };
    }
}]);