text:
namespace policy {

// Toggling the ForceLegacyDefaultReferrerPolicy enterprise policy should flip
// the corresponding content::Referrer global.
class ForceLegacyDefaultReferrerPolicy : public InProcessBrowserTest {
 public:
  void SetUp() override {
    EXPECT_CALL(policy_provider_, IsInitializationComplete(testing::_))
        .WillRepeatedly(testing::Return(true));
    BrowserPolicyConnector::SetPolicyProviderForTesting(&policy_provider_);
    InProcessBrowserTest::SetUp();
  }

 protected:
  MockConfigurationPolicyProvider policy_provider_;
};

IN_PROC_BROWSER_TEST_F(ForceLegacyDefaultReferrerPolicy, UpdatesDynamically) {
  // When the policy's unset, we shouldn't be forcing the legacy default
  // referrer policy.
  EXPECT_FALSE(content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());

  policy::PolicyMap values;
  values.Set(key::kForceLegacyDefaultReferrerPolicy, POLICY_LEVEL_RECOMMENDED,
             POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
             std::make_unique<base::Value>(true), nullptr);
  policy_provider_.UpdateChromePolicy(values);
  base::RunLoop().RunUntilIdle();
  // When the policy's true, we should have flipped the global to true.
  EXPECT_TRUE(content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());

  values.Set(key::kForceLegacyDefaultReferrerPolicy, POLICY_LEVEL_RECOMMENDED,
             POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
             std::make_unique<base::Value>(false), nullptr);
  policy_provider_.UpdateChromePolicy(values);
  base::RunLoop().RunUntilIdle();
  // When the policy's false, we should have flipped the global back to false.
  EXPECT_FALSE(content::Referrer::ShouldForceLegacyDefaultReferrerPolicy());
}

}  // namespace policy


text:
{{}}

{{define "title"}}Employee Details{{end}}
{{define "content"}}
<form class="form-horizontal" action="/employees/save" method="POST">
	<fieldset>
		<legend>Employee Details</legend>
		<input type="hidden" name="ID" value="{{.E.ID}}">

			CPS Email

				<input type="text" id="CPSEmail" name="CPSEmail"
				value="{{.E.CPSEmail}}" {{if not .Admin}}disabled="disabled"{{end}} class="form-control">
				Set by the administrator.

			Roles

					<input type="checkbox" id="AdminRole" name="AdminRole"
					{{if .E.Roles.Admin}}checked="checked"{{end}}
					{{if not .Admin}}disabled="disabled"{{end}}>
					Admin

					<input type="checkbox" id="HRRole" name="HRRole"
					{{if .E.Roles.HR}}checked="checked"{{end}}
					{{if not .Admin}}disabled="disabled"{{end}}>
					HR

					<input type="checkbox" id="TeacherRole" name="TeacherRole"
					{{if .E.Roles.Teacher}}checked="checked"{{end}}
					{{if not .Admin}}disabled="disabled"{{end}}>
					Teacher

				Set by the administrator.

			Enabled

					<input type="checkbox" id="Enabled" name="Enabled"
						{{if .E.Enabled}}checked="checked"{{end}}>
					Enabled

			Name*

				<input type="text" id="Name" name="Name" value="{{.E.Name}}" required="required" class="form-control">

			Arabic Name

				<input type="text" id="ArabicName" name="ArabicName" value="{{.E.ArabicName}}" class="form-control">

			Gender

				<select id="Gender" name="Gender" class="form-control">
					<option></option>
					<option value="M"
					{{if equal .E.Gender "M"}}selected="selected"{{end}}
					>Male</option>
					<option value="F"
					{{if equal .E.Gender "F"}}selected="selected"{{end}}
					>Female</option>
				</select>

			Type*

				<select id="Type" name="Type" required="required" class="form-control">
					{{$type := .E.Type}}
					{{range .T}}
					<option {{if equal . $type}}selected="selected"{{end}}
					value="{{.}}">{{.}}</option>
					{{end}}
				</select>

			Job Description

				<input type="text" id="JobDescription" name="JobDescription" value="{{.E.JobDescription}}" class="form-control">

			Date of Hiring

				<input type="date" id="dateOfHiring" name="DateOfHiring" value="{{.E.DateOfHiring | formatDate}}"
					class="form-control">

			Qualifications

				<textarea id="Qualifications" name="Qualifications" rows="5" class="form-control">{{.E.Qualifications}}</textarea>

			Nationality

				<select id="Nationality" name="Nationality" class="form-control">
					<option></option>
					{{$country := .E.Nationality}}
					{{range .C}}
					<option {{if equal . $country}}selected="selected"{{end}}
					value="{{.}}">{{.}}</option>
					{{end}}
				</select>

			CPR Number

				<input type="number" id="CPR" name="CPR"
					pattern="^[0-9]{9}$" value="{{.E.CPR}}" class="form-control">

			Passport

				<input type="text" id="Passport" name="Passport" value="{{.E.Passport}}" class="form-control">

			Date of Birth*

				<input type="date" id="dateOfBirth" name="DateOfBirth" value="{{.E.DateOfBirth | formatDate}}"
					required="required" class="form-control">

			Mobile Phone

				<input type="text" id="MobilePhone" name="MobilePhone" value="{{.E.MobilePhone}}" class="form-control">

			Address

				<textarea id="Address" name="Address" rows="5" class="form-control">{{.E.Address}}</textarea>

			Emergency Phone

				<input type="text" id="EmergencyPhone" name="EmergencyPhone" value="{{.E.EmergencyPhone}}" class="form-control">

			Health Information

				<textarea id="HealthInfo" name="HealthInfo" rows="5" class="form-control">{{.E.HealthInfo}}</textarea>

			Comments

				<textarea id="Comments" name="Comments" rows="5" class="form-control">{{.E.Comments}}</textarea>

			<input type="submit" name="action" class="btn btn-default btn-primary" value="Save">
			<input type="button" class="btn btn-default cps-go-back" value="Cancel">
			<input type="submit" name="action" class="btn btn-danger are-you-sure" value="Delete">

	</fieldset>
</form>
{{end}}

redpajama_set_name: RedPajamaGithub


text:
package com.pulkit4tech.privy;

import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.gson.GsonBuilder;
import com.pulkit4tech.privy.data.PostPrivyDeleteRequest;
import com.pulkit4tech.privy.data.json.LocationData;
import com.pulkit4tech.privy.data.json.MarkerData;
import com.pulkit4tech.privy.data.json.PostPrivyDeleteResponse;

import org.json.JSONObject;

import static android.content.Intent.ACTION_VIEW;
import static com.pulkit4tech.privy.constants.Constants.DEBUG;

public class PrivyDetailsActivity extends AppCompatActivity {

    private MarkerData data;
    private String GOOGLE_MAP_API_KEY = "key";
    private String MAPS = "maps";
    private String API = "api";
    private String PLACE = "place";
    private String DELETE = "delete";
    private String JSON = "json";
    private String OK = "OK";
    private InterstitialAd interstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_privy_details);
        setAddMob();
        setToolBar();
        setFab();

        data = retrieveData();
        if (data != null) {
            Log.d(DEBUG, data.toString());
            setData();
        }

        setDelete();
    }

    private void setAddMob() {
        if(interstitialAd==null) {
            interstitialAd = new InterstitialAd(this);
            interstitialAd.setAdUnitId(getString(R.string.ad_id_interstitial));
            Log.d(DEBUG, "initialize InterstitialAd: " + interstitialAd);
        }
        interstitialAd.loadAd(new AdRequest.Builder().build());
        interstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                Log.d(DEBUG, "InterstitialAd loaded");
                displayInterstitial();
            }

            @Override
            public void onAdClosed() {
                super.onAdClosed();
            }

            @Override
            public void onAdFailedToLoad(int i) {
                super.onAdFailedToLoad(i);
            }

            @Override
            public void onAdLeftApplication() {
                super.onAdLeftApplication();
            }

            @Override
            public void onAdOpened() {
                super.onAdOpened();
            }
        });
    }

    private void displayInterstitial() {
        if (interstitialAd.isLoaded()) {
            interstitialAd.show();
        }
    }

    private void setDelete() {
        Button delete = (Button) findViewById(R.id.delete_privy);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deletePrivy();
            }
        });
    }

    private void deletePrivy() {
        JsonObjectRequest request = new JsonObjectRequest(
                postDeleteUrl(),
                postJsonBody(),
                postDelResListner,
                errorListener
        );

        Volley.newRequestQueue(this).add(request);
    }

    private JSONObject postJsonBody() {
        JSONObject jsonObject = null;
        try {
            PostPrivyDeleteRequest delete_data = new PostPrivyDeleteRequest();
            delete_data.setPlaceid(data.getPlaceid());
            jsonObject = new JSONObject(new GsonBuilder().create().toJson(delete_data));
        } catch (Exception e) {
            Log.d(DEBUG, e.toString());
        }
        return jsonObject;
    }

    private String postDeleteUrl() {
        Uri.Builder builder = new Uri.Builder();
        builder.scheme("https")
                .authority(getString(R.string.request_api))
                .appendPath(MAPS)
                .appendPath(API)
                .appendPath(PLACE)
                .appendPath(DELETE)
                .appendPath(JSON)
                .appendQueryParameter(GOOGLE_MAP_API_KEY, getString(R.string.google_maps_key));
        String url = builder.build().toString();
        Log.d(DEBUG, url);
        return url;
    }

    private Response.Listener postDelResListner = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            PostPrivyDeleteResponse res = new GsonBuilder().create().fromJson(response.toString(), PostPrivyDeleteResponse.class);
            if (res.getStatus().equals(OK)) {
                Toast.makeText(getApplicationContext(), getString(R.string.delete_request_success), Toast.LENGTH_LONG).show();
                finish();
            } else {
                Log.d(DEBUG, res.toString());
                snackMsg(getString(R.string.delete_request_failed) + "Reason : " + res.getStatus());
            }
        }
    };

    private Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            snackMsg(getString(R.string.network_error));
            Log.d(DEBUG, error.toString());
        }
    };

    private void setFab() {
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDirection();
            }
        });
    }

    private void getDirection() {
        try {
            Intent intent = new Intent(ACTION_VIEW,
                    Uri.parse(String.format("http://maps.google.com/maps?daddr=%f,%f", data.getGeometry().getLocation().getLat(), data.getGeometry().getLocation().getLng())));
            startActivity(intent);
        } catch (Exception e) {
            Log.d(DEBUG, e.toString());
            snackMsg(getString(R.string.error_processing_request));
        }
    }

    private void setToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //noinspection ConstantConditions,ConstantConditions
        getSupportActionBar().setTitle(R.string.toolbar_title_privy_details);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    private void setData() {
        TextView name = (TextView) findViewById(R.id.privy_details_name);
        TextView geometry = (TextView) findViewById(R.id.privy_details_geo);
        TextView open_now = (TextView) findViewById(R.id.privy_details_opening);
        TextView vicinity = (TextView) findViewById(R.id.privy_details_vicinity);
        TextView ratings = (TextView) findViewById(R.id.privy_details_ratings);

        name.setText(checkNameValue(data.getName()));
        geometry.setText(checkGeoValue(data.getGeometry()));
        open_now.setText(checkOpening(data.getOpeninghours()));
        vicinity.setText(checkVicinityValue(data.getVicinity()));
        ratings.setText(checkRatingValue(data.getRating()));
    }

    private String checkNameValue(String val) {
        if (val == null)
            return getString(R.string.n_a);
        return val;
    }

    private String checkVicinityValue(String vicinity) {
        if (vicinity == null)
            return getString(R.string.n_a);

        return vicinity;
    }

    private String checkRatingValue(float rating) {
        if (rating == 0)
            return getString(R.string.n_a);

        return String.format("%.2f", rating);
    }

    private String checkOpening(MarkerData.OpeningHours openingHours) {
        if (openingHours == null)
            return getString(R.string.n_a);

        return openingHours.isOpennow() ? "YES" : "NO";
    }

    private String checkGeoValue(LocationData geo) {
        if (geo == null)
            return getString(R.string.n_a);
        return "Lat : " + String.format("%.2f", geo.getLocation().getLat()) + " Lng : " + String.format("%.2f", geo.getLocation().getLng());
    }

    private MarkerData retrieveData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            return (MarkerData) getIntent().getSerializableExtra(getString(R.string.marker_data));
        }
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // close this activity and return to preview activity (if there is any)
        }

        return super.onOptionsItemSelected(item);
    }

    private void snackMsg(String msg) {
        Snackbar.make((CardView) findViewById(R.id.cardview), msg, Snackbar.LENGTH_LONG).show();
    }
}


text:
package org.basex.query.expr;

import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * Iterative filter expression without numeric predicates.
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Christian Gruen
 */
public final class IterFilter extends Filter {
  /**
   * Constructor.
   * @param info input info
   * @param root root expression
   * @param preds predicate expressions
   */
  IterFilter(final InputInfo info, final Expr root, final Expr... preds) {
    super(info, root, preds);
  }

  @Override
  public Iter iter(final QueryContext qc) {
    return new Iter() {
      Iter iter;

      @Override
      public Item next() throws QueryException {
        // first call - initialize iterator
        if(iter == null) iter = root.iter(qc);
        // filter sequence
        for(Item item; (item = qc.next(iter)) != null;) {
          if(match(item, qc)) return item;
        }
        return null;
      }
    };
  }

  @Override
  public Value value(final QueryContext qc) throws QueryException {
    final ValueBuilder vb = new ValueBuilder(qc);
    final Iter iter = root.iter(qc);
    for(Item item; (item = qc.next(iter)) != null;) {
      if(match(item, qc)) vb.add(item);
    }
    return vb.value(this);
  }

  @Override
  public IterFilter copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return copyType(new IterFilter(info, root.copy(cc, vm), Arr.copyAll(cc, vm, exprs)));
  }
}


text:
/**
 * This class defines the auth-token that all the services in the SearchClient instance passes along it's serverside lookups.
 */
export class AuthToken {
    /**
     * Getter will call token resolver to obtain the Json Web Token that is to be used to authenticate the rest-calls to the search-service.
     */
    get authenticationToken(): string {
        return this.tokenResolver instanceof Function ? this.tokenResolver() : "";
    }

    public tokenResolver: () => string;
}


text:
/*
 * js/styles/cocoa.js
 *
 * This script contains code needed for the Cocoa style.
 *
 * Subject to terms and conditions in LICENSE.md.
 *
 */

if (typeof window.Styles.Cocoa === 'undefined') {
    window.Styles.Cocoa = true;

    // Thumbs up and down styles.
    (function() {
        // Create dummy elements to get the computed styles for these elements.
        var td = document.createElement('td');
        td.dataset.col = 'rating';

        var el = document.createElement('div');
        el.className = 'song-row';
        el.appendChild(td);
        el.style.display = 'none';
        document.body.appendChild(el);

        // Get the background-position for thumbs up.
        td.dataset.rating = '5';
        var thumbsUpStyle = document.defaultView.getComputedStyle(td, null);
        var thumbsUpBackX = parseInt(thumbsUpStyle.backgroundPositionX);
        var thumbsUpBackY = parseInt(thumbsUpStyle.backgroundPositionY);

        // Get the background-position for thumbs down.
        td.dataset.rating = '1';
        var thumbsDownStyle = document.defaultView.getComputedStyle(td, null);
        var thumbsDownBackX = parseInt(thumbsDownStyle.backgroundPositionX);
        var thumbsDownBackY = parseInt(thumbsDownStyle.backgroundPositionY);

        // Remove the element.
        document.body.removeChild(el);

        // Apply a new stylesheet for the new thumbs up and down positions.
        thumbsUpBackY -= 9;
        thumbsDownBackY -= 7;

        var thumbsUpPosition = thumbsUpBackX + 'px ' + thumbsUpBackY + 'px';
        var thumbsDownPosition = thumbsDownBackX + 'px ' + thumbsDownBackY + 'px';

        window.Styles.applyStyle('thumbsUpDown',
            '.song-row [data-col="rating"][data-rating="5"]:not(.stars) { background-position: ' + thumbsUpPosition + ' !important; } ' +

            '.song-row [data-col="rating"][data-rating="1"]:not(.stars), ' +
            '.song-row [data-col="rating"][data-rating="2"]:not(.stars) { background-position: ' + thumbsDownPosition + ' !important; } '
        );
    })();
}


text:
from functools import wraps

"""
Helper decorators for handling context from skills.
"""

def adds_context(context, words=''):
    """Decorator adding context to the Adapt context manager.

    Args:
        context (str): context Keyword to insert
        words (str): optional string content of Keyword
    """
    def context_add_decorator(func):
        @wraps(func)
        def func_wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            args[0].set_context(context, words)
            return ret
        return func_wrapper
    return context_add_decorator

def removes_context(context):
    """Decorator removing context from the Adapt context manager.

    Args:
        context (str): Context keyword to remove
    """
    def context_removes_decorator(func):
        @wraps(func)
        def func_wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            args[0].remove_context(context)
            return ret
        return func_wrapper
    return context_removes_decorator


text:
<!DOCTYPE html>

  {% set bootstrap_version = '3.3.4' %}
  {% set modernizer_version = '2.8.3' %}
  {% set jquery_version = '2.1.4' %}
  {% set parsley_version = '2.0.7' %}
  {% set awesome_version = '4.3.0' %}
  {% set bootswatch_version = '3.3.4' %}
  {% set bootswatch_theme = 'darkly' %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
    <title>{% block title%}DXLR Expenses{% endblock %}</title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/{{ bootstrap_version }}/css/bootstrap.min.css" rel="stylesheet" />
    <link href="//netdna.bootstrapcdn.com/font-awesome/{{ awesome_version }}/css/font-awesome.min.css" rel="stylesheet" >
    <link href="//netdna.bootstrapcdn.com/bootswatch/{{ bootswatch_version }}/{{ bootswatch_theme }}/bootstrap.min.css" rel="stylesheet" >

    <link href="/static/css/main.css" rel="stylesheet" />
    <link rel="shortcut icon" href="/static/img/favicon.ico" />
    {% block style_block %}{# page-specific CSS #}{% endblock %}
    {# Modernizr must be here, above body tag. #}
    {% block head_script %}{# defer-incapable JS block #}{% endblock %}

    {% include 'includes/nav.html' %} {# pull in navbar #}

      {% include 'includes/flash_message.html' %} {# page-level feedback notices #}

        {% block content %}{# main content area #}{% endblock %}

        {% block footer %}{% endblock %}

    {% block tail_script %}{# defer-capable JS block #}{% endblock %}


text:
layout : blogpost1
---

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% include bloghead.html %}
    <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/style.css" />
    <link rel="stylesheet" href="{{ site.baseurl }}/assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">
 <link rel="stylesheet" href="{{ site.baseurl }}/assets/css/Navigation-Clean1.css">
 <link rel="stylesheet" href="{{ site.baseurl }}/assets/css/blogpost.css">

 <link rel="stylesheet" href="assets/css/Navigation-Clean1.css">
 <link rel="stylesheet" href="{{ site.baseurl }}/assets/css/blogpost.css">
    <title>Blogs</title>

Aman's Home
                    <button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1">Toggle navigation</button>

Blog

About

{{ page.title }}

              {{ content }}

			© Aman Bhargava 2017


text:
[![Gem Version](https://img.shields.io/gem/v/omnifiles.svg)](https://rubygems.org/gems/omnifiles)
[![Code Climate](https://codeclimate.com/github/theirix/omnifiles/badges/gpa.svg)](https://codeclimate.com/github/theirix/omnifiles)
[![Dependency Status](https://gemnasium.com/theirix/omnifiles.svg)](https://gemnasium.com/theirix/omnifiles)

File storage and shortener server.

OmniFiles is built with Sinatra and Rack and uses an Mongo database to store shortened
urls and statistics.

## Installation

OmniFiles is a Sinatra/Rack application and can be used as a gem or as a server in local directory.

### As a gem

1. Install a gem

        gem install omnifiles

2. Point an env variable `OMNIFILES_SETTINGS` to location of a settings file `/path/to/settings.yaml` (see Configurarion).

3. Start an app as a Thin server

        OMNIFILES_SETTINGS=/path/to/settings.yaml omnifiles
Of course, you can provide any additional Thin options at command line:

        OMNIFILES_SETTINGS=/path/to/settings.yaml omnifiles -p 3000
Or at config file (see Thin documentation):

        OMNIFILES_SETTINGS=/path/to/settings.yaml omnifiles -C /path/to/thin.yaml

## As a rack app

OmniFiles can be started using `config.ru` with you favourite Rack server.

1. Clone a git repo

2. Install dependencies

        bundle install

3. Point an env variable `OMNIFILES_SETTINGS` to location of a settings file `/path/to/settings.yaml` (see Configurarion).

4. Start Rack app

        rackup

## Configuration

Settings file template can be found at `config/settings.yaml.example`.

If you prefer production Rack environment, please use `production` instead of `development` section in the config.
Also specify `-E production` at `omnifiles` (actially Thin) command line.

If you prefer to run omnifiles as a daemon, don't forget to set log and pid location. Author prefer to follow XDG and place all the files at the `~/.local/share/omnifiles`, including the database. So one can use following command line:

    OMNIFILES_SETTINGS=$HOME/.local/share/omnifiles/settings.yaml omnifiles start -d -a 127.0.0.1 -p 3000 \
      -l $HOME/.local/share/omnifiles/omnifiles.log \
      -P $HOME/.local/share/omnifiles/omnifiles.pid

Complex Thin options can be hidden in Thin config.yaml file:

    OMNIFILES_SETTINGS=$HOME/.local/share/omnifiles/settings.yaml omnifiles start -C $HOME/.local/share/omnifiles/thin.yaml

Note that OmniFiles and Thin configs are two distinct configs.

## Usage

1. Storing files.
OmniFiles can store files by issuing an authenticated POST form request:

        % curl --digest -u user:secret -F "file=@/path/to/file.jpg" 'http://localhost:3000/store'
        http://localhost:3000/f/e63A12
Or you can post a file just as a binary POST data:

        % curl --digest -u user:secret -H "Content-Type: application/octet-stream" --data-binary "@/path/to/file.jpg" 'http://localhost:3000/store'
        http://localhost:3000/f/e63A12
OmniFiles returns a short url in response so you can just issue following command to save URL in clipboard

        % curl --digest -u user:secret -F "file=@/path/to/file.jpg" 'http://localhost:3000/store' | pbcopy

2. Accessing files.
Just access given URL:

        % curl http://localhost:3000/f/e63A12
OmniFiles remembers MIME type and composes a correct typed response.
Header `X-Original-Filename` contains escaped original filename.

3. Viewing statistics.
OmniFiles provides file access statistics using authenticated requests.
Visit an url using web browser or curl.

        http://localhost:3000/stat/e63A12

3. Control panel.
Viewing and deleting stored files can be performed at control panel:

		http://localhost:3000/stat

## License information

Please consult with the LICENSE.txt for license information. It is MIT by the way.


text:
CREATE DEFINER=`root`@`localhost` PROCEDURE `createPost`(IN `inRecipeName` VARCHAR(255), IN `inPostBody` TEXT)
BEGIN
DECLARE result VARCHAR(255);
INSERT
INTO	recipe	(description,	name,	username)
VALUES	(inPostBody, inRecipeName,'user');
SET	result	= 'Recipe created!';
SELECT result;
END


text:
using System;
using System.Text;
using System.CodeDom;
using System.Reflection;
using System.Globalization;
using System.Collections.Generic;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Activities.Common;

namespace System.Workflow.Activities.Rules
{
    [Serializable]
    public abstract class RuleAction
    {
        public abstract bool Validate(RuleValidation validator);
        public abstract void Execute(RuleExecution context);
        public abstract ICollection<string> GetSideEffects(RuleValidation validation);
        public abstract RuleAction Clone();
    }

    [Serializable]
    public class RuleHaltAction : RuleAction
    {
        public override bool Validate(RuleValidation validator)
        {
            // Trivial... nothing to validate.
            return true;
        }

        public override void Execute(RuleExecution context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            context.Halted = true;
        }

        public override ICollection<string> GetSideEffects(RuleValidation validation)
        {
            return null;
        }

        public override RuleAction Clone()
        {
            return (RuleAction)this.MemberwiseClone();
        }

        public override string ToString()
        {
            return "Halt";
        }

        public override bool Equals(object obj)
        {
            return (obj is RuleHaltAction);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    [Serializable]
    public class RuleUpdateAction : RuleAction
    {
        private string path;

        public RuleUpdateAction(string path)
        {
            this.path = path;
        }

        public RuleUpdateAction()
        {
        }

        public string Path
        {
            get { return path; }
            set { path = value; }
        }

        public override bool Validate(RuleValidation validator)
        {
            if (validator == null)
                throw new ArgumentNullException("validator");

            bool success = true;

            if (path == null)
            {
                ValidationError error = new ValidationError(Messages.NullUpdate, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                success = false;
            }

            // now make sure that the path is valid
            string[] parts = path.Split('/');
            if (parts[0] == "this")
            {
                Type currentType = validator.ThisType;
                for (int i = 1; i < parts.Length; ++i)
                {
                    if (parts[i] == "*")
                    {
                        if (i < parts.Length - 1)
                        {
                            // The "*" occurred in the middle of the path, which is a no-no.
                            ValidationError error = new ValidationError(Messages.InvalidWildCardInPathQualifier, ErrorNumbers.Error_InvalidWildCardInPathQualifier);
                            error.UserData[RuleUserDataKeys.ErrorObject] = this;
                            validator.AddError(error);
                            success = false;
                            break;
                        }
                        else
                        {
                            // It occurred at the end, which is okay.
                            break;
                        }
                    }
                    else if (string.IsNullOrEmpty(parts[i]) && i == parts.Length - 1)
                    {
                        // It's okay to end with a "/".
                        break;
                    }

                    while (currentType.IsArray)
                        currentType = currentType.GetElementType();

                    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                    if (validator.AllowInternalMembers(currentType))
                        bindingFlags |= BindingFlags.NonPublic;
                    FieldInfo field = currentType.GetField(parts[i], bindingFlags);
                    if (field != null)
                    {
                        currentType = field.FieldType;
                    }
                    else
                    {
                        PropertyInfo property = currentType.GetProperty(parts[i], bindingFlags);
                        if (property != null)
                        {
                            currentType = property.PropertyType;
                        }
                        else
                        {
                            string message = string.Format(CultureInfo.CurrentCulture, Messages.UpdateUnknownFieldOrProperty, parts[i]);
                            ValidationError error = new ValidationError(message, ErrorNumbers.Error_InvalidUpdate);
                            error.UserData[RuleUserDataKeys.ErrorObject] = this;
                            validator.AddError(error);
                            success = false;
                            break;
                        }
                    }
                }
            }
            else
            {
                ValidationError error = new ValidationError(Messages.UpdateNotThis, ErrorNumbers.Error_InvalidUpdate);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                success = false;
            }

            return success;
        }

        public override void Execute(RuleExecution context)
        {
            // This action has no execution behaviour.
        }

        public override ICollection<string> GetSideEffects(RuleValidation validation)
        {
            return new string[] { this.path };
        }

        public override RuleAction Clone()
        {
            return (RuleAction)this.MemberwiseClone();
        }

        public override string ToString()
        {
            return "Update(\"" + this.path + "\")";
        }

        public override bool Equals(object obj)
        {
#pragma warning disable 56506
            RuleUpdateAction other = obj as RuleUpdateAction;
            return ((other != null) && (string.Equals(this.Path, other.Path, StringComparison.Ordinal)));
#pragma warning restore 56506
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    [Serializable]
    public class RuleStatementAction : RuleAction
    {
        private CodeStatement codeDomStatement;

        public RuleStatementAction(CodeStatement codeDomStatement)
        {
            this.codeDomStatement = codeDomStatement;
        }

        public RuleStatementAction(CodeExpression codeDomExpression)
        {
            this.codeDomStatement = new CodeExpressionStatement(codeDomExpression);
        }

        public RuleStatementAction()
        {
        }

        public CodeStatement CodeDomStatement
        {
            get { return codeDomStatement; }
            set { codeDomStatement = value; }
        }

        public override bool Validate(RuleValidation validator)
        {
            if (validator == null)
                throw new ArgumentNullException("validator");

            if (codeDomStatement == null)
            {
                ValidationError error = new ValidationError(Messages.NullStatement, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                return false;
            }
            else
            {
                return CodeDomStatementWalker.Validate(validator, codeDomStatement);
            }
        }

        public override void Execute(RuleExecution context)
        {
            if (codeDomStatement == null)
                throw new InvalidOperationException(Messages.NullStatement);
            CodeDomStatementWalker.Execute(context, codeDomStatement);
        }

        public override ICollection<string> GetSideEffects(RuleValidation validation)
        {
            RuleAnalysis analysis = new RuleAnalysis(validation, true);
            if (codeDomStatement != null)
                CodeDomStatementWalker.AnalyzeUsage(analysis, codeDomStatement);
            return analysis.GetSymbols();
        }

        public override RuleAction Clone()
        {
            RuleStatementAction newAction = (RuleStatementAction)this.MemberwiseClone();
            newAction.codeDomStatement = CodeDomStatementWalker.Clone(codeDomStatement);
            return newAction;
        }

        public override string ToString()
        {
            if (codeDomStatement == null)
                return "";

            StringBuilder decompilation = new StringBuilder();
            CodeDomStatementWalker.Decompile(decompilation, codeDomStatement);
            return decompilation.ToString();
        }

        public override bool Equals(object obj)
        {
#pragma warning disable 56506
            RuleStatementAction other = obj as RuleStatementAction;
            return ((other != null) && (CodeDomStatementWalker.Match(CodeDomStatement, other.CodeDomStatement)));
#pragma warning restore 56506
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}


text:
namespace mx
{
    namespace core
    {
        class TechnicalChoice;
        using TechnicalChoicePtr = std::shared_ptr<TechnicalChoice>;
        using TechnicalChoiceSet = std::vector<TechnicalChoicePtr>;
    }

    namespace impl
    {
        class TechnicalFunctions
        {

        public:
            TechnicalFunctions( const core::TechnicalChoiceSet& inTechincalChoiceSet, Cursor inCursor );

            void parseTechnicalMarks( std::vector<api::MarkData>& outMarks ) const;

        private:
            const core::TechnicalChoiceSet& myTechincalChoiceSet;
            const Cursor myCursor;

        private:
            bool parseTechicalMark( const core::TechnicalChoice& techicalChoice, api::MarkData& outMarkData ) const;
        };
    }
}


text:
package simplejdbc.exception;

import junit.framework.TestCase;

/**
 * SimpleJdbcRuntimeExceptionのテストクラス
 * @author yasu
 *
 */
public class SimpleJdbcRuntimeExceptionTest extends TestCase {

	/**
	 * protectedコンストラクタのテスト
	 */
	public void testProtectedConstructer() {

		SimpleJdbcRuntimeException exception = new SimpleJdbcRuntimeException();
		assertEquals(null, exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException("test message");
		assertEquals("test message", exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException("test message", new IllegalArgumentException("dummy message"));
		assertEquals("test message", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());

		exception = new SimpleJdbcRuntimeException(new IllegalArgumentException("dummy message"));
		assertEquals("java.lang.IllegalArgumentException: dummy message", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());
	}

	/**
	 * publicコンストラクタのテスト
	 */
	public void testPublicConstructer() {

		SimpleJdbcRuntimeException exception = new SimpleJdbcRuntimeException(EntityMock.class, "test message");
		assertEquals("<simplejdbc.exception.SimpleJdbcRuntimeExceptionTest$EntityMock> test message", exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException(EntityMock.class, "test message", new IllegalArgumentException("dummy message"));
		assertEquals("<simplejdbc.exception.SimpleJdbcRuntimeExceptionTest$EntityMock> test message", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());

		exception = new SimpleJdbcRuntimeException(EntityMock.class, "test message", null);
		assertEquals("<simplejdbc.exception.SimpleJdbcRuntimeExceptionTest$EntityMock> test message", exception.getMessage());
		assertEquals(null ,exception.getCause());

		exception = new SimpleJdbcRuntimeException(EntityMock.class, null);
		assertEquals("<simplejdbc.exception.SimpleJdbcRuntimeExceptionTest$EntityMock> null", exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException(null, "test message");
		assertEquals("test message", exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException(null, "test message", new IllegalArgumentException("dummy message"));
		assertEquals("test message", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());

		exception = new SimpleJdbcRuntimeException(EntityMock.class, null, new IllegalArgumentException("dummy message"));
		assertEquals("<simplejdbc.exception.SimpleJdbcRuntimeExceptionTest$EntityMock> null", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());

		exception = new SimpleJdbcRuntimeException((Class<?>) null, null);
		assertEquals("null", exception.getMessage());
		assertEquals(null, exception.getCause());

		exception = new SimpleJdbcRuntimeException((Class<?>) null, null, new IllegalArgumentException("dummy message"));
		assertEquals("null", exception.getMessage());
		assertTrue(exception.getCause() instanceof IllegalArgumentException);
		assertEquals("dummy message" ,exception.getCause().getMessage());

		exception = new SimpleJdbcRuntimeException((Class<?>) null, null, null);
		assertEquals("null", exception.getMessage());
		assertEquals(null ,exception.getCause());

	}

	/**
	 * エンティティクラスのモック
	 * @author yasu
	 *
	 */
	public static class EntityMock {

		private String dummyField;

		public String getDummyField() {
			return dummyField;
		}

		public void setDummyField(String dummyField) {
			this.dummyField = dummyField;
		}

	}

}


text:
layout: manual
title: Backup
category: SetUp
path: '/en/:id'
language: en
flag: us
---

### Backup of data

- When Tomcat startup, create a folder ".knowledge" in home directory, and stores the system data.
- You can backup to copy of this directory.

### How to check data directory path
- When start-up of knowledge, data directory path is output to tomcat log. ({tomcatdirectory}/logs/catalina.out)

```
INFO  2016-06-09 07:47:37,424 [InitializationListener(49)] Knowledge start
INFO  2016-06-09 07:47:37,424 [InitializationListener(50)] knowledge install path: 'Knowledge webapp path'
INFO  2016-06-09 07:47:37,425 [InitializationListener(51)] knowledge home path: 'Data directory for backup'
```

### How to change data directory path
- You can change the data directory to set environment variable 'KNOWLEDGE_HOME'.


text:
@interface RootViewController () <WebServiceConnectorDelegate>
- (void)handleWebServiceConnector: (WebServiceConnector*)webServiceConnector
                           result: (id)result;
@end

////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation RootViewController
@synthesize tableView=_tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	NSArray* sampleData = @[@"One", @"Two", @"Three"];
	[self setTableData: sampleData
		  forTableView: self.tableView];
}

#pragma mark -
#pragma mark IBActions
- (IBAction)webServiceTestAction: (id)sender
{
#if USE_COMPLETION_HANLDER
    WebServiceConnector* wsc = [[WebServiceConnector alloc] initWithURLString: WEB_SERVICE_URL_STRING
																   parameters: nil
																	 httpBody: nil
                                                            completionHandler: ^(WebServiceConnector* wsc, id result, NSError* error){
                                                                if ( result )
                                                                {
                                                                    [self handleWebServiceConnector: wsc
                                                                                result: result];
                                                                }
                                                                else // Error
                                                                {
                                                                    [AlertUtility showAlertWithTitle: NSLocalizedString(@"Connection Error", @"UIAlertView title")
                                                                                message: [error localizedDescription]];
                                                                }
                                                            }];
#else
	WebServiceConnector* wsc = [[WebServiceConnector alloc] initWithURLString: WEB_SERVICE_URL_STRING
																   parameters: nil
																	 httpBody: nil
																	 delegate: self];
#endif

	if ( wsc )
	{
		wsc.httpMethod = HTTP_GET;
		[wsc start];   // starts or queues the web service connector
	}
	else
	{
		[AlertUtility showAlertWithTitle: NSLocalizedString(@"Error", @"UIAlertView title")
								 message: NSLocalizedString(@"There was an error creating the web service connector.", @"UIAlertView message")];
	}
}

#pragma mark -
- (void)didSelectDataObject: (id<DataObject>)dataObject
{
	if ( [dataObject isKindOfClass: [NSString class]] )
	{
		NSString* message = (NSString*)dataObject;

		[AlertUtility showAlertWithTitle: NSLocalizedString(@"You Selected", @"UIAlertView title")
								 message: message];
	}
	else
	{
		[super didSelectDataObject: dataObject];
	}
}

#pragma mark -
#pragma mark WebServiceConnectorDelegate
- (void)webServiceConnector: (WebServiceConnector*)webServiceConnector
        didFinishWithResult: (id)result;
{
    [self handleWebServiceConnector: webServiceConnector
                             result: result];
}

- (void)webServiceConnector: (WebServiceConnector*)webServiceConnector
           didFailWithError: (NSError*)error
{
    KL_LOG(@"[%@]webServiceConnector:didFailWithError: %@", CLASS_NAME, [error localizedDescription]);

}

#pragma mark -
#pragma mark Private
- (void)handleWebServiceConnector: (WebServiceConnector*)webServiceConnector
                           result: (id)result
{
    // Check for errors
    NSInteger statusCode = webServiceConnector.statusCode;
	if ( statusCode == HTTP_STATUS_UNAUTHORIZED || statusCode == HTTP_STATUS_FORBIDDEN )
	{
        [AlertUtility showAlertWithTitle: NSLocalizedString(@"Server Error", @"UIAlertView title")
                                 message: NSLocalizedString(@"Your connection was not authorized.", @"")];
	}
    else if ( statusCode == HTTP_STATUS_INTERNAL_SERVER_ERROR )
    {
        [AlertUtility showAlertWithTitle: NSLocalizedString(@"Server Error", @"UIAlertView title")
                                 message: NSLocalizedString(@"There was an internal server error, please try your request again later.", @"")];
    }
	else
	{
        KL_LOG(@"[%@]webServiceConnector:didFinishWithResult:\n%@", CLASS_NAME, result);
		NSDictionary* resultDict = SAFE_DICTIONARY(result);
		NSMutableArray* dataArray = [NSMutableArray array];

		// Step through all of the results, looking for strings
		for ( NSString* key in resultDict )
		{
			NSString* str = SAFE_STRING([resultDict objectForKey: key]);

			if ( str )
				[dataArray addObject: str];
		}

		// If we have some data, update the tableView
		if ( [dataArray count] )
		{
			[self setTableData: dataArray
				  forTableView: self.tableView];

			[self.tableView reloadData];
		}
    }
}

@end


text:
Bacon.Observable.prototype.flatMapConcat = function() {
  var desc = new Bacon.Desc(this, "flatMapConcat", Array.prototype.slice.call(arguments, 0));
  return withDesc(desc, this.flatMapWithConcurrencyLimit(1, ...arguments));
};


text:
char run;

void close_win(void);
void print_mouse_motion(float, float);
void print_scroll_up(void);
void print_scroll_down(void);
void print_scroll_left(void);
void print_scroll_right(void);
void print_left_mb(void);
void print_right_mb(void);
void print_w(void);
void print_a(void);
void print_s(void);
void print_d(void);

int main(int argc, char *argv[])
{
  printf("starting unit test %s\n", PROGRAM_NAME);
  if(argc){}
  if(argv){}

  NUS_window win;
  NUS_event_handler eve;

  if(nus_window_build(PROGRAM_NAME, 600, 400, &win) != NUS_SUCCESS){
    printf("ERROR::failed to build nus window\n");
    return -1;
  }
  if(nus_event_handler_build(&eve) != NUS_SUCCESS){
    printf("ERROR::failed to build event handler\n");
    return -1;
  }

  nus_event_handler_append(eve, NUS_EVENT_CLOSE_WINDOW, 0, close_win);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_MOTION,
				    0, print_mouse_motion);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_SCROLL,
				    NUS_SCROLL_UP,
				    print_scroll_up);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_SCROLL,
				    NUS_SCROLL_DOWN,
				    print_scroll_down);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_SCROLL,
				    NUS_SCROLL_LEFT,
				    print_scroll_left);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_SCROLL,
				    NUS_SCROLL_RIGHT,
				    print_scroll_right);

  nus_event_handler_append(eve, NUS_EVENT_MOUSE_BUTTON_PRESS,
				    NUS_MOUSE_BUTTON_LEFT, print_left_mb);
  nus_event_handler_append(eve, NUS_EVENT_MOUSE_BUTTON_PRESS,
				    NUS_MOUSE_BUTTON_RIGHT, print_right_mb);

  nus_event_handler_append(eve, NUS_EVENT_KEY_PRESS, NUS_KEY_ESC, close_win);
  nus_event_handler_append(eve, NUS_EVENT_KEY_PRESS, NUS_KEY_W, print_w);
  nus_event_handler_append(eve, NUS_EVENT_KEY_PRESS, NUS_KEY_A, print_a);
  nus_event_handler_append(eve, NUS_EVENT_KEY_PRESS, NUS_KEY_S, print_s);
  nus_event_handler_append(eve, NUS_EVENT_KEY_PRESS, NUS_KEY_D, print_d);

  nus_event_handler_set(&eve);

  run = 1;
  while(run){
    nus_system_events_handle(win);
  }

  nus_event_handler_free(&eve);
  nus_window_free(&win);

  printf("unit test %s completed\n", PROGRAM_NAME);
  return 0;
}
void close_win(void){
  run = 0;
}

void print_mouse_motion(float relative_x, float relative_y)
{
  printf("change in mouse x: %f\nchange in mouse y:%f\n", relative_x, relative_y);
}
void print_scroll_up(void)
{
  printf("scrolled up\n");
}
void print_scroll_down(void)
{
  printf("scrolled down\n");
}
void print_scroll_left(void)
{
  printf("scrolled left\n");
}
void print_scroll_right(void)
{
  printf("scrolled right\n");
}
void print_left_mb(void)
{
  printf("left click\n");
}
void print_right_mb(void)
{
  printf("right click\n");
}
void print_w(void)
{
  printf("w\n");
}
void print_a(void)
{
  printf("a\n");
}
void print_s(void)
{
  printf("s\n");
}
void print_d(void)
{
  printf("d\n");
}


text:
module BandsInTownApiClient
	class Request
		def initialize( action, artist_id, client_id, format=:json )
			base_url = "http://api.bandsintown.com/"
			@action = action
			@artist_id = artist_id
			get_params = "?api_version=2.0&app_id=#{client_id}"
			@url = "#{base_url}#{action_uri}.#{format}#{get_params}"
		end

		def response
			begin
				r = open(@url)
				JSON::parse(r.read)
			rescue => e
				@error = e
				error_response
			end
		end

		def error_response
			{ error: @error }
		end

		def action_uri
			case @action
				when :events
					"artists/#{@artist_id}/events"
				else
					raise "Unsuported api action"
			end
		end
	end
end


text:
<?php

namespace Akamai\Analytics;

use Akamai\Analytics\AbstractService\MediaAnalytics;

class Viewer extends MediaAnalytics
{
    const API_REPORT_TYPE_VIEWER = 'viewer-diagnostics';

    public function getReportType()
    {
        return self::API_REPORT_TYPE_VIEWER;
    }
}


text:
module Data.TopicFilterTrieSpec (spec) where

import           Data.List (foldl', sort)

import qualified Data.Text as T

import qualified Data.TopicFilterTrie as TT
import           Network.MQTT.Packet

import           Test.Hspec

spec :: Spec
spec = do
  describe "empty" $ do
    it "creates empty topic filter trie" $ do
      let tt = TT.empty :: TT.TopicFilterTrie Int
      TT.lookup (topicFilter "b") tt `shouldBe` Nothing

    it "empty tries are same" $ do
      let x = TT.empty :: TT.TopicFilterTrie Int
      let y = TT.empty :: TT.TopicFilterTrie Int
      x `shouldBe` y

  describe "member" $ do
    it "returns False on empty trie" $ do
      TT.member (topicFilter "a") TT.empty `shouldBe` False

    it "finds element" $ do
      let tt = trie [ "a" --> "text" ]
      TT.member (topicFilter "a") tt `shouldBe` True

  describe "insert" $ do
    it "inserts single element in empty trie" $ do
      let tt = TT.insert (topicFilter "a") "text" TT.empty
      TT.lookup (topicFilter "a") tt `shouldBe` Just "text"

    it "inserts with empty topic filter name" $ do
      let tt = TT.insert (topicFilter "") "hello" TT.empty
      TT.lookup (topicFilter "") tt `shouldBe` Just "hello"

    it "overrides old value" $ do
      let tt = TT.insert (topicFilter "a/b") "y" $ trie [ "a/b" --> "x" ]
      TT.lookup (topicFilter "a/b") tt `shouldBe` Just "y"

  describe "lookup" $ do
    it "doesn't find anything in empty trie" $ do
      TT.lookup (topicFilter "a") (TT.empty :: TT.TopicFilterTrie Int) `shouldBe` Nothing

  describe "delete" $ do
    it "deletes single element" $ do
      let tt = trie [ "a" --> "text" ]
      let tt' = TT.delete (topicFilter "a") tt
      TT.member (topicFilter "a") tt' `shouldBe` False

    it "deletes from empty trie" $ do
      let tt = TT.delete (topicFilter "a") TT.empty :: TT.TopicFilterTrie Int
      TT.member (topicFilter "a") tt `shouldBe` False

  describe "matches" $ do
    it "works on one-element filter" $ do
      let tt = trie [ "a" --> "text" ]
      TT.matches (topic "a") tt `shouldBe` ["text"]

    it "finds exact match" $ do
      let tt = trie [ "a/b/c" --> "text" ]
      TT.matches (topic "a/b/c") tt `shouldBe` ["text"]

    it "doesn't trigger on submatch" $ do
      let tt = trie [ "a/b/c" --> "text" ]
      TT.matches (topic "a/b") tt `shouldBe` []

    it "doesn't trigger on overmatch" $ do
      let tt = trie [ "a/b/c" --> "text" ]
      TT.matches (topic "a/b/c/d") tt `shouldBe` []

    it "single-level wildcard works in one-level topic" $ do
      let tt = trie [ "+" --> "text" ]
      TT.matches (topic "hello") tt `shouldBe` ["text"]

    it "single-level wildcard works at end" $ do
      let tt = trie [ "a/+" --> "text" ]
      TT.matches (topic "a/b") tt `shouldBe` ["text"]

    it "multiple matches" $ do
      let tt = trie [ "+" --> "wildcard"
                    , "hello" --> "exact match"
                    ]
      -- sorting to make results stable
      sort (TT.matches (topic "hello") tt)
        `shouldBe` sort ["exact match", "wildcard"]

    it "single-level wildcard works in the middle" $ do
      let tt = trie [ "a/+/b" --> "text" ]
      TT.matches (topic "a/hello/b") tt `shouldBe` ["text"]
      TT.matches (topic "a/hello/c") tt `shouldBe` []

    it "multi-level wildcard work in one-level topic" $ do
      let tt = trie [ "#" --> "text" ]
      TT.matches (topic "hello") tt `shouldBe` ["text"]

    it "multi-level wildcard matches at end" $ do
      let tt = trie [ "hello/#" --> "text" ]
      TT.matches (topic "hello/world") tt `shouldBe` ["text"]

    it "multi-level wildcard matches multiple levels" $ do
      let tt = trie [ "hello/#" --> "text" ]
      TT.matches (topic "hello/world/test") tt `shouldBe` ["text"]

trie :: [(String, a)] -> TT.TopicFilterTrie a
trie = foldl' (\xs (x,y) -> TT.insert (topicFilter x) y xs) TT.empty

(-->) :: a -> b -> (a, b)
(-->) = (,)

topicFilter :: String -> TopicFilter
topicFilter = TopicFilter . T.pack

topic :: String -> TopicName
topic = TopicName . T.pack


text:
namespace net {

// SSLKeyLogger logs SSL key material for debugging purposes. This should only
// be used when requested by the user, typically via the SSLKEYLOGFILE
// environment variable. See also
// https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
class NET_EXPORT SSLKeyLogger {
 public:
  virtual ~SSLKeyLogger() {}

  // Writes |line| followed by a newline. This may be called by multiple threads
  // simultaneously. If two calls race, the order of the lines is undefined, but
  // each line will be written atomically.
  virtual void WriteLine(const std::string& line) = 0;
};

}  // namespace net

#endif  // NET_SSL_SSL_KEY_LOGGER_H_


text:
require 'stringio'

share_as :AllNodes do

  it "should respond to source_path" do
    @instance.should respond_to(:source_path)
  end

  it "should have as source path the one given to the constructor" do
    @instance.source_path.should == @source_path
  end

  it "should have a dest_path accessor" do
    @instance.should respond_to(:dest_path)
    @instance.should respond_to(:dest_path=)
  end

  it "should be able to set an object as a dest_path" do
    path = mock "DestPath"
    @instance.dest_path = path
    @instance.dest_path.should == path
  end

  it "should have a meta_info attribute" do
    @instance.should respond_to(:meta_info)
  end

  it "should have the meta informations stored in an hash" do
    @instance.meta_info.should be_kind_of(Hash)
  end

  it "should be able to store some information in the meta_info hash" do
    @instance.meta_info[:hello].should be_nil
    @instance.meta_info[:hello] = "world"
    @instance.meta_info[:hello].should == "world"
  end

  it "should respond to buildable?" do
    @instance.should respond_to(:buildable?)
  end

  it "should be buildable if it has got a dest path" do
    @instance.dest_path = mock "Path"
    @instance.should_receive(:template?).and_return(false)
    @instance.should be_buildable
  end

  it "should not be buildable if it hasn't got a dest path" do
    @instance.dest_path = nil
    @instance.should_not be_buildable
  end

  it "should respond to template?" do
    @instance.should respond_to(:template?)
  end

  it "should not be buildable if it is a template" do
    @instance.dest_path = mock "Path"
    @instance.should_receive(:template?).and_return(true)
    @instance.should_not be_buildable
  end
end

share_as :AllStandardNodes do
  it_should_behave_like AllNodes

  it "should respond to build" do
    @instance.should respond_to(:build)
  end

  it "should be buildable" do
    @instance.should be_buildable
  end

  it "should not be a template" do
    @instance.should_not be_template
  end

  it "should have a constructor with 3 parameters" do
    lambda {
      @instance.class.new(@context, @source_path, @path_handler)
    }.should_not raise_error
  end
end

share_as :AllTemplateNodes do
  it_should_behave_like AllNodes

  it "should respond to render" do
    @instance.should respond_to(:render)
  end

  it "should not be buildable" do
    @instance.should_not be_buildable
  end

  it "should be a template" do
    @instance.should be_template
  end

  it "should render the content of the passed hash" do
    @instance.render(@node, :main => "hello world" ).should =~ /hello world/
  end
end


text:
package com.pxene.hadoop;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.GenericOptionsParser;

public class GetWords {

	public static class GetWordsMapper extends MapReduceBase implements
			Mapper<LongWritable, Text, Text, Text>{

		@Override
		public void map(LongWritable key, Text value,
				OutputCollector<Text, Text> output, Reporter reporter)
				throws IOException {

			//value is the data of line
			String keyWords = null;
			Pattern bdPattern = Pattern.compile(".*m.baidu.com.*");
			Pattern smPattern = Pattern.compile(".*m.sm.cn.*");
			Pattern sougouPattern = Pattern.compile(".*m.sougou.com.*");
			Pattern soPattern = Pattern.compile(".*m.so.com.*");

			Matcher bdMatcher = bdPattern.matcher(value.toString());
			Matcher smMatcher = smPattern.matcher(value.toString());
			Matcher sougouMatcher = sougouPattern.matcher(value.toString());
			Matcher soMatcher = soPattern.matcher(value.toString());
			System.out.println("line data is " + value.toString());
			String[] rows = value.toString().split(new Character((char) 0x01).toString());
			String url = rows[3];
			if (bdMatcher.matches() || smMatcher.matches() ||
					sougouMatcher.matches() || soMatcher.matches()) {
				if (bdMatcher.matches()) {
					//baidu search url
					Pattern wordPattern = Pattern.compile(".*?word=.*");
					Matcher wordMatcher = wordPattern.matcher(url);
					if (wordMatcher.matches()) {
						//include keywords
						int start = url.indexOf("?word=");
						int end = url.indexOf("&");
						if (start > 0 && end > 0) {
							keyWords = url.substring(start + 6, end);
							System.out.println("baidu keywords is " + URLDecoder.decode(keyWords, "UTF-8"));
							output.collect(new Text(rows[1]), new Text(URLDecoder.decode(keyWords, "UTF-8")));
						}
					}
				}

				if (smMatcher.matches() || soMatcher.matches()) {

					//shenma search && 360so search
					Pattern wordPattern = Pattern.compile(".*?q=.*");
					Matcher wordMatcher = wordPattern.matcher(url);
					if (wordMatcher.matches()) {

						//
						int start = url.indexOf("?q=");
						int end = url.indexOf("&");
						if (start > 0 && end > 0) {

							keyWords = url.substring(start + 3, end);
							System.out.println("sm and so keywords is " + URLDecoder.decode(keyWords, "UTF-8"));
							output.collect(new Text(rows[1]), new Text(URLDecoder.decode(keyWords, "UTF-8")));
						}
					}
				}

				if (sougouMatcher.matches()) {

					//360so
					Pattern wordPattern = Pattern.compile(".*keyword=.*");
					Matcher wordMatcher = wordPattern.matcher(url);
					if(wordMatcher.matches()){

						int start = url.indexOf("keyword=");
						int end = url.indexOf("&", start);
						if (start > 0 && end > 0) {
							keyWords = url.substring(start + 8, end);
						}else {
							keyWords = url.substring(start);
						}
						System.out.println("sougou keywords is " + URLDecoder.decode(keyWords, "UTF-8"));
						output.collect(new Text(rows[1]), new Text(URLDecoder.decode(keyWords, "UTF-8")));
					}
				}
				//TODO rows[3] get the abstract word
				System.out.println("IMSI is " + rows[1]);
				System.out.println("url is " + rows[3]);
			}
		}
	}

	public static class GetWordsReducer extends MapReduceBase implements
			Reducer<Text, Text, Text, Text>{

		@Override
		public void reduce(Text key, Iterator<Text> values,
				OutputCollector<Text, Text> output, Reporter reporter)
				throws IOException {

			boolean first = true;
		    StringBuilder toReturn = new StringBuilder();
		    while (values.hasNext()){
		    	if (!first){
		    		toReturn.append(",");
		    	}
		        first=false;
		        toReturn.append(values.next().toString());
		    }

		      output.collect(key, new Text(toReturn.toString()));
		}
	}

	public static class SplitWordsReducer extends MapReduceBase implements
		Reducer<Text, Text, Text, Text>{

		@Override
		public void reduce(Text key, Iterator<Text> values,
				OutputCollector<Text, Text> output, Reporter reporter)
				throws IOException {

		}

	}

	public static void main(String[] args) throws IOException {
		JobClient client = new JobClient();
	    JobConf conf = new JobConf(GetWords.class);
	    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
	    if (otherArgs.length < 2) {
	      System.err.println("Usage: dealData <in> [<in>...] <out>");
	      System.exit(2);
	    }
	    conf.setJobName("GetWords");
	    conf.setOutputKeyClass(Text.class);
	    conf.setOutputValueClass(Text.class);
	    for (int i = 0; i < otherArgs.length - 1; ++i) {
		      FileInputFormat.addInputPath(conf, new Path(otherArgs[i]));
		}
		FileOutputFormat.setOutputPath(conf,
		      new Path(otherArgs[otherArgs.length - 1]));
	    conf.setMapperClass(GetWordsMapper.class);
	    conf.setReducerClass(GetWordsReducer.class);
	    client.setConf(conf);
	    try {
	      JobClient.runJob(conf);
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	  }
}