text:
'''TODO add file comment!
'''

from datetime import datetime
import csv
import logging
import StringIO

def _strip_bom(fname):
    '''Return file object with Byte Order Mark (BOM) stripped off.

    Note: if the file does not exist the exception will need to be handled by
        the calling code.
    '''
    logging.debug('Stripping the BOM (if present) off %s...', fname)
    with open(fname, 'r') as raw:
        pre_strip = raw.read()

    # decode; if utf-8 this will strip off BOM, else nothing changes
    post_strip = pre_strip.decode('utf-8-sig')
    return StringIO.StringIO(post_strip)

def _find_missing_csv_fields(dict_reader, field_list):
    '''Return list of all fields in field_list that dict_reader is missing'''
    missing_fields = list()
    for field in field_list:
        if field not in dict_reader.fieldnames:
            missing_fields.append(field)

    return missing_fields

def _get_csv_reader(fname, check_fields):
    '''Create the CSV reader object and check it for the passed in fields'''
    csv_reader = csv.DictReader(_strip_bom(fname), skipinitialspace=True)
    missing_fields = _find_missing_csv_fields(csv_reader, check_fields)
    if missing_fields:
        raise Exception('%s is missing these column(s): %s' % (fname, (', '.join(missing_fields))))
    return csv_reader

def _get_date_key(date_str, date_fmt, fname):
    try:
        date_key = datetime.strptime(date_str, date_fmt).date()
    except ValueError:
        raise ValueError('Incorrect date format in %s. \'%s\' doesn\'t match %s' % (fname, date_str, date_fmt))

    return date_key

def build_key_val_dict(fname, dict_key, dict_val, date_fmt):
    '''Creates a dictionary from a CSV file fname from two columns in the file

    {dict_key: dict_val}

    Exceptions are raised under these circumstances (calling code should handle
    accordingly):
        * The file doesn't exist (via _get_csv_reader())
        * The CSV does not contain the header fields in 'dict_key' and/or
          'dict_val' (via _get_csv_reader)
        * A date is not formatted correctly
        * The date appears more than once in the CSV file

    Note: that since we are sensitive to the csv columns, we cannot just read in
    the file straight with the csv.DictReader since it doesn't support stripping
    off the BOM. We have to first read the characters in (which will strip off
    the BOM) and then pass it to the DictReader via a StringIO. I'm open to
    better suggestions.
    '''
    csv_reader = _get_csv_reader(fname, [dict_key, dict_val])

    my_dict = dict()
    for item in csv_reader:
        date_key = _get_date_key(item[dict_key], date_fmt, fname)

        # Make sure this date key hasn't been added before. If it has log the
        # warning but still update the existing key with the new value
        if date_key in my_dict.keys():
            raise Exception('This date has appeared more than once: %s. Please ensure that %s has unique dates and try again', date_key.strftime(date_fmt), fname)

        my_dict[date_key] = float(item[dict_val])

    return my_dict

def build_key_multi_val_dict(fname, dict_key, val_list, date_fmt):
    '''Creates a dictionary to a dictionary from a CSV file and it's values.

    {dict_key: {val1: val, val2: val,...}}
    '''
    # create a copy of the val_list so we can add the key to it for the filed checker
    check_vals = list(val_list)
    check_vals.append(dict_key)
    csv_reader = _get_csv_reader(fname, check_vals)

    my_dict = dict()
    for item in csv_reader:
        date_key = _get_date_key(item[dict_key], date_fmt, fname)

        # Make sure this date key hasn't been added before. If it has log the
        # warning but still update the existing key with the new value
        if date_key in my_dict.keys():
            raise Exception('This date has appeared more than once: %s. Please ensure that %s has unique dates and try again', date_key.strftime(date_fmt), fname)

        # build inner dict
        inner_dict = dict()
        for inner_key in val_list:
            inner_dict[inner_key] = item[inner_key]

        my_dict[date_key] = inner_dict

    return my_dict


text:
package projectmanager.dada.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import projectmanager.dada.R;
import projectmanager.dada.adapter.ViewMyPublishTaskAdapter;
import projectmanager.dada.model.StatusType;
import projectmanager.dada.model.Task;
import projectmanager.dada.model.User;
import projectmanager.dada.pages.MyPublishTaskDetailActivity;
import projectmanager.dada.util.ApiManager;
import projectmanager.dada.util.DataManager;

/**
 * Created by tao on 2016/12/17.
 */

public class PublishedTaskFragment extends Fragment {
    private GetMyPublishTaskSetTask getMyPublishSetTask;
    private ListView myPublishListView;
    private View myPublishLinearLayout;
    private View progressView;
    private ArrayList<Task> myPublishTaskList;
    private ViewMyPublishTaskAdapter myPublishTaskAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_my_publish_task, container, false);
        myPublishListView = (ListView) view.findViewById(R.id.my_publish_task_list_view);
        progressView = view.findViewById(R.id.get_my_publish_task_progress);
        myPublishLinearLayout = view.findViewById(R.id.my_publish_total_linear_layout);
        return view;
    }

    @Override
    public void onResume(){
        super.onResume();
        myPublishTaskList = new ArrayList<>();
        tryGetMyPublishTasks();
        new UpdateUserProfile().execute();
    }

    /**
     * 执行从服务器获取数据的动作
     */
    private void tryGetMyPublishTasks(){
        showProgress(true);
        getMyPublishSetTask = new GetMyPublishTaskSetTask();
        getMyPublishSetTask.execute((Void) null);
    }

    /**
     * 在用户从服务器获取自己发布的任务的时候
     * @param show 设定进度框显示与否
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            myPublishLinearLayout.setVisibility(show ? View.GONE : View.VISIBLE);
            myPublishLinearLayout.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    myPublishLinearLayout.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            progressView.setVisibility(show ? View.VISIBLE : View.GONE);
            progressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    progressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            progressView.setVisibility(show ? View.VISIBLE : View.GONE);
            myPublishLinearLayout.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * 从服务器获取数据的线程
     */
    public class GetMyPublishTaskSetTask extends AsyncTask<Void, Void, Boolean> {
        private User nowLoginUser;
        GetMyPublishTaskSetTask(){
            nowLoginUser = DataManager.getInstance().getCurrentUser();
        }
        @Override
        protected void onPreExecute(){
            showProgress(true);
        }
        @Override
        protected Boolean doInBackground(Void... voids) {
            ArrayList<Task> acceptList = ApiManager.getInstance().handleGetPublishTasks(nowLoginUser.getUserId(),
                    0,10);
            if(acceptList == null) {
                myPublishTaskList = new ArrayList<>();
                return false;
            }else if(acceptList.isEmpty()){
                myPublishTaskList = new ArrayList<>();
                rearrangeTaskSort();
                return true;
            }else{
                myPublishTaskList = acceptList;
                rearrangeTaskSort();
                return true;
            }
        }
        @Override
        protected void onPostExecute(final Boolean success) {
            getMyPublishSetTask = null;
            showProgress(false);
            if (success == true) {
                myPublishTaskAdapter = new ViewMyPublishTaskAdapter(getActivity(),
                        R.layout.my_publish_task_view,myPublishTaskList);
                myPublishListView.setAdapter(myPublishTaskAdapter);
                myPublishListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                        Task clickTask = myPublishTaskList.get(position);
                        DataManager.getInstance().setSelectedMyPublishTask(clickTask);
                        Intent nextPage = new Intent(getActivity(),MyPublishTaskDetailActivity.class);
                        startActivity(nextPage);

                    }
                });
                myPublishTaskAdapter.notifyDataSetChanged();
            }
        }
        @Override
        protected void onCancelled() {
            getMyPublishSetTask = null;
            showProgress(false);
        }
    }

    public class UpdateUserProfile extends AsyncTask<Void, Void, Boolean>{
        private User newLoginUser;
        @Override
        protected Boolean doInBackground(Void... voids) {
            newLoginUser = ApiManager.getInstance().handleGetUserById
                    (DataManager.getInstance().getCurrentUser().getUserId());
            if(newLoginUser== null){
                return false;
            }else{
                return true;
            }
        }
        @Override
        protected void onPostExecute(final Boolean success) {
            if (success == true) {
                DataManager.getInstance().setCurrentUser(newLoginUser);
            }
        }
        @Override
        protected void onCancelled() { }
    }

    private void rearrangeTaskSort(){
        ArrayList<Task> confirmTasks = new ArrayList<>();
        ArrayList<Task> ongoingTasks = new ArrayList<>();
        ArrayList<Task> openTasks = new ArrayList<>();
        ArrayList<Task> finishTasks = new ArrayList<>();
        ArrayList<Task> cancelTask = new ArrayList<>();
        for(Task tempTask : myPublishTaskList){
            if(tempTask.getStatus() == StatusType.WAITCONFIRM.getCode()){
                confirmTasks.add(tempTask);
            }else if(tempTask.getStatus() == StatusType.GOINGON.getCode()){
                ongoingTasks.add(tempTask);
            }else if(tempTask.getStatus() == StatusType.OPEN.getCode()){
                openTasks.add(tempTask);
            }else if(tempTask.getStatus() == StatusType.FINISHED.getCode()){
                finishTasks.add(tempTask);
            }else{
                cancelTask.add(tempTask);
            }
        }
        ArrayList<Task> newList = new ArrayList<>();
        newList.addAll(confirmTasks);
        newList.addAll(ongoingTasks);
        newList.addAll(openTasks);
        newList.addAll(finishTasks);
        newList.addAll(cancelTask);
        myPublishTaskList = newList;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.pearson.entech.elasticsearch.search.facet.approx.date.external;

import java.io.IOException;

import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;

/**
 * A placeholder for use in facets which don't have any individual entries.
 * Follows the enum singleton pattern. Just implements a no-op toXContent() call.
 */
public enum NullEntry implements ToXContent {

    /**
     * The only instance of NullEntry you'll ever need.
     */
    INSTANCE;

    @Override
    public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
        return builder;
    }

}


text:
var Vue = require('vue');

import Greeter from './components/Greeter.vue';

new Vue({
    el: '#app',

    components: { Greeter },

    ready() {
        alert('Vue and Vueify all set to go!');
    }
});


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include "Common.hpp"
# include "String.hpp"

namespace s3d
{
	namespace detail
	{
		//////////////////////////////////////////////////////////////////////////////
		//
		//	Copyright (c) 2012 - present, Victor Zverovich
		//
		//	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.
		//
		//	--- Optional exception to the license ---
		//
		//	As an exception, if, as a result of your compiling your source code, portions
		//	of this Software are embedded into a machine-executable object form of such
		//	source code, you may redistribute such embedded portions in such object form
		//	without including the above copyright and permission notices.
		class IntFormatter
		{
		private:

			enum { BUFFER_SIZE = std::numeric_limits<uint64>::digits10 + 3 };

			mutable char32 buffer_[BUFFER_SIZE];

			char32* str_;

			char32* format_decimal(uint64 value) noexcept;

			void format_signed(int64 value) noexcept;

		public:

			SIV3D_NODISCARD_CXX20
			explicit IntFormatter(int32 value) noexcept;

			SIV3D_NODISCARD_CXX20
			explicit IntFormatter(int64 value) noexcept;

			SIV3D_NODISCARD_CXX20
			explicit IntFormatter(uint32 value) noexcept;

			SIV3D_NODISCARD_CXX20
			explicit IntFormatter(uint64 value) noexcept;

			std::size_t size() const noexcept
			{
				return buffer_ - str_ + BUFFER_SIZE - 1;
			}

			const char32* data() const  noexcept
			{
				return str_;
			}

			const char32* c_str() const noexcept
			{
				buffer_[BUFFER_SIZE - 1] = '\0';
				return str_;
			}

			String str() const
			{
				return String(str_, size());
			}
		};
		//
		//////////////////////////////////////////////////////////////////////////////
	}
}


text:
<?php

namespace spec\Chippin\SDK;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class InstigatorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Chippin\SDK\Instigator');
    }
}


text:
package org.eclipse.php.internal.ui;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.php.internal.core.project.PHPNature;

/**
 * This is a factory project class for the PHP Demo use -pd for gettingthis
 */
public class PhpDemoProject {

	private static final String SRC_FOLDER = "src/";	 //$NON-NLS-1$
	private static final String FILES_PATH = "/resources/phpdemo/"; 	 //$NON-NLS-1$
	private static final String TEST_PROJECT_NAME = "PHPDemo"; 	 //$NON-NLS-1$
	private static final String FILE_NAME1 = "01-Visibility1.php"; //$NON-NLS-1$
	private static final String FILE_NAME2 = "02-Visibility2.php"; //$NON-NLS-1$
	private static final String FILE_NAME3 = "03-html.php"; //$NON-NLS-1$
	private static final String FILE_NAME5 = "05-Inherit.php"; //$NON-NLS-1$
	private static final String FILE_NAME6 = "06-FunctionParameter.php"; //$NON-NLS-1$
	private static final String FILE_NAME7 = "07-ClassExtension.php"; //$NON-NLS-1$
	private static final String FILE_NAME8 = "08-MemberReference.php"; //$NON-NLS-1$
	private static final String FILE_NAME9 = "09-Including.php"; //$NON-NLS-1$
	private static final String FILE_NAME10 = "Employee.php"; //$NON-NLS-1$
	private static final String FILE_NAME11 = "Manager.php"; //$NON-NLS-1$
	private static final String FILE_NAME12 = "Person.php"; //$NON-NLS-1$
	private static final String SRC_FILE_NAME1 = "01-included.php"; //$NON-NLS-1$

	public PhpDemoProject() {
	}

	public static void run() {

		final IProject testProject = ResourcesPlugin.getWorkspace().getRoot()
				.getProject(TEST_PROJECT_NAME);

		if (testProject.exists()) {
			return;
		}
		try {
			// create Example project
			testProject.create(null);
			testProject.open(null);
			providePhpNatureToProject(testProject);

			final IFile file = createFile(testProject, FILES_PATH, FILE_NAME1);
			createFile(testProject, FILES_PATH, FILE_NAME2);
			createFile(testProject, FILES_PATH, FILE_NAME3);
			createFile(testProject, FILES_PATH, FILE_NAME5);
			createFile(testProject, FILES_PATH, FILE_NAME6);
			createFile(testProject, FILES_PATH, FILE_NAME7);
			createFile(testProject, FILES_PATH, FILE_NAME8);
			createFile(testProject, FILES_PATH, FILE_NAME9);
			createFile(testProject, FILES_PATH, FILE_NAME10);
			createFile(testProject, FILES_PATH, FILE_NAME11);
			createFile(testProject, FILES_PATH, FILE_NAME12);

			createFolder(testProject, FILES_PATH, SRC_FOLDER);
			createFile(testProject, FILES_PATH, SRC_FOLDER + SRC_FILE_NAME1);
		} catch (Exception e) {
			Logger.logException(e);
		}
	}

	private static IFile createFile(final IProject testProject,
			String filePath, String fileName) throws IOException, CoreException {
		URL demoFileURL = FileLocator.find(Platform.getBundle(PHPUiPlugin
				.getPluginId()), new Path(filePath + fileName), null);
		demoFileURL = FileLocator.resolve(demoFileURL);
		IPath p = testProject.getFullPath();
		p = p.append(fileName);
		final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(p);
		InputStream inputStream = (InputStream) demoFileURL.getContent();
		file.create(inputStream, true, null);
		return file;
	}

	private static IFolder createFolder(final IProject testProject,
			String filePath, String folderName) throws IOException,
			CoreException {
		URL demoFileURL = FileLocator.find(Platform.getBundle(PHPUiPlugin
				.getPluginId()), new Path(filePath + folderName), null);
		demoFileURL = FileLocator.resolve(demoFileURL);
		IPath p = testProject.getFullPath();
		p = p.append(folderName);
		final IFolder folder = ResourcesPlugin.getWorkspace().getRoot()
				.getFolder(p);
		folder.create(true, true, null);
		return folder;
	}

	// this method provides a PHP nature to the created project that is given
	private static void providePhpNatureToProject(IProject project)
			throws ExecutionException {
		try {
			IProjectDescription desc = null;

			// configure .project
			String[] natureIds = new String[] { PHPNature.ID };
			if (null != natureIds) {
				desc = project.getDescription();
				desc.setNatureIds(natureIds);
				project.setDescription(desc, null);
			}

		} catch (CoreException e) {
			Logger.logException(e);
		}
	}
}


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="yes" name="apple-mobile-web-app-capable">
  <meta name="google-site-verification" content="WL1ODKKvlWjqsK-5AQdM-JRO0BauJSFVj85HnmMU4cA" />
  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0;">
  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/poole.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/hyde.css">
  <link rel="stylesheet" href="{{ site.baseurl }}lib/imagebox/css/lightbox.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <script type="text/javascript" src="{{site.baseurl}}lib/jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="{{site.baseurl}}lib/imagebox/js/lightbox-plus-jquery.js"></script>

  <script type="text/javascript" src="{{site.baseurl}}lib/freezeframe.js">
      freezeframe_options = {
    	loading_background_color: "white",
    	animation_icon_position: "center center"
    }

  </script>

  <link rel="stylesheet" href="{{ site.baseurl }}lib/highlight/styles/monokai_sublime.css">
  <script src="{{ site.baseurl }}lib/highlight/highlight.pack.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.baseurl }}public/Icon-76@2x.png">
  <link rel="shortcut icon" href="{{ site.baseurl }}public/Icon-76.png">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
<!doctype html>

    <meta charset="UTF-8"/>
    <title>DU Arcade 2016</title>

    {{ #scripts }}

    {{ /scripts }}

    <link rel="stylesheet" href="css/main.css">

        bitDecay Games Presents


text:
@extends(main)

@args Album album

    @if(album.isNew()){
        Create new album
    } else {
        Edit album - @album.name
    }

<form action="@url(saveAlbum)" method="post">

        Name
        <input type="text" name="album.name" value="@album.name">

        <button class="btn">Submit</button>

</form>


text:
package com.matthewmitchell.nubitsj.core;

import java.util.List;

/**
 * Implementors can be connected to a {@link BlockChain} and have its methods called when various things
 * happen that modify the state of the chain, for example: new blocks being received, a re-org occurring, or the
 * best chain head changing.
 */
public interface BlockChainListener {
    /**
     * Called when a new block on the best chain is seen, after relevant transactions are extracted and sent to
     * us via either {@link #receiveFromBlock(Transaction, StoredBlock, com.matthewmitchell.nubitsj.core.BlockChain.NewBlockType, int)}
     * or {@link #notifyTransactionIsInBlock(Sha256Hash, StoredBlock, com.matthewmitchell.nubitsj.core.BlockChain.NewBlockType, int)}.
     * If this block is causing a re-organise to a new chain, this method is NOT called even though the block may be
     * the new best block: your reorganize implementation is expected to do whatever would normally be done do for a new
     * best block in this case.
     */
    void notifyNewBestBlock(StoredBlock block) throws VerificationException;

    /**
     * Called when starting or stopping a download of valid hashes.
     * @param isDownloading true if the hashes started to download. false if the download stopped.
     */
    void notifyHashDownload(boolean isDownloading);

    /**
     * Called by the {@link BlockChain} when the best chain (representing total work done) has changed. In this case,
     * we need to go through our transactions and find out if any have become invalid. It's possible for our balance
     * to go down in this case: money we thought we had can suddenly vanish if the rest of the network agrees it
     * should be so.

     *
     * The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last (i.e. newest blocks first).
     */
    void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks,
                    List<StoredBlock> newBlocks) throws VerificationException;

    /**
     * Returns true if the given transaction is interesting to the listener. If yes, then the transaction will
     * be provided via the receiveFromBlock method. This method is essentially an optimization that lets BlockChain
     * bypass verification of a blocks merkle tree if no listeners are interested, which can save time when processing
     * full blocks on mobile phones. It's likely the method will be removed in future and replaced with an alternative
     * mechanism that involves listeners providing all keys that are interesting.
     */
    boolean isTransactionRelevant(Transaction tx) throws ScriptException;

    /**
     *
Called by the {@link BlockChain} when we receive a new block that contains a relevant transaction.

     *
     *
A transaction may be received multiple times if is included into blocks in parallel chains. The blockType
     * parameter describes whether the containing block is on the main/best chain or whether it's on a presently
     * inactive side chain.

     *
     *
The relativityOffset parameter is an arbitrary number used to establish an ordering between transactions
     * within the same block. In the case where full blocks are being downloaded, it is simply the index of the
     * transaction within that block. When Bloom filtering is in use, we don't find out the exact offset into a block
     * that a transaction occurred at, so the relativity count is not reflective of anything in an absolute sense but
     * rather exists only to order the transaction relative to the others.

     */
    void receiveFromBlock(Transaction tx, StoredBlock block,
                          BlockChain.NewBlockType blockType,
                          int relativityOffset) throws VerificationException;

    /**
     *
Called by the {@link BlockChain} when we receive a new {@link FilteredBlock} that contains the given
     * transaction hash in its merkle tree.

     *
     *
A transaction may be received multiple times if is included into blocks in parallel chains. The blockType
     * parameter describes whether the containing block is on the main/best chain or whether it's on a presently
     * inactive side chain.

     *
     *
The relativityOffset parameter in this case is an arbitrary (meaningless) number, that is useful only when
     * compared to the relativity count of another transaction received inside the same block. It is used to establish
     * an ordering of transactions relative to one another.

     *
     *
This method should return false if the given tx hash isn't known about, e.g. because the the transaction was
     * a Bloom false positive. If it was known about and stored, it should return true. The caller may need to know
     * this to calculate the effective FP rate.

     *
     * @return whether the transaction is known about i.e. was considered relevant previously.
     */
    boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
                                       BlockChain.NewBlockType blockType,
                                       int relativityOffset) throws VerificationException;
}


text:
package org.apache.hyracks.storage.common.buffercache;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.replication.IIOReplicationManager;

/**
 * Implementation of an IBufferCache that counts the number of pins/unpins,
 * latches/unlatches, and file create/delete/open/close called on it. It
 * delegates the actual functionality to another IBufferCache set in the c'tor.
 * The counters are updated in a thread-safe fashion using AtomicLong.
 */
public class DebugBufferCache implements IBufferCache {

    // Actual BufferCache functionality is delegated to this bufferCache.
    private final IBufferCache bufferCache;
    private AtomicLong pinCount = new AtomicLong();
    private AtomicLong unpinCount = new AtomicLong();
    private AtomicLong readLatchCount = new AtomicLong();
    private AtomicLong readUnlatchCount = new AtomicLong();
    private AtomicLong writeLatchCount = new AtomicLong();
    private AtomicLong writeUnlatchCount = new AtomicLong();
    private AtomicLong createFileCount = new AtomicLong();
    private AtomicLong deleteFileCount = new AtomicLong();
    private AtomicLong openFileCount = new AtomicLong();
    private AtomicLong closeFileCount = new AtomicLong();

    public DebugBufferCache(IBufferCache bufferCache) {
        this.bufferCache = bufferCache;
        resetCounters();
    }

    @Override
    public void createFile(FileReference fileRef) throws HyracksDataException {
        bufferCache.createFile(fileRef);
        createFileCount.addAndGet(1);
    }

    @Override
    public void openFile(int fileId) throws HyracksDataException {
        bufferCache.openFile(fileId);
        openFileCount.addAndGet(1);
    }

    @Override
    public void closeFile(int fileId) throws HyracksDataException {
        bufferCache.closeFile(fileId);
        closeFileCount.addAndGet(1);
    }

    @Override
    public void deleteFile(int fileId, boolean flushDirtyPages) throws HyracksDataException {
        bufferCache.deleteFile(fileId, flushDirtyPages);
        deleteFileCount.addAndGet(1);
    }

    @Override
    public ICachedPage tryPin(long dpid) throws HyracksDataException {
        return bufferCache.tryPin(dpid);
    }

    @Override
    public ICachedPage pin(long dpid, boolean newPage) throws HyracksDataException {
        ICachedPage page = bufferCache.pin(dpid, newPage);
        pinCount.addAndGet(1);
        return page;
    }

    @Override
    public void unpin(ICachedPage page) throws HyracksDataException {
        bufferCache.unpin(page);
        unpinCount.addAndGet(1);
    }

    @Override
    public int getPageSize() {
        return bufferCache.getPageSize();
    }

    @Override
    public int getNumPages() {
        return bufferCache.getNumPages();
    }

    @Override
    public void close() throws HyracksDataException {
        bufferCache.close();
    }

    public void resetCounters() {
        pinCount.set(0);
        unpinCount.set(0);
        readLatchCount.set(0);
        readUnlatchCount.set(0);
        writeLatchCount.set(0);
        writeUnlatchCount.set(0);
        createFileCount.set(0);
        deleteFileCount.set(0);
        openFileCount.set(0);
        closeFileCount.set(0);
    }

    public long getPinCount() {
        return pinCount.get();
    }

    public long getUnpinCount() {
        return unpinCount.get();
    }

    public long getReadLatchCount() {
        return readLatchCount.get();
    }

    public long getReadUnlatchCount() {
        return readUnlatchCount.get();
    }

    public long getWriteLatchCount() {
        return writeLatchCount.get();
    }

    public long getWriteUnlatchCount() {
        return writeUnlatchCount.get();
    }

    public long getCreateFileCount() {
        return createFileCount.get();
    }

    public long getDeleteFileCount() {
        return deleteFileCount.get();
    }

    public long getOpenFileCount() {
        return openFileCount.get();
    }

    public long getCloseFileCount() {
        return closeFileCount.get();
    }

    @Override
    public void flushDirtyPage(ICachedPage page) throws HyracksDataException {
        bufferCache.flushDirtyPage(page);
    }

    @Override
    public void force(int fileId, boolean metadata) throws HyracksDataException {
        bufferCache.force(fileId, metadata);
    }

    @Override
    public int createMemFile() throws HyracksDataException {
        return bufferCache.createMemFile();
    }

    @Override
    public void deleteMemFile(int fileId) throws HyracksDataException {
        bufferCache.deleteMemFile(fileId);
    }

    @Override
    public int getNumPagesOfFile(int fileId) throws HyracksDataException {
        return bufferCache.getNumPagesOfFile(fileId);
    }

    @Override
    public void adviseWontNeed(ICachedPage page) {
        bufferCache.adviseWontNeed(page);
    }

    @Override
    public ICachedPage confiscatePage(long dpid) throws HyracksDataException {
        return bufferCache.confiscatePage(dpid);
    }

    @Override
    public void returnPage(ICachedPage page) {
        bufferCache.returnPage(page);
    }

    @Override
    public IFIFOPageQueue createFIFOQueue() {
        return bufferCache.createFIFOQueue();
    }

    @Override
    public void finishQueue() {
        bufferCache.finishQueue();
    }

    @Override
    public void copyPage(ICachedPage src, ICachedPage dst) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setPageDiskId(ICachedPage page, long dpid) {
        // TODO Auto-generated method stub

    }

    @Override
    public void returnPage(ICachedPage page, boolean reinsert) {
        // TODO Auto-generated method stub

    }

    @Override
    public int getFileReferenceCount(int fileId) {
        return bufferCache.getFileReferenceCount(fileId);
    }

    @Override
    public boolean isReplicationEnabled() {
        return false;
    }

    @Override
    public IIOReplicationManager getIOReplicationManager() {
        return null;
    }

    @Override
    public void purgeHandle(int fileId) throws HyracksDataException {
        bufferCache.purgeHandle(fileId);
    }
}


text:
We 💛 contributions! The rules for contributing to this project are few:

1. Don't be a jerk
1. Ask nicely
1. Search issues before opening a new one
1. Lint and run tests locally before submitting a PR
1. Adhere to the code style the project has chosen


text:
#ifndef __VCG_DECIMATION_TRICOLLAPSE
#define __VCG_DECIMATION_TRICOLLAPSE

#include<vcg/complex/algorithms/edge_collapse.h>
#include<vcg/simplex/face/pos.h>
#include<vcg/complex/algorithms/local_optimization.h>
#include<vcg/complex/algorithms/update/topology.h>

namespace vcg{
namespace tri{

/** \addtogroup trimesh */
/*@{*/
/// This Class is specialization of LocalModification for the edge collapse.
/// It wraps the atomic operation EdgeCollapse to be used in a optimizatin routine.
/// Note that it has knowledge of the heap of the class LocalOptimization because
/// it is responsible of updating it after a collapse has been performed;
/// This is the base class of all the specialized collapse classes like for example Quadric Edge Collapse.
/// Each derived class

template<class TriMeshType, class VertexPair, class MYTYPE>
class TriEdgeCollapse: public LocalOptimization<TriMeshType>::LocModType
{
public:
 /// static data to gather statistical information about the reasons of collapse failures
  class FailStat {
  public:
	static int &Volume()           {static int vol=0; return vol;}
	static int &LinkConditionFace(){static int lkf=0; return lkf;}
	static int &LinkConditionEdge(){static int lke=0; return lke;}
	static int &LinkConditionVert(){static int lkv=0; return lkv;}
	static int &OutOfDate()        {static int ofd=0; return ofd;}
	static int &Border()           {static int bor=0; return bor;}
  static void Init()
  {
   Volume()           =0;
   LinkConditionFace()=0;
   LinkConditionEdge()=0;
   LinkConditionVert()=0;
   OutOfDate()        =0;
   Border()           =0;
  }
};
protected:
  typedef	typename TriMeshType::FaceType FaceType;
  typedef	typename TriMeshType::FaceType::VertexType VertexType;
//	typedef	typename VertexType::EdgeType EdgeType;
  typedef	typename FaceType::VertexType::CoordType CoordType;
  typedef	typename TriMeshType::VertexType::ScalarType ScalarType;
  typedef typename LocalOptimization<TriMeshType>::HeapElem HeapElem;
	typedef typename LocalOptimization<TriMeshType>::HeapType HeapType;

  TriMeshType *mt;
	///the pair to collapse
  VertexPair pos;

	///mark for up_dating
	static int& GlobalMark(){ static int im=0; return im;}

	///mark for up_dating
	int localMark;

	/// priority in the heap
	ScalarType _priority;

	public:
	/// Default Constructor
	inline	TriEdgeCollapse()
			{}
	///Constructor with postype
   inline TriEdgeCollapse(const VertexPair &p, int mark, BaseParameterClass *pp)
			{
				localMark = mark;
				pos=p;
        _priority = ComputePriority(pp);
			}

		~TriEdgeCollapse()
			{}

private:

public:

  inline ScalarType ComputePriority(BaseParameterClass *)
  {
		_priority = Distance(pos.V(0)->cP(),pos.V(1)->cP());
    return _priority;
  }

  virtual const char *Info(TriMeshType &m) {
		mt = &m;
    static char buf[60];
      sprintf(buf,"%i -> %i %g\n", int(pos.V(0)-&m.vert[0]), int(pos.V(1)-&m.vert[0]),-_priority);
   return buf;
  }

  inline void Execute(TriMeshType &m, BaseParameterClass *)
  {
    CoordType MidPoint=(pos.V(0)->P()+pos.V(1)->P())/2.0;
    EdgeCollapser<TriMeshType,VertexPair>::Do(m, pos, MidPoint);
  }

  static bool IsSymmetric(BaseParameterClass *) { return true;}

  // This function is called after an action to re-add in the heap elements whose priority could have been changed.
  // in the plain case we just put again in the heap all the edges around the vertex resulting from the previous collapse: v[1].
  // if the collapse is not symmetric you should add also backward edges (because v0->v1 collapse could be different from v1->v0)

  inline  void UpdateHeap(HeapType & h_ret, BaseParameterClass *pp)
  {
    GlobalMark()++;
    VertexType *v[2];
    v[0]= pos.V(0);v[1]=pos.V(1);
    v[1]->IMark() = GlobalMark();

    // First loop around the remaining vertex to unmark visited flags
    vcg::face::VFIterator<FaceType> vfi(v[1]);
    while (!vfi.End()){
      vfi.V1()->ClearV();
      vfi.V2()->ClearV();
      ++vfi;
    }

    // Second Loop: add all the outgoing edges around v[1]
    // for each face add the two edges outgoing from v[1] and not visited.
    vfi = face::VFIterator<FaceType>(v[1]);
    while (!vfi.End())
    {
      assert(!vfi.F()->IsD());
      if( !(vfi.V1()->IsV()) && (vfi.V1()->IsRW()))
      {
        vfi.V1()->SetV();
        h_ret.push_back(HeapElem(new MYTYPE(VertexPair( vfi.V(),vfi.V1() ),GlobalMark(),pp)));
        std::push_heap(h_ret.begin(),h_ret.end());
        if(! this->IsSymmetric(pp)){
          h_ret.push_back(HeapElem(new MYTYPE(VertexPair( vfi.V1(),vfi.V()),GlobalMark(),pp)));
          std::push_heap(h_ret.begin(),h_ret.end());
        }
      }
      if(  !(vfi.V2()->IsV()) && (vfi.V2()->IsRW()))
      {
        vfi.V2()->SetV();
        h_ret.push_back(HeapElem(new MYTYPE(VertexPair(vfi.F()->V(vfi.I()),vfi.F()->V2(vfi.I())),GlobalMark(),pp)));
        std::push_heap(h_ret.begin(),h_ret.end());
        if(! this->IsSymmetric(pp)){
          h_ret.push_back(HeapElem(new MYTYPE(VertexPair (vfi.F()->V1(vfi.I()),vfi.F()->V(vfi.I())),GlobalMark(),pp)));
          std::push_heap(h_ret.begin(),h_ret.end());
        }
      }
      //        if(vfi.V1()->IsRW() && vfi.V2()->IsRW() )
      //        {
      //          h_ret.push_back(HeapElem(new MYTYPE(EdgeType(vfi.V1(),vfi.V2()),this->GlobalMark())));
      //          std::push_heap(h_ret.begin(),h_ret.end());
      //          if(IsSymmetric()){
      //            h_ret.push_back(HeapElem(new MYTYPE(EdgeType(vfi.V2(),vfi.V1()), this->GlobalMark())));
      //            std::push_heap(h_ret.begin(),h_ret.end());
      //          }
      //        }
      ++vfi;
    } // end while
  }

  ModifierType IsOfType(){ return TriEdgeCollapseOp;}

  inline bool IsFeasible(BaseParameterClass *){
    return EdgeCollapser<TriMeshType,VertexPair>::LinkConditions(pos);
	}

  inline bool IsUpToDate() const
  {
      VertexType *v0=pos.cV(0);
      VertexType *v1=pos.cV(1);
			if( v0->IsD() || v1->IsD() ||
				 localMark < v0->IMark()  ||
		  	 localMark < v1->IMark()   )
			{
				++FailStat::OutOfDate();
				return false;
      }
        return true;
	}

	virtual ScalarType Priority() const {
	return _priority;
  }

  static void Init(TriMeshType &m, HeapType &h_ret, BaseParameterClass *pp)
  {
    vcg::tri::UpdateTopology<TriMeshType>::VertexFace(m);
    h_ret.clear();
    typename TriMeshType::FaceIterator fi;
    for(fi = m.face.begin(); fi != m.face.end();++fi)
    if(!(*fi).IsD()){
       for (int j=0;j<3;j++)
      {
        VertexPair p((*fi).V0(j), (*fi).V1(j));
        p.Sort();
        h_ret.push_back(HeapElem(new MYTYPE(p, IMark(m),pp)));
        //printf("Inserting in heap coll %3i ->%3i %f\n",p.V()-&m.vert[0],p.VFlip()-&m.vert[0],h_ret.back().locModPtr->Priority());
      }
    }
	}

};
}//end namespace tri
}//end namespace vcg

#endif


text:
<?php

namespace Zend\Expressive\Tooling\Module;

use Symfony\Component\Console\Command\Command;
use Zend\ComponentInstaller\Injector\ConfigAggregatorInjector;
use Zend\ComponentInstaller\Injector\InjectorInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use ZF\ComposerAutoloading\Command\Enable;

class RegisterCommand extends Command
{
    const HELP = <<< 'EOT'
Register an existing middleware module with the application, by:

- Ensuring a PSR-4 autoloader entry is present in composer.json, and the
  autoloading rules have been generated.
- Ensuring the ConfigProvider class for the module is registered with the
  application configuration.
EOT;

    const HELP_ARG_MODULE = 'The module to register with the application';

    /**
     * Configure command.
     */
    protected function configure()
    {
        $this->setDescription('Register a middleware module with the application');
        $this->setHelp(self::HELP);
        CommandCommonOptions::addDefaultOptionsAndArguments($this);
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $module = $input->getArgument('module');
        $composer = $input->getOption('composer') ?: 'composer';
        $modulesPath = CommandCommonOptions::getModulesPath($input);

        $injector = new ConfigAggregatorInjector(getcwd());
        $configProvider = sprintf('%s\ConfigProvider', $module);
        if (! $injector->isRegistered($configProvider)) {
            $injector->inject(
                $configProvider,
                InjectorInterface::TYPE_CONFIG_PROVIDER
            );
        }

        $enable = new Enable(getcwd(), $modulesPath, $composer);
        $enable->setMoveModuleClass(false);
        $enable->process($module);

        $output->writeln(sprintf('Registered autoloading rules and added configuration entry for module %s', $module));
        return 0;
    }
}


text:
import {
  Constructor,
  MetaClass,
  targetStore,
  TypeMetadata,
  ExcludeMetadata,
  ExcludeMetadataArgs,
  PropMetadata,
  RelationMetadata,
  TypeDefinition, // leave for angular AOT compiler.
  PropMetadataArgs, // leave for angular AOT compiler.
  RelationMetadataArgs // leave for angular AOT compiler.
} from '@tdm/core/tdm';

targetStore.on.processType((target: Constructor<any>) => {
  const meta = targetStore.getTargetMeta(target);
  meta.getValues(RelationMetadata).forEach(relation => {
    // Its possible to set @Relation() without @Prop(), so make sure to create one if not set by the user.
    const prop = meta.getCreateProp(relation.decoratorInfo);
    prop.setRelationship(relation);

    // if the fk is a different key, attach a reference to the foreign key PropMetadata (and create 1 if not there)
    if (relation.name !== relation.foreignKey) {
      meta.getCreateProp(relation.foreignKey).foreignKeyOf = prop;
    }
  });
});

/**
 * @propertyDecorator instance
 * @param def
 */
export const Prop = MetaClass.decorator(PropMetadata, true);

/** @internal */
export let exclude: any = {};
exclude = MetaClass.decorator(ExcludeMetadata, true, 'classPropMethod'); // for Angular AOT

/**
 * @propertyDecorator instance
 */
export function Exclude(
  metaArgs?: ExcludeMetadataArgs
): (
  target: Object | Function,
  key?: TdmPropertyKey,
  desc?: PropertyDescriptor
) => any {
  return exclude(metaArgs) as any;
}

/**
 * @propertyDecorator instance
 * @param def
 */
export const Relation = MetaClass.decorator(RelationMetadata, true);

/**
 * @propertyDecorator instance
 * @param def
 */
export const Type = MetaClass.decorator(TypeMetadata);

/**
 * @propertyDecorator instance
 */
export function Identity(): Function {
  return (target: Object, key: TdmPropertyKey) => {
    targetStore.getTargetMeta(<any>target.constructor).model().identity = key;
  };
}


text:
// MIT © 2017 azu
import { Dictionary } from "./Dictionary";

const sanitizeFileName = require("sanitize-filename");

const escapeName = (fileName: string) => {
    return fileName.replace(/\s/g, "_").replace(/^\./, "_");
};

/**
 * Create fileName-safe slug string from dictionary
 * @param {Dictionary} dictionary
 * @returns {string}
 */
export function createSlugFromDictionary(dictionary: Dictionary): string {
    return sanitizeFileName(escapeName(dictionary.expected.value));
}


text:
{%block header %}
{%endblock%}

{%block body %}
{%endblock %}

{%block footer %}
{%endblock %}


text:
package org.apache.catalina.authenticator;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Realm;
import org.apache.catalina.Session;
import org.apache.catalina.SessionEvent;
import org.apache.catalina.SessionListener;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.LifecycleSupport;
import org.apache.catalina.util.StringManager;
import org.apache.catalina.valves.ValveBase;

/**
 * A Valve that supports a "single sign on" user experience,
 * where the security identity of a user who successfully authenticates to one
 * web application is propogated to other web applications in the same
 * security domain.  For successful use, the following requirements must
 * be met:
 *

 *
This Valve must be configured on the Container that represents a
 *     virtual host (typically an implementation of Host).

 *
The Realm that contains the shared user and role
 *     information must be configured on the same Container (or a higher
 *     one), and not overridden at the web application level.

 *
The web applications themselves must use one of the standard
 *     Authenticators found in the
 *     org.apache.catalina.authenticator package.

 *

 *
 * @author Craig R. McClanahan
 *
 */

public class SingleSignOn
    extends ValveBase
    implements Lifecycle, SessionListener {

    // ----------------------------------------------------- Instance Variables

    /**
     * The cache of SingleSignOnEntry instances for authenticated Principals,
     * keyed by the cookie value that is used to select them.
     */
    protected Map<String,SingleSignOnEntry> cache =
        new HashMap<String,SingleSignOnEntry>();

    /**
     * Descriptive information about this Valve implementation.
     */
    protected static String info =
        "org.apache.catalina.authenticator.SingleSignOn";

    /**
     * The lifecycle event support for this component.
     */
    protected LifecycleSupport lifecycle = new LifecycleSupport(this);

    /**
     * Indicates whether this valve should require a downstream Authenticator to
     * reauthenticate each request, or if it itself can bind a UserPrincipal
     * and AuthType object to the request.
     */
    private boolean requireReauthentication = false;

    /**
     * The cache of single sign on identifiers, keyed by the Session that is
     * associated with them.
     */
    protected Map<Session,String> reverse = new HashMap<Session,String>();

    /**
     * The string manager for this package.
     */
    protected final static StringManager sm =
        StringManager.getManager(Constants.Package);

    /**
     * Component started flag.
     */
    protected boolean started = false;

    /**
     * Optional SSO cookie domain.
     */
    private String cookieDomain;

    // ------------------------------------------------------------- Properties

    /**
     * Returns the optional cookie domain.
     * May return null.
     *
     * @return The cookie domain
     */
    public String getCookieDomain() {
        return cookieDomain;
    }
    /**
     * Sets the domain to be used for sso cookies.
     *
     * @param cookieDomain cookie domain name
     */
    public void setCookieDomain(String cookieDomain) {
        if (cookieDomain != null && cookieDomain.trim().length() == 0) {
            cookieDomain = null;
        }
        this.cookieDomain = cookieDomain;
    }

    /**
     * Gets whether each request needs to be reauthenticated (by an
     * Authenticator downstream in the pipeline) to the security
     * Realm, or if this Valve can itself bind security info
     * to the request based on the presence of a valid SSO entry without
     * rechecking with the Realm</code..
     *
     * @return  true if it is required that a downstream
     *          Authenticator reauthenticate each request before calls to
     *          HttpServletRequest.setUserPrincipal()
     *          and HttpServletRequest.setAuthType() are made;
     *          false if the Valve can itself make
     *          those calls relying on the presence of a valid SingleSignOn
     *          entry associated with the request.
     *
     * @see #setRequireReauthentication
     */
    public boolean getRequireReauthentication()
    {
        return requireReauthentication;
    }

    /**
     * Sets whether each request needs to be reauthenticated (by an
     * Authenticator downstream in the pipeline) to the security
     * Realm, or if this Valve can itself bind security info
     * to the request, based on the presence of a valid SSO entry, without
     * rechecking with the Realm</code.
     *

     * If this property is false (the default), this
     * Valve will bind a UserPrincipal and AuthType to the request
     * if a valid SSO entry is associated with the request.  It will not notify
     * the security Realm of the incoming request.
     *

     * This property should be set to true if the overall server
     * configuration requires that the Realm reauthenticate each
     * request thread.  An example of such a configuration would be one where
     * the Realm implementation provides security for both a
     * web tier and an associated EJB tier, and needs to set security
     * credentials on each request thread in order to support EJB access.
     *

     * If this property is set to true, this Valve will set flags
     * on the request notifying the downstream Authenticator that the request
     * is associated with an SSO session.  The Authenticator will then call its
     * {@link AuthenticatorBase#reauthenticateFromSSO reauthenticateFromSSO}
     * method to attempt to reauthenticate the request to the
     * Realm, using any credentials that were cached with this
     * Valve.
     *

     * The default value of this property is false, in order
     * to maintain backward compatibility with previous versions of Tomcat.
     *
     * @param required  true if it is required that a downstream
     *                  Authenticator reauthenticate each request before calls
     *                  to  HttpServletRequest.setUserPrincipal()
     *                  and HttpServletRequest.setAuthType() are
     *                  made; false if the Valve can
     *                  itself make those calls relying on the presence of a
     *                  valid SingleSignOn entry associated with the request.
     *
     * @see AuthenticatorBase#reauthenticateFromSSO
     */
    public void setRequireReauthentication(boolean required)
    {
        this.requireReauthentication = required;
    }

    // ------------------------------------------------------ Lifecycle Methods

    /**
     * Add a lifecycle event listener to this component.
     *
     * @param listener The listener to add
     */
    public void addLifecycleListener(LifecycleListener listener) {

        lifecycle.addLifecycleListener(listener);

    }

    /**
     * Get the lifecycle listeners associated with this lifecycle. If this
     * Lifecycle has no listeners registered, a zero-length array is returned.
     */
    public LifecycleListener[] findLifecycleListeners() {

        return lifecycle.findLifecycleListeners();

    }

    /**
     * Remove a lifecycle event listener from this component.
     *
     * @param listener The listener to remove
     */
    public void removeLifecycleListener(LifecycleListener listener) {

        lifecycle.removeLifecycleListener(listener);

    }

    /**
     * Prepare for the beginning of active use of the public methods of this
     * component.  This method should be called after configure(),
     * and before any of the public methods of the component are utilized.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    public void start() throws LifecycleException {

        // Validate and update our current component state
        if (started)
            throw new LifecycleException
                (sm.getString("authenticator.alreadyStarted"));
        lifecycle.fireLifecycleEvent(START_EVENT, null);
        started = true;

    }

    /**
     * Gracefully terminate the active use of the public methods of this
     * component.  This method should be the last one called on a given
     * instance of this component.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that needs to be reported
     */
    public void stop() throws LifecycleException {

        // Validate and update our current component state
        if (!started)
            throw new LifecycleException
                (sm.getString("authenticator.notStarted"));
        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        started = false;

    }

    // ------------------------------------------------ SessionListener Methods

    /**
     * Acknowledge the occurrence of the specified event.
     *
     * @param event SessionEvent that has occurred
     */
    public void sessionEvent(SessionEvent event) {

        // We only care about session destroyed events
        if (!Session.SESSION_DESTROYED_EVENT.equals(event.getType())
                && (!Session.SESSION_PASSIVATED_EVENT.equals(event.getType())))
            return;

        // Look up the single session id associated with this session (if any)
        Session session = event.getSession();
        if (containerLog.isDebugEnabled())
            containerLog.debug("Process session destroyed on " + session);

        String ssoId = null;
        synchronized (reverse) {
            ssoId = (String) reverse.get(session);
        }
        if (ssoId == null)
            return;

        // Was the session destroyed as the result of a timeout?
        // If so, we'll just remove the expired session from the
        // SSO.  If the session was logged out, we'll log out
        // of all session associated with the SSO.
        if (((session.getMaxInactiveInterval() > 0)
            && (System.currentTimeMillis() - session.getLastAccessedTimeInternal() >=
                session.getMaxInactiveInterval() * 1000))
            || (Session.SESSION_PASSIVATED_EVENT.equals(event.getType()))) {
            removeSession(ssoId, session);
        } else {
            // The session was logged out.
            // Deregister this single session id, invalidating
            // associated sessions
            deregister(ssoId);
        }

    }

    // ---------------------------------------------------------- Valve Methods

    /**
     * Return descriptive information about this Valve implementation.
     */
    public String getInfo() {

        return (info);

    }

    /**
     * Perform single-sign-on support processing for this request.
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void invoke(Request request, Response response)
        throws IOException, ServletException {

        request.removeNote(Constants.REQ_SSOID_NOTE);

        // Has a valid user already been authenticated?
        if (containerLog.isDebugEnabled())
            containerLog.debug("Process request for '" + request.getRequestURI() + "'");
        if (request.getUserPrincipal() != null) {
            if (containerLog.isDebugEnabled())
                containerLog.debug(" Principal '" + request.getUserPrincipal().getName() +
                    "' has already been authenticated");
            getNext().invoke(request, response);
            return;
        }

        // Check for the single sign on cookie
        if (containerLog.isDebugEnabled())
            containerLog.debug(" Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = request.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }
        if (cookie == null) {
            if (containerLog.isDebugEnabled())
                containerLog.debug(" SSO cookie is not present");
            getNext().invoke(request, response);
            return;
        }

        // Look up the cached Principal associated with this cookie value
        if (containerLog.isDebugEnabled())
            containerLog.debug(" Checking for cached principal for " + cookie.getValue());
        SingleSignOnEntry entry = lookup(cookie.getValue());
        if (entry != null) {
            if (containerLog.isDebugEnabled())
                containerLog.debug(" Found cached principal '" +
                    (entry.getPrincipal() != null ? entry.getPrincipal().getName() : "") + "' with auth type '" +
                    entry.getAuthType() + "'");
            request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
            // Only set security elements if reauthentication is not required
            if (!getRequireReauthentication()) {
                request.setAuthType(entry.getAuthType());
                request.setUserPrincipal(entry.getPrincipal());
            }
        } else {
            if (containerLog.isDebugEnabled())
                containerLog.debug(" No cached principal found, erasing SSO cookie");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }

        // Invoke the next Valve in our pipeline
        getNext().invoke(request, response);

    }

    // --------------------------------------------------------- Public Methods

    /**
     * Return a String rendering of this object.
     */
    public String toString() {

        StringBuffer sb = new StringBuffer("SingleSignOn[");
        if (container == null )
            sb.append("Container is null");
        else
            sb.append(container.getName());
        sb.append("]");
        return (sb.toString());

    }

    // ------------------------------------------------------ Protected Methods

    /**
     * Associate the specified single sign on identifier with the
     * specified Session.
     *
     * @param ssoId Single sign on identifier
     * @param session Session to be associated
     */
    protected void associate(String ssoId, Session session) {

        if (containerLog.isDebugEnabled())
            containerLog.debug("Associate sso id " + ssoId + " with session " + session);

        SingleSignOnEntry sso = lookup(ssoId);
        if (sso != null)
            sso.addSession(this, session);
        synchronized (reverse) {
            reverse.put(session, ssoId);
        }

    }

    /**
     * Deregister the specified session.  If it is the last session,
     * then also get rid of the single sign on identifier
     *
     * @param ssoId Single sign on identifier
     * @param session Session to be deregistered
     */
    protected void deregister(String ssoId, Session session) {

        synchronized (reverse) {
            reverse.remove(session);
        }

        SingleSignOnEntry sso = lookup(ssoId);
        if ( sso == null )
            return;

        sso.removeSession( session );

        // see if we are the last session, if so blow away ssoId
        Session sessions[] = sso.findSessions();
        if ( sessions == null || sessions.length == 0 ) {
            synchronized (cache) {
                sso = (SingleSignOnEntry) cache.remove(ssoId);
            }
        }

    }

    /**
     * Deregister the specified single sign on identifier, and invalidate
     * any associated sessions.
     *
     * @param ssoId Single sign on identifier to deregister
     */
    protected void deregister(String ssoId) {

        if (containerLog.isDebugEnabled())
            containerLog.debug("Deregistering sso id '" + ssoId + "'");

        // Look up and remove the corresponding SingleSignOnEntry
        SingleSignOnEntry sso = null;
        synchronized (cache) {
            sso = (SingleSignOnEntry) cache.remove(ssoId);
        }

        if (sso == null)
            return;

        // Expire any associated sessions
        Session sessions[] = sso.findSessions();
        for (int i = 0; i < sessions.length; i++) {
            if (containerLog.isTraceEnabled())
                containerLog.trace(" Invalidating session " + sessions[i]);
            // Remove from reverse cache first to avoid recursion
            synchronized (reverse) {
                reverse.remove(sessions[i]);
            }
            // Invalidate this session
            sessions[i].expire();
        }

        // NOTE:  Clients may still possess the old single sign on cookie,
        // but it will be removed on the next request since it is no longer
        // in the cache

    }

    /**
     * Attempts reauthentication to the given Realm using
     * the credentials associated with the single sign-on session
     * identified by argument ssoId.
     *

     * If reauthentication is successful, the Principal and
     * authorization type associated with the SSO session will be bound
     * to the given Request object via calls to
     * {@link Request#setAuthType Request.setAuthType()} and
     * {@link Request#setUserPrincipal Request.setUserPrincipal()}
     *

     *
     * @param ssoId     identifier of SingleSignOn session with which the
     *                  caller is associated
     * @param realm     Realm implementation against which the caller is to
     *                  be authenticated
     * @param request   the request that needs to be authenticated
     *
     * @return  true if reauthentication was successful,
     *          false otherwise.
     */
    protected boolean reauthenticate(String ssoId, Realm realm,
                                     Request request) {

        if (ssoId == null || realm == null)
            return false;

        boolean reauthenticated = false;

        SingleSignOnEntry entry = lookup(ssoId);
        if (entry != null && entry.getCanReauthenticate()) {

            String username = entry.getUsername();
            if (username != null) {
                Principal reauthPrincipal =
                        realm.authenticate(username, entry.getPassword());
                if (reauthPrincipal != null) {
                    reauthenticated = true;
                    // Bind the authorization credentials to the request
                    request.setAuthType(entry.getAuthType());
                    request.setUserPrincipal(reauthPrincipal);
                }
            }
        }

        return reauthenticated;
    }

    /**
     * Register the specified Principal as being associated with the specified
     * value for the single sign on identifier.
     *
     * @param ssoId Single sign on identifier to register
     * @param principal Associated user principal that is identified
     * @param authType Authentication type used to authenticate this
     *  user principal
     * @param username Username used to authenticate this user
     * @param password Password used to authenticate this user
     */
    protected void register(String ssoId, Principal principal, String authType,
                  String username, String password) {

        if (containerLog.isDebugEnabled())
            containerLog.debug("Registering sso id '" + ssoId + "' for user '" +
                (principal != null ? principal.getName() : "") + "' with auth type '" + authType + "'");

        synchronized (cache) {
            cache.put(ssoId, new SingleSignOnEntry(principal, authType,
                                                   username, password));
        }

    }

    /**
     * Updates any SingleSignOnEntry found under key
     * ssoId with the given authentication data.
     *

     * The purpose of this method is to allow an SSO entry that was
     * established without a username/password combination (i.e. established
     * following DIGEST or CLIENT_CERT authentication) to be updated with
     * a username and password if one becomes available through a subsequent
     * BASIC or FORM authentication.  The SSO entry will then be usable for
     * reauthentication.
     *

     * NOTE: Only updates the SSO entry if a call to
     * SingleSignOnEntry.getCanReauthenticate() returns
     * false; otherwise, it is assumed that the SSO entry already
     * has sufficient information to allow reauthentication and that no update
     * is needed.
     *
     * @param ssoId     identifier of Single sign to be updated
     * @param principal the Principal returned by the latest
     *                  call to Realm.authenticate.
     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT,
     *                  DIGEST or FORM)
     * @param username  the username (if any) used for the authentication
     * @param password  the password (if any) used for the authentication
     */
    protected void update(String ssoId, Principal principal, String authType,
                          String username, String password) {

        SingleSignOnEntry sso = lookup(ssoId);
        if (sso != null && !sso.getCanReauthenticate()) {
            if (containerLog.isDebugEnabled())
                containerLog.debug("Update sso id " + ssoId + " to auth type " + authType);

            synchronized(sso) {
                sso.updateCredentials(principal, authType, username, password);
            }

        }
    }

    /**
     * Look up and return the cached SingleSignOn entry associated with this
     * sso id value, if there is one; otherwise return null.
     *
     * @param ssoId Single sign on identifier to look up
     */
    protected SingleSignOnEntry lookup(String ssoId) {

        synchronized (cache) {
            return ((SingleSignOnEntry) cache.get(ssoId));
        }

    }

    /**
     * Remove a single Session from a SingleSignOn.  Called when
     * a session is timed out and no longer active.
     *
     * @param ssoId Single sign on identifier from which to remove the session.
     * @param session the session to be removed.
     */
    protected void removeSession(String ssoId, Session session) {

        if (containerLog.isDebugEnabled())
            containerLog.debug("Removing session " + session.toString() + " from sso id " +
                ssoId );

        // Get a reference to the SingleSignOn
        SingleSignOnEntry entry = lookup(ssoId);
        if (entry == null)
            return;

        // Remove the inactive session from SingleSignOnEntry
        entry.removeSession(session);

        // Remove the inactive session from the 'reverse' Map.
        synchronized(reverse) {
            reverse.remove(session);
        }

        // If there are not sessions left in the SingleSignOnEntry,
        // deregister the entry.
        if (entry.findSessions().length == 0) {
            deregister(ssoId);
        }
    }

}


text:
using gmml::Structure;

using namespace v8;

namespace gems {
namespace {

Structure *extract_structure(Handle<Object> object) {
    return StructureModule::extract_ptr(object->Get(String::New("structure")));
}

int extract_index(Handle<Object> object) {
    return object->Get(String::New("index"))->ToInteger()->Value();
}

Handle<Value> get_size(Local<String> property, const AccessorInfo& info) {
    Local<Object> self = info.This();

    Structure *structure = extract_structure(self);

    int index = extract_index(self);

    return Integer::New(structure->residues(index)->size());
}

Handle<Value> get_name(Local<String> property, const AccessorInfo& info) {
    Local<Object> self = info.This();

    Structure *structure = extract_structure(self);

    int index = extract_index(self);

    return String::New(structure->residues(index)->name().c_str());
}

void set_name(Local<String> property, Local<Value> value,
              const AccessorInfo& info) {
    if (!value->IsString()) {
        ThrowException(String::New("Value is not a string."));
        return;
    }

    Local<Object> self = info.This();

    Structure *structure = extract_structure(self);

    int index = extract_index(self);

    structure->residues(index)->set_name(*String::Utf8Value(value));
}

Handle<Value> get_residue_prototype(const Arguments& args) {
    HandleScope scope;

    Local<Object> object = Object::New();

    object->SetAccessor(String::New("name"), get_name, set_name);

    object->SetAccessor(String::New("size"), get_size);

    return scope.Close(object);
}

}  // namespace

void ResidueModule::init(Handle<ObjectTemplate> global) {
    global->Set(String::New("_getResiduePrototype"),
                FunctionTemplate::New(get_residue_prototype));
}

}  // namespace gems


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>codelab demo</title>

  <link rel="stylesheet"
      href="//fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700">
  <link rel="import" href="../../iron-icons/iron-icons.html">
  <link rel="import" href="../../paper-button/paper-button.html">
  <link rel="import" href="../google-codelab-elements.html">

  <google-codelab title="Build Google Maps Using Web Components & No Code!"
                  feedback-link="https://github.com/googlecodelabs"
                  environment="web">

    <google-codelab-step label="Overview" duration="2">

In this codelab, You'll create a fully working Google Maps app using elements in Polymer's Google Web Components collection. The app will be responsive, include driving directions, and transit a mode. Along the way, you'll also learn about Polymer's data-binding features and iron element set.

What you'll learn

How to start a new Polymer-based project using Chrome Dev Editor

How to use elements in Polymer's iron, paper, and Google Web Component sets.

How to use Polymer's data binding features to reduce boilerplate code.

What you'll need

Basic understanding of HTML, CSS, and web development.

Install Chrome Dev Editor or use your own editor of choice.

<google-codelab-survey survey-id="test-survey-123">
How would rate your experience with Polymer?

<paper-radio-group><paper-radio-button>Novice</paper-radio-button><paper-radio-button>Intermediate</paper-radio-button><paper-radio-button>Advanced</paper-radio-button></paper-radio-group></google-codelab-survey>

      </google-codelab-step>

    <google-codelab-step label="Getting set up" duration="3">

Create a new project

This codelab uses Chrome Dev Editor, a Chrome app IDE. If you don't have it installed yet, please install it from Chrome Web Store.

<paper-button raised class="colored"><iron-icon icon="file-download"></iron-icon>Download Chrome Dev Editor</paper-button>

The first time you run Chrome Dev Editor it will ask you to setup your workspace environment.

Fire up Chrome Dev Editor and start a new project:

Click to start a new project.

Enter "PolymerMapsCodelab" as the Project name.

In the Project type dropdown, select "JavaScript web app (using Polymer paper elements)".

Click the Create button.

Chrome Dev Editor creates a basic scaffold for your Polymer app. In the background, it also uses Bower to download and install a list of dependencies (including the Polymer core library) into the bower_components/ folder. Fetching the components make take some time if your internet connection is slow. You'll learn more about using Bower in the next step.

bower.json

PolymerMapsCodelab/
  bower_components/ <!-- installed dependencies from Bower -->
  bower.json  <!-- Bower metadata files used for managing deps -->
  index.html  <!-- your app -->
  main.js
  styles.css

Preview the app

At any point, select the index.html file and hit the  button in the top toolbar to run the app. Chrome Dev Editor fires up a web server and navigates to the index.html page. This is great way to preview changes as you make them.

Next up

At this point the app doesn't do much. Let's add a map!

      </google-codelab-step>

    <google-codelab-step label="Using <google-map>" duration="5">

The Google Web Components provide the <google-map> element for declaratively rendering a Google Map. To use it, you first need to install it using Bower.

What is Bower?

Bower is a client-side package management tool that can be used with any web app. When working with Polymer, it simplifies the hassles of dependency management. Every component defines its own set of dependencies. When you use Bower to install a component, the component's dependencies are installed alongside it under bower_components/.

Install the <google-map> element

Normally, you'd run bower install GoogleWebComponents/google-map --save on the command line to install <google-map> and save it as a dependency. However, Chrome Dev Editor does not have a command line for running Bower commands. Instead, you need to manually edit bower.json to include google-map, then run Chrome Dev Editor's Bower Update feature. Bower Update checks the dependencies in bower.json and installs any missing ones.

Edit bower.json and add google-map to the dependencies object:

"dependencies": {
  "iron-elements": "PolymerElements/iron-elements#^1.0.0",
  "paper-elements": "PolymerElements/paper-elements#^1.0.1",
  "google-map": "GoogleWebComponents/google-map#^1.0.3"
}

Right-click the bower.json filename in the editor.

Select Bower Update from the context menu.

The download may take few seconds. You can verify that <google-map> (and any dependencies) were installed by checking that bower_components/google-map/ was created and populated.

Use the <google-map> element

To employ <google-map>, you need to:

Use an HTML Import to load it in index.html.

Declare an instance of the element on the page.

In index.html, remove all other HTML imports in the <head> and replace them with a single import that loads google-map.html:

index.html

<head>
  ....
  <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="bower_components/google-map/google-map.html">
</head>

Important: all imports need to come after webcomponents-lite.min.js so the polyfill can properly load them.

Next, replace the contents of <body> with an instance of <google-map>:

index.html

<body unresolved>
  <google-map latitude="37.779" longitude="-122.3892" zoom="13"></google-map>
</body>

As you can see, using <google-map> is completely declarative! The map is centered using the latitude and longitude attributes and its zoom level is set by the zoom attribute.

Style the map

If you run the app right now, nothing will display. In order for the map to properly display itself, you need to set its container (in this case, <body>) to have a fixed height.

Open styles.css and replace its contents with default styling:

styles.css

body, html {
  font-family: 'Roboto', Arial, sans-serif;
  height: 100%;
  margin: 0;
}

Add a marker

<google-map> supports adding map markers to the map by declaring <google-map-marker> elements as children. The marker locations are also set using latitude and longitude attributes.

Back in index.html, add a draggable <google-map-marker> to the map:

index.html

<google-map latitude="37.779" longitude="-122.3892" zoom="13" disable-default-ui>
  <google-map-marker latitude="37.779" longitude="-122.3892"
      title="Go Giants!" draggable="true"></google-map-marker>
</google-map>

Notice that we've also disabled the map's controls by setting disableDefaultUi to true. Since it's a boolean property, its presence as an HTML attribute makes it truthy.

Run the app

If you haven't already done so, hit the  button. At this point, you should see a map that takes up the entire viewport and has a single marker pin.

Frequently Asked Questions

Where are the reference docs for <google-map> and <google-map>?

stackoverflow link

google cloud link

      </google-codelab-step>

  </google-codelab>


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'bundler'
Bundler.require(:default, :development)
require 'webmock/rspec'

# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.include SpecHelperMethods
  config.extend VCR::RSpec::Macros
  config.filter_run :focused => true
  config.run_all_when_everything_filtered = true
  config.alias_example_to :fit, :focused => true
  config.alias_example_to :xit, :disabled => true
  config.color_enabled = true
end

VCR.configure do |c|
  c.cassette_library_dir     = 'spec/cassettes'
  c.hook_into                :webmock
  c.default_cassette_options = { :record => :new_episodes }
end


text:
define(function(require) {
    'use strict';

    var GridSidebarComponent;
    var _ = require('underscore');
    var $ = require('jquery');
    var mediator = require('oroui/js/mediator');
    var routing = require('routing');
    var widgetManager = require('oroui/js/widget-manager');
    var BaseComponent = require('oroui/js/app/components/base/component');
    var PageableCollection = require('orodatagrid/js/pageable-collection');
    var layoutHelper = require('oroui/js/tools/layout-helper');

    GridSidebarComponent = BaseComponent.extend({
        /**
         * @property {Object}
         */
        options: {
            container: '',
            sidebar: '',
            sidebarAlias: '',
            widgetAlias: '',
            widgetContainer: '',
            widgetRoute: 'oro_datagrid_widget',
            widgetRouteParameters: {
                gridName: ''
            },
            gridParam: 'grid',
            fixSidebarHeight: false
        },

        /**
         * @property {Object}
         */
        listen: {
            'grid_load:complete mediator': 'onGridLoadComplete'
        },

        /**
         * @property {Object}
         */
        $container: {},

        /**
         * @property {Object}
         */
        gridCollection: {},

        /**
         * {@inheritDoc}
         */
        initialize: function(options) {
            this.options = _.defaults(options || {}, this.options);

            this.$container = options._sourceElement;
            this.$widgetContainer = $(options.widgetContainer);

            mediator.on('grid-sidebar:change:' + this.options.sidebarAlias, this.onSidebarChange, this);

            this.$container.find('.control-minimize').click(_.bind(this.minimize, this));
            this.$container.find('.control-maximize').click(_.bind(this.maximize, this));

            if (this.options.fixSidebarHeight) {
                layoutHelper.setAvailableHeight('.' + this.options.sidebar);
            }

            this._maximizeOrMaximize(null);
        },

        /**
         * @param {Object} collection
         */
        onGridLoadComplete: function(collection) {
            if (collection.inputName === this.options.widgetRouteParameters.gridName) {
                this.gridCollection = collection;

                var self = this;
                widgetManager.getWidgetInstanceByAlias(
                    this.options.widgetAlias,
                    function() {
                        self._patchGridCollectionUrl(self._getQueryParamsFromUrl(location.search));
                    }
                );
            }
        },

        /**
         * @param {Object} data
         */
        onSidebarChange: function(data) {
            var params = _.extend(
                this._getQueryParamsFromUrl(location.search),
                data.params,
                this._getDatagridParams()
            );
            var widgetParams = _.extend(
                _.omit(this.options.widgetRouteParameters, this.options.gridParam),
                params
            );
            var self = this;

            this._pushState(_.omit(params, _.isNull));

            this._patchGridCollectionUrl(params);

            widgetManager.getWidgetInstanceByAlias(
                this.options.widgetAlias,
                function(widget) {
                    widget.setUrl(routing.generate(self.options.widgetRoute, widgetParams));

                    if (data.widgetReload) {
                        widget.render();
                    } else {
                        mediator.trigger('datagrid:doRefresh:' + widgetParams.gridName);
                    }
                }
            );
        },

        /**
         * @param {Object} params
         * @private
         */
        _patchGridCollectionUrl: function(params) {
            var collection = this.gridCollection;
            if (!_.isUndefined(collection)) {
                var url = collection.url;
                if (_.isUndefined(url)) {
                    return;
                }
                var newParams = _.extend(
                    this._getQueryParamsFromUrl(url),
                    _.omit(params, this.options.gridParam)
                );
                if (url.indexOf('?') !== -1) {
                    url = url.substring(0, url.indexOf('?'));
                }
                if (!_.isEmpty(newParams)) {
                    collection.url = url + '?' + this._urlParamsToString(newParams);
                }
            }
        },

        /**
         * @private
         * @param {Object} params
         */
        _pushState: function(params) {
            var paramsString = this._urlParamsToString(_.omit(params, ['saveState']));
            var current = mediator.execute('pageCache:getCurrent');
            mediator.execute('changeUrl', current.path + '?' + paramsString);
        },

        minimize: function() {
            this._maximizeOrMaximize('off');
        },

        maximize: function() {
            this._maximizeOrMaximize('on');
        },

        /**
         * @private
         * @param {String} state
         */
        _maximizeOrMaximize: function(state) {
            var params = this._getQueryParamsFromUrl(location.search);

            if (state === null) {
                state = params.sidebar || 'on';
            }

            if (state === 'on') {
                this.$container.addClass('grid-sidebar-maximized').removeClass('grid-sidebar-minimized');
                this.$widgetContainer.addClass('grid-sidebar-maximized').removeClass('grid-sidebar-minimized');

                delete params.sidebar;
            } else {
                this.$container.addClass('grid-sidebar-minimized').removeClass('grid-sidebar-maximized');
                this.$widgetContainer.addClass('grid-sidebar-minimized').removeClass('grid-sidebar-maximized');

                params.sidebar = state;
            }

            this._pushState(params);
        },

        /**
         * @param {String} url
         * @return {Object}
         * @private
         */
        _getQueryParamsFromUrl: function(url) {
            if (_.isUndefined(url)) {
                return {};
            }

            if (url.indexOf('?') === -1) {
                return {};
            }

            var query = url.substring(url.indexOf('?') + 1, url.length);
            if (!query.length) {
                return {};
            }

            return PageableCollection.decodeStateData(query);
        },

        /**
         * @param {Object} params
         * @return {String}
         * @private
         */
        _urlParamsToString: function(params) {
            return $.param(params);
        },

        /**
         * @returns {Object}
         * @private
         */
        _getDatagridParams: function() {
            var params = {};
            params[this.gridCollection.options.gridName] = this.gridCollection.urlParams;

            return params;
        },

        dispose: function() {
            if (this.disposed) {
                return;
            }

            mediator.off('grid-sidebar:change:' + this.options.sidebarAlias);

            delete this.gridCollection;

            GridSidebarComponent.__super__.dispose.call(this);
        }
    });

    return GridSidebarComponent;
});


text:
package org.createnet.raptor.common.authentication;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 *
 * @author Luca Capra <lcapra@fbk.eu>
 */
@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return LoginAuthenticationToken.class.isAssignableFrom(authentication);
    }

}


text:
<?php

namespace GraphAware\Bolt\Tests\Documentation;

use GraphAware\Bolt\GraphDatabase;
use GraphAware\Common\Driver\DriverInterface;

/**
 * Class DocumentationTest
 *
 * @group documentation
 */
class DocumentationTest extends \PHPUnit_Framework_TestCase
{
    public function testSetup()
    {
        /**
         * Creating a driver
         */

        $driver = GraphDatabase::driver("bolt://localhost");
        $this->assertInstanceOf(DriverInterface::class, $driver);
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Anna MacDonald ·

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/atom+xml" title="Anna MacDonald" href="/atom.xml">

          Anna MacDonald

        Values

    <time datetime="2015-02-05T00:00:00-08:00" class="post-date">05 Feb 2015</time>

Here are a list of values that come to mind at times in my life where I've been the happiest in some form or another: Accomplishment, Achievement, Affection, Ambition, Close relationships, Compassion, Competence, Confidence, Creativity, Credibility, Decisiveness, Enthusiasm, Excitement, Friendships, Growth, Helping others, Honesty, Inner harmony, Insight, Inspiration, Location, Meaningful work, Music, Nature, Peace, Personal development, Reputation, Romance, Serenity, Stability, Tranquility, Will-power, Wisdom. In general, I try to live up to these values (4/5) because they are standards that I wish to be held to and wish for others to reciprocate (for those actionable values).

One value that is very important to me is inspiration. I believe inspiration is an extremely important value for a person to possess, and I think it is a fairly difficult one to hold on to in times of stress or despair. I have struggled with feeling inspired a lot of my life, so always really treasure moments when I feel inspiration, and look for ways I can inspire other people. Finally, I think that inspiration is closely linked to motivation - which has also been a tough value for me to hold on to - and motivation is so important for success, but more importantly, overall happiness on a day-to-day level.

The last topic that someone asked for my advice on was regarding whether they should pursue a bootcamp like DBC. This topic is related to meaningful work, which I think is extremely important, and given my knowledge of my experience so far, I honestly explained all that I could about the various programs and referred them to Code Academy since I have found it the most enjoyable learning resource outside of the DBC materials. I was hoping to enable them to make an informed decision about whether they would enjoy a programming bootcamp.

I am happy when I think about my values, although sometimes I wish I cared more about things such as prestige and eventual income mainly because I think it may help with my motivation. I think my values of insight and compassion may help mediate stereotype threat if I feel it because I could understand what is making a person act a certain way that I recognize as stereotype threat.

I think the value that I have to work on the most to be successful at DBC is inspiration because I know that if I am able to think of an inspiring project or observe inspiring people in the programming world, that it would help me become more motivated. Since I am very self-aware of moments when I feel lacking in motivation and inspiration, I will need to be able to snap myself out of it and either let it pass or search for sources of inspiration in the community.

    Older

      Newer

          © <time datetime="2015-02-22T11:15:15-08:00">2015</time>. All rights reserved.


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Marattia melanesica Kuhn

### Remarks
null


text:
import unittest
import mock
import datetime

from touchdown.core.datetime import parse_datetime, utc

class TestDateTime(unittest.TestCase):

    def test_5m_ago(self):
        with mock.patch("touchdown.core.datetime.datetime") as mock_dt:
            mock_dt.utcnow.return_value = datetime.datetime(2015, 5, 25, 14, 23, 46, 890132)
            mock_dt.side_effect = datetime.datetime.now()

            self.assertEqual(
                parse_datetime("5m ago"),
                datetime.datetime(2015, 5, 25, 14, 18, 46, 890132, tzinfo=utc)
            )


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:color="@color/common_signin_btn_light_text_pressed" />
    <item
        android:state_enabled="false"
        android:state_focused="true"
        android:color="@color/common_signin_btn_light_text_disabled" />
    <item
        android:state_focused="true"
        android:color="@color/common_signin_btn_light_text_focused" />
    <item
        android:state_enabled="false"
        android:color="@color/common_signin_btn_light_text_disabled" />
    <item
        android:color="@color/common_signin_btn_light_text_default" />
</selector>
<!-- From: file:/home/frank/AndroidStudioProjects/DocHub/app/build/intermediates/exploded-aar/com.google.android.gms/play-services/6.1.71/res/color/common_signin_btn_text_light.xml -->


text:
@implementation NSString (Extension)

- (NSString * _Nullable)contentTypeForImage {
    uint8_t c;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self]];
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
            break;
        case 0x89:
            return @"png";
            break;
        case 0x47:
            return @"gif";
            break;
        case 0x49:
        case 0x4D:
            return @"tiff";
            break;
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *str = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([str hasPrefix:@"RIFF"] && [str hasPrefix:@"WEBP"]) {
                return @"webp";
            }
            break;
    }
    return nil;
}

- (NSString * _Nullable)reverseString {
    NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:self.length];
    for (NSInteger i = self.length - 1; i >= 0; i--) {
        unichar ch = [self characterAtIndex:i];
        [newString appendFormat:@"%c", ch];
    }
    return newString;
}

- (NSString *)reverseInString {
    NSMutableString *reverString = [NSMutableString stringWithCapacity:self.length];
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [reverString appendString:substring];
    }];
    return reverString;
}

- (NSString * _Nullable)chinaTransformWithPhoneticSymbol {
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [self mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    return pinyin;
}

- (NSString * _Nullable)chinaTransForm {
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [self mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripDiacritics, NO);
    //返回最近结果
    return pinyin;
}

@end