text:
package com.bjlx.QinShihuang.core;

import com.bjlx.QinShihuang.core.formatter.timeline.MomentFormatter;
import com.bjlx.QinShihuang.model.account.UserInfo;
import com.bjlx.QinShihuang.model.im.Content;
import com.bjlx.QinShihuang.model.im.Message;
import com.bjlx.QinShihuang.model.im.Relationship;
import com.bjlx.QinShihuang.model.misc.Card;
import com.bjlx.QinShihuang.model.misc.ImageItem;
import com.bjlx.QinShihuang.model.timeline.Moment;
import com.bjlx.QinShihuang.requestmodel.CardReq;
import com.bjlx.QinShihuang.utils.Constant;
import com.bjlx.QinShihuang.utils.ErrorCode;
import com.bjlx.QinShihuang.utils.MorphiaFactory;
import com.bjlx.QinShihuang.utils.QinShihuangResult;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.CriteriaContainerImpl;
import org.mongodb.morphia.query.Query;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 时间线核心实现
 * Created by xiaozhi on 2016/11/18.
 */
public class MomentAPI {

    /**
     * 取得数据库对象
     */
    private static Datastore ds = MorphiaFactory.getInstance();

    public static String getMoments(Long userId, String key, Integer offset, Integer limit, Long latestTime, Long earliestTime) throws Exception {
        try {
            if (!CommonAPI.checkKeyValid(userId, key)) {
                return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1049);
            }
            // 根据用户id查找关注人的id列表
            List<CriteriaContainerImpl> criterias = new ArrayList<>();
            criterias.add(ds.createQuery(Relationship.class).field(Relationship.fd_userA).equal(userId).criteria(Relationship.fd_followingB).equal(true));
            criterias.add(ds.createQuery(Relationship.class).field(Relationship.fd_userB).equal(userId).criteria(Relationship.fd_followingA).equal(true));
            Query<Relationship> query = ds.createQuery(Relationship.class);

            query.or(criterias.toArray(new CriteriaContainerImpl[criterias.size()]));
            query.offset(offset).limit(limit);
            List<Relationship> relationships = null;
            try {
                relationships = query.asList();
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }

            // 关注的人的id集合
            Set<Long> followingIds = new HashSet<Long>();
            if(relationships != null) {
                for (Relationship relationship : relationships) {
                    followingIds.add(relationship.getUserA());
                    followingIds.add(relationship.getUserB());
                }
            }
            followingIds.add(userId);

            // 发表人为自己或者关注的人
            Query<Moment> queryMoment = ds.createQuery(Moment.class).field(Moment.fd_userId).in(followingIds);
            if(latestTime == null) {
                queryMoment.field(Moment.fd_publishTime).lessThan(earliestTime).offset(offset).limit(limit)
                        .order(String.format("-%s", Moment.fd_publishTime));
            } else {
                queryMoment.field(Moment.fd_publishTime).greaterThan(latestTime).offset(offset).limit(limit)
                        .order(String.format("-%s", Moment.fd_publishTime));
            }
            List<Moment> moments = queryMoment.asList();
            if(moments == null)
                return QinShihuangResult.ok(MomentFormatter.getMapper().valueToTree(new ArrayList<Moment>()));
            else
                return QinShihuangResult.ok(MomentFormatter.getMapper().valueToTree(moments));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 查看某个人的朋友圈
     * @param userId 用户id
     * @param key 不羁旅行令牌
     * @param targetId 查看对象的用户id
     * @param offset 从第几个开始取
     * @param limit 取多少个
     * @param latestTime 最晚时间
     * @param earliestTime 最早时间
     * @return 信息列表
     * @throws Exception 异常
     */
    public static String getMomentsById(Long userId, String key, Long targetId, Integer offset, Integer limit, Long latestTime, Long earliestTime) throws Exception {
        try {
            if (!CommonAPI.checkKeyValid(userId, key)) {
                return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1050);
            }
            // 发表人为自己或者关注的人
            Query<Moment> query = ds.createQuery(Moment.class).field(Moment.fd_userId).equal(targetId);
            if(latestTime == null) {
                query.field(Moment.fd_publishTime).lessThan(earliestTime).offset(offset).limit(limit)
                        .order(String.format("-%s", Moment.fd_publishTime));
            } else {
                query.field(Moment.fd_publishTime).greaterThan(latestTime).offset(offset).limit(limit)
                        .order(String.format("-%s", Moment.fd_publishTime));
            }
            List<Moment> moments = query.asList();
            if(moments == null)
                return QinShihuangResult.ok(MomentFormatter.getMapper().valueToTree(new ArrayList<Moment>()));
            else
                return QinShihuangResult.ok(MomentFormatter.getMapper().valueToTree(moments));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 发布朋友圈
     * @param userId 用户id
     * @param key 不羁旅行令牌
     * @param originId 源id
     * @param originUserId 源作者id
     * @param originNickName 源作者昵称
     * @param originAvatar 源作者头像
     * @param text 文本内容
     * @param comment 自己的评论
     * @param images 图片内容
     * @param card 卡片内容
     * @return 结果
     * @throws Exception 异常
     */
    public static String addMoment(Long userId, String key, String originId, Long originUserId, String originNickName, ImageItem originAvatar, String text, String comment,
                                   List<ImageItem> images, CardReq card) throws Exception {
        try {
            if (!CommonAPI.checkKeyValid(userId, key)) {
                return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1051);
            }
            UserInfo userInfo = CommonAPI.getUserBasicWithMomentById(userId);
            if(userInfo == null)
                return QinShihuangResult.getResult(ErrorCode.USER_NOT_EXIST_1051);
            Moment moment = new Moment(userId, userInfo.getNickName(), userInfo.getAvatar());

            if(originId != null && CommonAPI.isObjectId(originId)) {
                moment.setOriginId(new ObjectId(originId));
                moment.setOriginUserId(originUserId);
                moment.setOriginNickName(originNickName);
                moment.setOriginAvatar(originAvatar);
            }
            if(text != null)
                moment.setText(text);
            if(comment != null)
                moment.setComment(comment);
            if(images != null && !images.isEmpty())
                moment.setImages(images);
            if(card != null) {
                Card c = new Card(new ObjectId(card.getId()),card.getTitle(), card.getSummary(), card.getCover(), card.getThumb(), card.getDetailUrl());
                moment.setCard(c);
            }
            ds.save(moment);

            // 根据用户id查找粉丝的id列表
            List<CriteriaContainerImpl> criterias = new ArrayList<>();
            criterias.add(ds.createQuery(Relationship.class).field(Relationship.fd_userA).equal(userId).criteria(Relationship.fd_followingA).equal(true));
            criterias.add(ds.createQuery(Relationship.class).field(Relationship.fd_userB).equal(userId).criteria(Relationship.fd_followingB).equal(true));
            Query<Relationship> query = ds.createQuery(Relationship.class);

            query.or(criterias.toArray(new CriteriaContainerImpl[criterias.size()]));
            List<Relationship> relationships = null;
            try {
                relationships = query.asList();
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }

            // 好友id集合
            Set<Long> contactIds = new HashSet<Long>();
            if(relationships != null) {
                for (Relationship relationship : relationships) {
                    contactIds.add(relationship.getUserA());
                    contactIds.add(relationship.getUserB());
                }
            }
            contactIds.remove(userId);

            // TODO 发送消息给每一个粉丝,此处只需要发一个提醒消息即可,消息的内容已不重要
            List<String> clientIds = ImAPI.getClientIdsByUserIds(contactIds.stream().collect(Collectors.toList()));
            Content content = new Content();
            content.setMoment(moment);
            Message msg = ImAPI.buildMessage(userId, userInfo.getNickName(), userInfo.getAvatar(), userInfo.getId(), content, System.currentTimeMillis(), Constant.MOMENT_MSG, Constant.GROUP_CHAT);
            msg.setAbbrev("");
            ImAPI.sendGroupMsg(msg, clientIds);
            return QinShihuangResult.ok(MomentFormatter.getMapper().valueToTree(moment));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}


text:
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// 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.
//
//

#ifndef io_binary_INCL_
#define io_binary_INCL_

/*! \file
\brief Declarations for namespace io::binary
*/

#include <fstream>
#include <string>
#include <vector>

namespace io
{

/*! \brief Declarations and Definitions for libio.

\par General Concept:

Package-specific conventions for Input/Output involving strings and streams.

\par Special Notes:

+ Provides thread-save wrapping for output streams.

*/
namespace binary
{
	//! Open stream and verify data size
	bool
	prepareStream
		( std::ifstream & ifs
		, std::string const & fpath
		, std::streamsize const & bytesPerRec
		, std::streamsize * const & ptNumRecs
		);

	//! Save contiguous collection of objects to binary file
	template <typename Type>
	inline
	bool
	save
		( Type * const & ptData
		, size_t const & numItems
		, std::string const & fpath
		);

	//! Convenience function for above save()
	template <typename Type>
	inline
	bool
	save
		( std::vector<Type> const & items
		, std::string const & fpath
		);

	//! Load collection of objects from binary file
	template <typename Type>
	inline
	std::vector<Type>
	load
		( std::string const & fpath
		);

} // binary

} // io

// Inline definitions
#include "libio/binary.inl"

#endif // io_binary_INCL_

redpajama_set_name: RedPajamaGithub


text:
package de.nebur97.git.gw2api.item.restrictions;

/**
 * Racial and class restrictions.
Asura
Charr
Human
Norn

 * Sylvari
Guardian
 *
 * @author NeBuR97
 *
 */
public enum Restriction
{
    ASURA, CHARR, GUARDIAN, HUMAN, MESMER, NONE, NORN, RANGER, SYLVARI, WARRIOR;
}


text:
<?php

/**
 * Front end composite field for userforms
 */
class UserFormsGroupField extends UserFormsCompositeField {

	public function __construct($children = null) {
		parent::__construct($children);
		$this->setTag('fieldset');
	}

	public function getLegend() {
		// Legend defaults to title
		return parent::getLegend() ?: $this->Title();
	}

	public function processNext(EditableFormField $field) {
		// When ending a group, jump up one level
		if($field instanceof EditableFieldGroupEnd) {
			return $this->getParent();
		}

		// Otherwise behave as per normal composite field
		return parent::processNext($field);
	}
}


text:
package org.jetbrains.idea.svn.dialogs;

import com.intellij.CommonBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.util.NotNullFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FilteringIterator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.browse.DirectoryEntry;
import org.jetbrains.idea.svn.dialogs.browserCache.Expander;
import org.jetbrains.idea.svn.dialogs.browserCache.NodeLoadState;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class RepositoryTreeNode implements TreeNode, Disposable {

  private TreeNode myParentNode;
  @NotNull private final List<TreeNode> myChildren;
  private final RepositoryTreeModel myModel;
  private final SVNURL myURL;
  private final Object myUserObject;

  @NotNull private final NodeLoadState myLoadState;
  private NodeLoadState myChildrenLoadState;

  public RepositoryTreeNode(RepositoryTreeModel model, TreeNode parentNode,
                            @NotNull SVNURL url, Object userObject, @NotNull NodeLoadState state) {
    myParentNode = parentNode;

    myURL = url;
    myModel = model;
    myUserObject = userObject;

    myLoadState = state;
    myChildren = ContainerUtil.newArrayList();
    myChildrenLoadState = NodeLoadState.EMPTY;
  }

  public RepositoryTreeNode(RepositoryTreeModel model, TreeNode parentNode, @NotNull SVNURL url, Object userObject) {
    // created outside: only roots
    this(model, parentNode, url, userObject, NodeLoadState.REFRESHED);
  }

  public Object getUserObject() {
    return myUserObject;
  }

  public int getChildCount() {
    return getChildren().size();
  }

  public Enumeration children() {
    return Collections.enumeration(getChildren());
  }

  public TreeNode getChildAt(int childIndex) {
    return (TreeNode) getChildren().get(childIndex);
  }

  public int getIndex(TreeNode node) {
    return getChildren().indexOf(node);
  }

  public boolean getAllowsChildren() {
    return !isLeaf();
  }

  public boolean isLeaf() {
    return myUserObject instanceof DirectoryEntry && ((DirectoryEntry)myUserObject).isFile();
  }

  public TreeNode getParent() {
    return myParentNode;
  }

  public void reload(final boolean removeCurrentChildren) {
    // todo lazyLoading as explicit: keeping...
    reload(removeCurrentChildren ? myModel.getSelectionKeepingExpander() : myModel.getLazyLoadingExpander(), removeCurrentChildren);
  }

  @Nullable
  public TreeNode getNextChildByKey(final String key, final boolean isFolder) {
    final ByKeySelectedSearcher searcher = (isFolder) ? new FolderByKeySelectedSearcher(key, myChildren) :
                                                 new FileByKeySelectedSearcher(key, myChildren);
    return searcher.getNextSelectedByKey();
  }

  public String toString() {
    if (myParentNode instanceof RepositoryTreeRootNode) {
      return myURL.toString();
    }
    return SVNPathUtil.tail(myURL.getPath());
  }

  public void reload(@NotNull Expander expander, boolean removeCurrentChildren) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (removeCurrentChildren || NodeLoadState.EMPTY.equals(myChildrenLoadState)) {
      initChildren();
    }

    myModel.getCacheLoader().load(this, expander);
  }

  private void initChildren() {
    myChildren.clear();
    myChildren.add(new SimpleTextNode(CommonBundle.getLoadingTreeNodeText()));
    myChildrenLoadState = NodeLoadState.LOADING;
  }

  private List getChildren() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (NodeLoadState.EMPTY.equals(myChildrenLoadState)) {
      initChildren();
      myModel.getCacheLoader().load(this, myModel.getLazyLoadingExpander());
    }
    return myChildren;
  }

  public SVNURL getURL() {
    return myURL;
  }

  @Nullable
  public DirectoryEntry getSVNDirEntry() {
    return myUserObject instanceof DirectoryEntry ? (DirectoryEntry)myUserObject : null;
  }

  public void dispose() {
  }

  public TreeNode[] getSelfPath() {
    return myModel.getPathToRoot(this);
  }

  public boolean isRepositoryRoot() {
    return ! (myUserObject instanceof DirectoryEntry);
  }

  @NotNull
  public List<TreeNode> getAllAlreadyLoadedChildren() {
    return ContainerUtil.newArrayList(myChildren);
  }

  @NotNull
  public List<RepositoryTreeNode> getAlreadyLoadedChildren() {
    return ContainerUtil.collect(myChildren.iterator(), FilteringIterator.instanceOf(RepositoryTreeNode.class));
  }

  public boolean isDisposed() {
    return myModel.isDisposed();
  }

  public void setChildren(@NotNull List<DirectoryEntry> children, @NotNull NodeLoadState state) {
    final List<TreeNode> nodes = new ArrayList<TreeNode>();
    for (final DirectoryEntry entry : children) {
      if (!myModel.isShowFiles() && !entry.isDirectory()) {
        continue;
      }
      nodes.add(new RepositoryTreeNode(myModel, this, entry.getUrl(), entry, state));
    }

    myChildrenLoadState = state;
    myChildren.clear();
    myChildren.addAll(nodes);

    myModel.reload(this);
  }

  public void setParentNode(final TreeNode parentNode) {
    myParentNode = parentNode;
  }

  public void setAlienChildren(final List<TreeNode> children, final NodeLoadState oldState) {
    myChildren.clear();

    for (TreeNode child : children) {
      if (child instanceof RepositoryTreeNode) {
        ((RepositoryTreeNode) child).setParentNode(this);
        myChildren.add(child);
        myChildrenLoadState = oldState;
      }
      else if (child instanceof SimpleTextNode) {
        SimpleTextNode node = (SimpleTextNode)child;
        myChildren.add(new SimpleTextNode(node.getText(), node.isError()));
        myChildrenLoadState = oldState;
      }
    }

    myModel.reload(this);
  }

  public void setErrorNode(@NotNull String text) {
    myChildren.clear();
    myChildren.add(new SimpleTextNode(text, true));
    myChildrenLoadState = NodeLoadState.ERROR;
    myModel.reload(this);
  }

  public SvnVcs getVcs() {
    return myModel.getVCS();
  }

  public boolean isCached() {
    return NodeLoadState.CACHED.equals(myLoadState);
  }

  @Nullable
  public RepositoryTreeNode getNodeWithSamePathUnderModelRoot() {
    return myModel.findByUrl(this);
  }

  public NodeLoadState getChildrenLoadState() {
    return myChildrenLoadState;
  }

  public void doOnSubtree(@NotNull NotNullFunction<RepositoryTreeNode, Object> function) {
    new SubTreeWalker(this, function).execute();
  }

  private static class SubTreeWalker {

    @NotNull private final RepositoryTreeNode myNode;
    @NotNull private final NotNullFunction<RepositoryTreeNode, Object> myFunction;

    private SubTreeWalker(@NotNull RepositoryTreeNode node, @NotNull NotNullFunction<RepositoryTreeNode, Object> function) {
      myNode = node;
      myFunction = function;
    }

    public void execute() {
      executeImpl(myNode);
    }

    private void executeImpl(final RepositoryTreeNode node) {
      myFunction.fun(node);
      for (RepositoryTreeNode child : node.getAlreadyLoadedChildren()) {
        myFunction.fun(child);
      }
    }
  }
}


text:
package jj.configuration;

import javax.inject.Inject;
import javax.inject.Singleton;

import jj.script.Global;

import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

/**
 *

 * Exposes the environment variables of the process to the script API
 *
 *

 * may make this a per-request instance? in which case allow the prototype
 * to be altered?
 * @author jason
 *
 */
@Singleton
public class EnvironmentScriptable implements Scriptable {

	private final Scriptable parentScope;
	private final Scriptable prototype;

	@Inject
	EnvironmentScriptable(final @Global ScriptableObject global) {
		parentScope = global;
		prototype = NativeObject.getObjectPrototype(parentScope);
	}

	@Override
	public String getClassName() {
		return getClass().getSimpleName();
	}

	@Override
	public Object get(String name, Scriptable start) {
		String result = System.getenv(name);
		return result == null ? NOT_FOUND : result;
	}

	@Override
	public Object get(int index, Scriptable start) {
		return NOT_FOUND;
	}

	@Override
	public boolean has(String name, Scriptable start) {
		return System.getenv(name) != null;
	}

	@Override
	public boolean has(int index, Scriptable start) {
		return false;
	}

	@Override
	public void put(String name, Scriptable start, Object value) {
		// nosir
	}

	@Override
	public void put(int index, Scriptable start, Object value) {
		// nosir
	}

	@Override
	public void delete(String name) {
		// nosir
	}

	@Override
	public void delete(int index) {
		// nosir
	}

	@Override
	public Scriptable getPrototype() {
		return prototype;
	}

	@Override
	public void setPrototype(Scriptable prototype) {
		// nope
	}

	@Override
	public Scriptable getParentScope() {
		return parentScope;
	}

	@Override
	public void setParentScope(Scriptable parent) {
		// nope
	}

	@Override
	public Object[] getIds() {
		return System.getenv().keySet().toArray();
	}

	@Override
	public Object getDefaultValue(Class<?> hint) {
		return this;
	}

	@Override
	public boolean hasInstance(Scriptable instance) {
		return instance == this;
	}

}


text:
.. _zend.stdlib.hydrator:

Zend\\Stdlib\\Hydrator
======================

Hydration is the act of populating an object from a set of data.

The ``Hydrator`` is a simple component to provide mechanisms both for hydrating objects, as well as extracting data
sets from them.

The component consists of an interface, and several implementations for common use cases.

.. _zend.stdlib.hydrator.interface:

HydratorInterface
-----------------

.. code-block:: php
   :linenos:

   namespace Zend\Stdlib\Hydrator;

   interface HydratorInterface
   {
       /**
        * Extract values from an object
        *
        * @param  object $object
        * @return array
        */
       public function extract($object);

       /**
        * Hydrate $object with the provided $data.
        *
        * @param  array $data
        * @param  object $object
        * @return object
        */
       public function hydrate(array $data, $object);
   }

.. _zend.stdlib.hydrator.usage:

Usage
-----

Usage is quite simple: simply instantiate the hydrator, and then pass information to it.

.. code-block:: php
   :linenos:

   use Zend\Stdlib\Hydrator;
   $hydrator = new Hydrator\ArraySerializable();

   $object = new ArrayObject(array());

   $hydrator->hydrate($someData, $object);

   // or, if the object has data we want as an array:
   $data = $hydrator->extract($object);

.. _zend.stdlib.hydrator.concrete:

Available Implementations
-------------------------

- **Zend\\Stdlib\\Hydrator\\ArraySerializable**

  Follows the definition of ``ArrayObject``. Objects must implement either the ``exchangeArray()`` or
  ``populate()`` methods to support hydration, and the ``getArrayCopy()`` method to support extraction.

- **Zend\\Stdlib\\Hydrator\\ClassMethods**

  Any data key matching a setter method will be called in order to hydrate; any method matching a getter method
  will be called for extraction.

- **Zend\\Stdlib\\Hydrator\\DelegatingHydrator**

  Composes a hydrator locator containing hydrators and will delegate ``hydrate()`` and ``extract()`` calls to the
  appropriate one based upon the class name of the object being operated on.

.. code-block:: php
   :linenos:

    // Instantiate each hydrator you wish to delegate to
    $albumHydrator = new Zend\Stdlib\Hydrator\ClassMethods;
    $artistHydrator = new Zend\Stdlib\Hydrator\ClassMethods;

    // Map the entity class name to the hydrator using the HydratorPluginManager
    // In this case we have two entity classes, "Album" and "Artist"
    $hydrators = new Zend\Stdlib\Hydrator\HydratorPluginManager;
    $hydrators->setService('Album', $albumHydrator);
    $hydrators->setService('Artist', $artistHydrator);

    // Create the DelegatingHydrator and tell it to use our configured hydrator locator
    $delegating = new Zend\Stdlib\Hydrator\DelegatingHydrator($hydrators);

    // Now we can use $delegating to hydrate or extract any supported object
    $array = $delegating->extract(new Artist);
    $artist = $delegating->hydrate($data, new Artist);

- **Zend\\Stdlib\\Hydrator\\ObjectProperty**

  Any data key matching a publicly accessible property will be hydrated; any public properties will be used for
  extraction.

- **Zend\\Stdlib\\Hydrator\\Reflection**

  Similar to the ``ObjectProperty`` hydrator, but uses `PHP's reflection API <http://php.net/manual/en/intro.reflection.php>`_
  to hydrate or extract properties of any visibility.  Any data key matching an existing property will be hydrated;
  any existing properties will be used for extraction.


text:
namespace pegtl
{
   namespace internal
   {
      template< char C >
      using is_alpha = std::integral_constant< bool, ( ( 'a' <= C ) && ( C <= 'z' ) ) || ( ( 'A' <= C ) && ( C <= 'Z' ) ) >;

      template< char C, bool A = is_alpha< C >::value > struct ichar_equal;

      template< char C > struct ichar_equal< C, true >
      {
         static bool match( const char c )
         {
            return ( C | 0x20 ) == ( c | 0x20 );
         }
      };

      template< char C > struct ichar_equal< C, false >
      {
         static bool match( const char c )
         {
            return c == C;
         }
      };

      template< char ... Cs > struct istring_equal;

      template<> struct istring_equal<>
      {
         static bool match( const char * )
         {
            return true;
         }
      };

      template< char C, char ... Cs > struct istring_equal< C, Cs ... >
      {
         static bool match( const char * r )
         {
            return ichar_equal< C >::match( * r ) && istring_equal< Cs ... >::match( r + 1 );
         }
      };

      template< char ... Cs > struct istring;

      template< char ... Cs >
      struct skip_control< istring< Cs ... > > : std::true_type {};

      template<> struct istring<>
            : trivial< true > {};

      template< char ... Cs >
      struct istring
      {
         using analyze_t = analysis::counted< analysis::rule_type::ANY, sizeof ... ( Cs ) >;

         template< typename Input >
         static bool match( Input & in )
         {
            if ( in.size() >= sizeof ... ( Cs ) ) {
               if ( istring_equal< Cs ... >::match( in.begin() ) ) {
                  in.bump( sizeof ... ( Cs ) );
                  return true;
               }
            }
            return false;
         }
      };

   } // internal

} // pegtl

#endif


text:
layout: post
title: Easy PDF Presentations With Pandoc
category: education
tags: education latex beamer markdown emacs text presentations
---

As a dedicated Emacs and Linux user, I find my life much simpler when
I can live in plain text as much as possible. This allows me to
leverage the experience I've built up with my favorite editor, version
content and collaborate painlessly with git, and avoid proprietary
formats and applications. As a researcher and student, I've preferred
$$\LaTeX$$ for writing reports and papers for these reasons, as well
as its renowned typesetting capabilities. I've dabbled with using the
Beamer package for presentations, but ultimately while LaTeX is great
for formatting documents, it can be very tedious to typeset your
presentations. This is where Pandoc comes in.

Pandoc is a highly flexible program for processing Markdown and
converting it to many formats. Conveniently, one of the formats that
it supports is Beamer presentations. The lightweight nature of
Markdown allows me to focus on content in my presentations as opposed
to formatting.

This summer I've been teaching
[CSE30: Computer Organization and Systems Programming](http://cseweb.ucsd.edu/classes/su15/cse30-a/index.html). In
the past, I've not really spent much time preparing for discussion
section because few students regularly show up, but in an effort to
improve my teaching and presentation skills I've decided to come to
class prepared with a detailed presentation. It's debatable whether
this is better than having less structure, talking more off-script,
and using the blackboard. For me, since I still get nervous when
presenting, I find that having a lot of text helps me stay calm. I
still struggle with maintaining eye contact and not reading off
slides, but I think having a coherent presentation is a good first
step to developing my teaching experience.

The awesome thing about the Pandoc-Beamer-PDF workflow is that I can
just type up my points in outline form and format them using
Markdown's intuitive syntax, allowing me to focus on content vs
presentation. I have a simple Makefile that converts my Markdown file
to PDF using pandoc. When I need to specify some more complex
formatting rules or equations, I can insert LaTeX which is passed
through directly to LaTeX.

One of the "issues" with Beamer is that the default templates are
rather bland and dated. While it's arguably not important for the
presentation to be "hip" and "modern" as long as the content is good,
having a visually pleasing presentation never hurts, and thankfully
there's an alternative Beamer theme named
[Metropolis](https://github.com/matze/mtheme/) which features
an excellent modern font (Mozilla's Fira Sans) and clean layout. Using
it is as simple as specifying a TeX header file when calling Pandoc.

For full details, check out
[the code](https://github.com/ibrahima/cse30/tree/master/disc4) for
one of my discussion section presentations.


text:
require 'spec_helper'

describe Puppet::Type.type(:network_config).provider(:interfaces) do
  def fixture_data(file)
    basedir = File.join(PROJECT_ROOT, 'spec', 'fixtures', 'provider', 'network_config', 'interfaces_spec')
    File.read(File.join(basedir, file))
  end

  after do
    v_level = $VERBOSE
    $VERBOSE = nil
    Instance.reset!
    $VERBOSE = v_level
  end

  describe 'provider features' do
    it 'is hotpluggable' do
      expect(described_class.declared_feature?(:hotpluggable)).to be true
    end
  end

  describe 'when parsing' do
    it 'parses out auto interfaces' do
      fixture = fixture_data('loopback')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'lo' }[:onboot]).to be true
    end

    it "parses out allow-hotplug interfaces as 'hotplug'" do
      fixture = fixture_data('single_interface_dhcp')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }[:hotplug]).to be true
    end

    it "parses out allow-auto interfaces as 'onboot'" do
      fixture = fixture_data('two_interface_dhcp')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth1' }[:onboot]).to be true
    end

    it 'parses out iface lines' do
      fixture = fixture_data('single_interface_dhcp')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(family: 'inet',
                                                         method: 'dhcp',
                                                         mode: :raw,
                                                         name: 'eth0',
                                                         hotplug: true,
                                                         options: {})
    end

    it 'ignores source and source-directory lines' do
      fixture = fixture_data('jessie_source_stanza')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(family: 'inet',
                                                         method: 'dhcp',
                                                         mode: :raw,
                                                         name: 'eth0',
                                                         hotplug: true,
                                                         options: {})
    end

    it 'ignores variable whitespace in iface lines (network-#26)' do
      fixture = fixture_data('iface_whitespace')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(family: 'inet',
                                                         method: 'dhcp',
                                                         mode: :raw,
                                                         name: 'eth0',
                                                         hotplug: true,
                                                         options: {})
    end

    it 'parses out lines following iface lines' do
      fixture = fixture_data('single_interface_static')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(name: 'eth0',
                                                         family: 'inet',
                                                         method: 'static',
                                                         mode: :raw,
                                                         ipaddress: '192.168.0.2',
                                                         netmask: '255.255.255.0',
                                                         onboot: true,
                                                         mtu: '1500',
                                                         options: {
                                                           'broadcast' => '192.168.0.255',
                                                           'gateway' => '192.168.0.1'
                                                         })
    end

    # mapping sections aren't support, and might not ever be supported.
    # it "should parse out mapping lines"
    # it "should parse out lines following mapping lines"

    it 'allows for multiple options sections' do
      fixture = fixture_data('single_interface_options')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(name: 'eth0',
                                                         family: 'inet',
                                                         method: 'dhcp',
                                                         mode: :raw,
                                                         options: {
                                                           'pre-up' => '/bin/touch /tmp/eth0-up',
                                                           'post-down' => [
                                                             '/bin/touch /tmp/eth0-down1',
                                                             '/bin/touch /tmp/eth0-down2'
                                                           ]
                                                         })
    end

    it 'parses out vlan iface lines' do
      fixture = fixture_data('two_interfaces_static_vlan')
      data = described_class.parse_file('', fixture)
      expect(data.find { |h| h[:name] == 'eth0' }).to eq(name: 'eth0',
                                                         family: 'inet',
                                                         method: 'static',
                                                         mode: :raw,
                                                         ipaddress: '192.168.0.2',
                                                         netmask: '255.255.255.0',
                                                         onboot: true,
                                                         mtu: '1500',
                                                         options: {
                                                           'broadcast' => '192.168.0.255',
                                                           'gateway' => '192.168.0.1'
                                                         })
      expect(data.find { |h| h[:name] == 'eth0.1' }).to eq(name: 'eth0.1',
                                                           family: 'inet',
                                                           method: 'static',
                                                           ipaddress: '172.16.0.2',
                                                           netmask: '255.255.255.0',
                                                           onboot: true,
                                                           mtu: '1500',
                                                           mode: :vlan,
                                                           options: {
                                                             'broadcast' => '172.16.0.255',
                                                             'gateway' => '172.16.0.1',
                                                             'vlan-raw-device' => 'eth0'
                                                           })
    end

    describe 'when reading an invalid interfaces' do
      it 'with misplaced options should fail' do
        expect do
          described_class.parse_file('', "address 192.168.1.1\niface eth0 inet static\n")
        end.to raise_error(%r{Malformed debian interfaces file})
      end

      it 'with an option without a value should fail' do
        expect do
          described_class.parse_file('', "iface eth0 inet manual\naddress")
        end.to raise_error(%r{Malformed debian interfaces file})
      end
    end
  end

  describe 'when formatting' do
    let(:eth0_provider) do
      instance_double('eth0_provider',
                      name: 'eth0',
                      ensure: :present,
                      onboot: true,
                      hotplug: true,
                      family: 'inet',
                      method: 'static',
                      ipaddress: '169.254.0.1',
                      netmask: '255.255.0.0',
                      mtu: '1500',
                      mode: nil,
                      options: nil)
    end

    let(:vlan20_provider) do
      instance_double('vlan20_provider',
                      name: 'vlan20',
                      ensure: :present,
                      onboot: true,
                      hotplug: true,
                      family: 'inet',
                      method: 'static',
                      ipaddress: '169.254.0.1',
                      netmask: '255.255.0.0',
                      mtu: '1500',
                      mode: :vlan,
                      options: {
                        'vlan-raw-device' => 'eth1'
                      })
    end

    let(:vlan10_provider) do
      instance_double('vlan10_provider',
                      name: 'vlan10',
                      ensure: :present,
                      onboot: true,
                      hotplug: true,
                      family: 'inet',
                      method: 'dhcp',
                      ipaddress: nil,
                      netmask: nil,
                      mtu: nil,
                      mode: :vlan,
                      options: {})
    end

    let(:eth1_4500_provider) do
      instance_double('eth1_4500_provider',
                      name: 'eth1.4500',
                      ensure: :present,
                      onboot: true,
                      hotplug: true,
                      family: 'inet',
                      method: 'dhcp',
                      ipaddress: nil,
                      netmask: nil,
                      mtu: nil,
                      mode: :vlan,
                      options: {})
    end

    let(:eth1_provider) do
      instance_double('eth1_provider',
                      name: 'eth1',
                      ensure: :present,
                      onboot: false,
                      hotplug: true,
                      family: 'inet',
                      method: 'static',
                      ipaddress: '169.254.0.1',
                      netmask: '255.255.0.0',
                      mtu: '576',
                      mode: nil,
                      options: {
                        'pre-up' => '/bin/touch /tmp/eth1-up',
                        'post-down' => [
                          '/bin/touch /tmp/eth1-down1',
                          '/bin/touch /tmp/eth1-down2'
                        ]
                      })
    end

    let(:lo_provider) do
      instance_double('lo_provider',
                      name: 'lo',
                      onboot: true,
                      hotplug: false,
                      family: 'inet',
                      method: 'loopback',
                      ipaddress: nil,
                      netmask: nil,
                      mtu: '65536',
                      mode: nil,
                      options: nil)
    end

    before do
      allow(described_class).to receive(:header).and_return "# HEADER: stubbed header\n"
    end

    let(:content) { described_class.format_file('', [lo_provider, eth0_provider, eth1_provider]) } # rubocop:disable RSpec/ScatteredLet

    describe 'writing the auto section' do
      it 'allows at most one section' do
        expect(content.scan(%r{^auto .+$}).length).to eq(1)
      end

      it 'has the correct interfaces appended' do
        expect(content.scan(%r{^auto .+$}).first).to match('auto eth0 lo')
      end
    end

    describe 'writing only the auto section' do
      let(:content) { described_class.format_file('', [lo_provider]) }

      it 'skips the allow-hotplug line' do
        expect(content.scan(%r{^allow-hotplug .*$}).length).to eq(0)
      end
    end

    describe 'writing the allow-hotplug section' do
      it 'allows at most one section' do
        expect(content.scan(%r{^allow-hotplug .+$}).length).to eq(1)
      end

      it 'has the correct interfaces appended' do
        expect(content.scan(%r{^allow-hotplug .+$}).first).to match('allow-hotplug eth0 eth1')
      end
    end

    describe 'writing only the allow-hotplug section' do
      let(:content) { described_class.format_file('', [eth1_provider]) }

      it 'skips the auto line' do
        expect(content.scan(%r{^auto .*$}).length).to eq(0)
      end
    end

    describe 'writing iface blocks' do
      let(:content) { described_class.format_file('', [lo_provider, eth0_provider]) }

      it 'produces an iface block for each interface' do
        expect(content.scan(%r{iface eth0 inet static}).length).to eq(1)
      end

      it 'adds all options following the iface block' do
        block = [
          'iface eth0 inet static',
          'address 169.254.0.1',
          'netmask 255.255.0.0',
          'mtu 1500'
        ].join("\n")
        expect(content.split('\n').find { |line| line.match(%r{iface eth0}) }).to match(block)
      end

      it 'fails if the family property is not defined' do
        allow(lo_provider).to receive(:family).and_return(nil)
        expect { content }.to raise_exception(%r{does not have a family})
      end

      it 'fails if the method property is not defined' do
        allow(lo_provider).to receive(:method).and_return(nil)
        expect { content }.to raise_exception(%r{does not have a method})
      end
    end

    describe 'writing vlan iface blocks' do
      let(:content) { described_class.format_file('', [vlan20_provider]) }

      it 'adds all options following the iface block' do
        block = [
          'iface vlan20 inet static',
          'vlan-raw-device eth1',
          'address 169.254.0.1',
          'netmask 255.255.0.0',
          'mtu 1500'
        ].join("\n")
        expect(content.split('\n').find { |line| line.match(%r{iface vlan20}) }).to match(block)
      end
    end

    describe 'writing wrong vlan iface blocks' do
      let(:content) { described_class.format_file('', [eth1_4500_provider]) }

      it 'fails with wrong VLAN ID' do
        expect { content }.to raise_error(Puppet::Error, %r{Interface eth1.4500: missing vlan-raw-device or wrong VLAN ID in the iface name})
      end
    end

    describe 'writing wrong vlanNN iface blocks' do
      let(:content) { described_class.format_file('', [vlan10_provider]) }

      it 'fails with missing vlan-raw-device' do
        expect { content }.to raise_error(Puppet::Error, %r{Interface vlan10: missing vlan-raw-device or wrong VLAN ID in the iface name})
      end
    end

    describe 'writing the options section' do
      let(:content) { described_class.format_file('', [eth1_provider]) }

      describe 'with a string value' do
        it 'writes a single entry' do
          expect(content.scan(%r{pre-up .*$}).size).to eq(1)
        end

        it 'writes the value as an modified string' do
          expect(content.scan(%r{^\s*pre-up .*$}).first).to eq('    pre-up /bin/touch /tmp/eth1-up')
        end
      end

      describe 'with an array value' do
        it 'writes an entry per array value' do
          expect(content.scan(%r{post-down .*$}).size).to eq(2)
        end

        it 'writes the values in order' do
          expect(content.scan(%r{^\s*post-down .*$})[0]).to eq('    post-down /bin/touch /tmp/eth1-down1')
          expect(content.scan(%r{^\s*post-down .*$})[1]).to eq('    post-down /bin/touch /tmp/eth1-down2')
        end
      end
    end
  end
end


text:
'use strict';

angular.module('myApp.auth', ['ngRoute', 'ng-token-auth'])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/login', {
        templateUrl: 'auth/login.html',
        controller: 'AuthCtrl'
      })
      .when('/signup', {
        templateUrl: 'auth/signup.html',
        controller: 'AuthCtrl'
      });
  }])
  .config(function($authProvider) {
    $authProvider.configure({
      apiUrl: REST_API_URL
    });
  })
  .controller("AuthCtrl", ['validateUser','$location', function(validateUser, $location) {
    validateUser().then(function(logged) {
      if (logged) {
        $location.path('/chat').replace();
      }
    });
  }]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2015 StreamSets Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.streamsets</groupId>
  <artifactId>streamsets-datacollector-rbgen-maven-plugin</artifactId>
  <version>1.6.0.0-SNAPSHOT</version>
  <description>StreamSets Data Collector RB Gen Maven Plugin</description>
  <name>StreamSets Data Collector RB Gen Maven Plugin</name>
  <packaging>maven-plugin</packaging>

  <properties>
    <!-- required JDK version -->
    <javaVersion>1.7</javaVersion>

    <!-- Platform encoding override -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <maven-compiler-plugin>3.1</maven-compiler-plugin>

    <maven.dependency.version>3.0</maven.dependency.version>
    <maven.plugin-tools.version>3.4</maven.plugin-tools.version>

    <commons-io.version>2.4</commons-io.version>
    <jackson.version>2.4.3</jackson.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <scope>provided</scope>
      <version>${maven.dependency.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <scope>provided</scope>
      <version>${maven.dependency.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <scope>compile</scope>
      <version>${maven.dependency.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <scope>provided</scope>
      <version>${maven.plugin-tools.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <scope>compile</scope>
      <version>${commons-io.version}</version>
    </dependency>
    <!--<dependency>-->
      <!--<groupId>com.fasterxml.jackson.core</groupId>-->
      <!--<artifactId>jackson-core</artifactId>-->
      <!--<scope>compile</scope>-->
      <!--<version>${jackson.version}</version>-->
    <!--</dependency>-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <scope>compile</scope>
      <version>${jackson.version}</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven-compiler-plugin}</version>
        <configuration>
          <source>${javaVersion}</source>
          <target>${javaVersion}</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>${maven.plugin-tools.version}</version>
        <executions>
          <execution>
            <id>default-descriptor</id>
            <phase>process-classes</phase>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
class ImageLoaderQueue : public QObject
{
	Q_OBJECT

	public:
		ImageLoaderQueue(ImageLoader *imageLoader, QObject *parent = Q_NULLPTR);

	public slots:
		void load(const QByteArray &data);
		void clear();

	private slots:
		void loadingSuccess(const QPixmap &, int);
		void loadingFinished();

	signals:
		void finished(const QPixmap &, int);
		void loadImage(const QByteArray &);

	private:
		QByteArray m_next;
		bool m_waiting;
		bool m_cancelNext;
		bool m_hasNext;
};

#endif // IMAGE_LOADER_QUEUE_H


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

// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/pubsublite/v1/admin.proto

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_MOCKS_MOCK_ADMIN_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_MOCKS_MOCK_ADMIN_CONNECTION_H

#include "google/cloud/pubsublite/admin_connection.h"
#include <gmock/gmock.h>

namespace google {
namespace cloud {
namespace pubsublite_mocks {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/**
 * A class to mock `AdminServiceConnection`.
 *
 * Application developers may want to test their code with simulated responses,
 * including errors, from an object of type `AdminServiceClient`. To do so,
 * construct an object of type `AdminServiceClient` with an instance of this
 * class. Then use the Google Test framework functions to program the behavior
 * of this mock.
 *
 * @see [This example][bq-mock] for how to test your application with
 * GoogleTest. While the example showcases types from the BigQuery library, the
 * underlying principles apply for any pair of `*Client` and `*Connection`.
 *
 * [bq-mock]: @googleapis_dev_link{bigquery,bigquery-read-mock.html}
 */
class MockAdminServiceConnection : public pubsublite::AdminServiceConnection {
 public:
  MOCK_METHOD(Options, options, (), (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Topic>, CreateTopic,
      (google::cloud::pubsublite::v1::CreateTopicRequest const& request),
      (override));

  MOCK_METHOD(StatusOr<google::cloud::pubsublite::v1::Topic>, GetTopic,
              (google::cloud::pubsublite::v1::GetTopicRequest const& request),
              (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::TopicPartitions>,
      GetTopicPartitions,
      (google::cloud::pubsublite::v1::GetTopicPartitionsRequest const& request),
      (override));

  MOCK_METHOD(StreamRange<google::cloud::pubsublite::v1::Topic>, ListTopics,
              (google::cloud::pubsublite::v1::ListTopicsRequest request),
              (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Topic>, UpdateTopic,
      (google::cloud::pubsublite::v1::UpdateTopicRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DeleteTopic,
      (google::cloud::pubsublite::v1::DeleteTopicRequest const& request),
      (override));

  MOCK_METHOD(
      StreamRange<std::string>, ListTopicSubscriptions,
      (google::cloud::pubsublite::v1::ListTopicSubscriptionsRequest request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Subscription>, CreateSubscription,
      (google::cloud::pubsublite::v1::CreateSubscriptionRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Subscription>, GetSubscription,
      (google::cloud::pubsublite::v1::GetSubscriptionRequest const& request),
      (override));

  MOCK_METHOD(StreamRange<google::cloud::pubsublite::v1::Subscription>,
              ListSubscriptions,
              (google::cloud::pubsublite::v1::ListSubscriptionsRequest request),
              (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Subscription>, UpdateSubscription,
      (google::cloud::pubsublite::v1::UpdateSubscriptionRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DeleteSubscription,
      (google::cloud::pubsublite::v1::DeleteSubscriptionRequest const& request),
      (override));

  MOCK_METHOD(
      future<StatusOr<google::cloud::pubsublite::v1::SeekSubscriptionResponse>>,
      SeekSubscription,
      (google::cloud::pubsublite::v1::SeekSubscriptionRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Reservation>, CreateReservation,
      (google::cloud::pubsublite::v1::CreateReservationRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Reservation>, GetReservation,
      (google::cloud::pubsublite::v1::GetReservationRequest const& request),
      (override));

  MOCK_METHOD(StreamRange<google::cloud::pubsublite::v1::Reservation>,
              ListReservations,
              (google::cloud::pubsublite::v1::ListReservationsRequest request),
              (override));

  MOCK_METHOD(
      StatusOr<google::cloud::pubsublite::v1::Reservation>, UpdateReservation,
      (google::cloud::pubsublite::v1::UpdateReservationRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DeleteReservation,
      (google::cloud::pubsublite::v1::DeleteReservationRequest const& request),
      (override));

  MOCK_METHOD(
      StreamRange<std::string>, ListReservationTopics,
      (google::cloud::pubsublite::v1::ListReservationTopicsRequest request),
      (override));

  MOCK_METHOD(
      future<StatusOr<google::cloud::pubsublite::v1::TopicPartitions>>,
      AsyncGetTopicPartitions,
      (google::cloud::pubsublite::v1::GetTopicPartitionsRequest const& request),
      (override));
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace pubsublite_mocks
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_MOCKS_MOCK_ADMIN_CONNECTION_H


text:
Start

Einladungen {{userLogged.name}}

Laden Sie Freunde und Bekannte ein, KURAVIS auszuprobieren. Einfach E-Mail Adresse(n) eingeben, "Senden" klicken, fertig.

Ihre Freunde und Bekannte erhalten dann eine Einladungsmail mit personalisiertem Zugangslink.
Für jede Bewertung die Sie abgeben, können Sie eine Einladung versenden. Die Einladung wird anonym versendet. Bitte informieren Sie den Empfänger vorgängig über einen alternativen Kommunikationskanal, dass
die Einladung durch Sie initiert wurde.

Einladungen

 		 <invitation-count value="{{invitationsCount}}"></invitation-count>

Bitte anmelden

		<input type="email" class="form-control" ng-disabled="((invitationsCount <= 0) && (isAdminLogged == false))" ng-model="invitationEmail" placeholder="E-mail"/>

		Sie haben keine Einladungen verfügbar. Sie müssen zuerst eine Bewertung vornehmen.

		<button ng-disabled="((invitationsCount <= 0) && (isAdminLogged == false))" class="btn btn-default pull-right" ng-disabled="!invitationEmail" ng-click="sendInvitation()">Senden</button>

Einladungsverlauf

			Gesandt an
			{{emailObject.email}}
			<button class="btn btn-default pull-right noPaddingRight" ng-click="resendInvitation(emailObject.email)">Erneut senden</button>


text:
'use strict';

var app = angular.module('knl');

app.filter('limitToDots', [
    function () {
        return function (input, limit) {
            if (!input || input.length <= limit) {
                return input;
            } else {
                return input.substring(0, limit) + '...';
            }
        };
    }
]);


text:
title:  Selvstendighet
date:  14/09/2022
---

Evas synd i Edens hage var ikke bare at hun tvilte på det Gud sa. Hovedproblemet var at hun trodde hun var klok nok til selv å avgjøre hva som var bra og rett. Hun stolte på egen dømmekraft. Når vi stoler mer på vår egen dømmekraft enn på Guds ord, åpner vi oss opp for alle slags problemer.

Historien om Saul beskriver trinnene til selvtilstrekkelighet og den tragedien som fort følger. Samuel salvet ham til Guds konge (1 Sam 10,1). Så ga han ham klare instrukser, men Saul var ulydig (1 Sam 10,8).

`Les neste del i 1 Sam 13,1–14. Hva gjorde Saul som førte til hans undergang?`

Tre trinn førte Saul ned på selvgodhetens vei kort tid etter at han ble konge. Ingen av disse trinnene var spesielt dårlige i seg selv. Likevel hadde de i seg spiren til tragedien fordi de ble tatt uavhengig av Gud. Legg merke til hvordan Saul gikk under.

1. Saul sa: «Jeg så» – at styrken spredte seg og at Samuel ikke kom (1 Sam 13,11). Saul var under press, og han vurderte det som skjedde med sine egne øyne.
2. Saul gikk fra «jeg så» til «jeg tenkte» – at filistrene ville slå dem (1 Sam 13,12). Det han så med egne øyne, formet det han antok om situasjonen.
3. Saul gikk fra «jeg tenkte» til «jeg våget» – han følte seg nødt til å ofre (1 Sam 13,12). Det Saul tenkte, formet følelsene hans.

Dette har vi alle gjort: vi stoler på det vi ser, som får oss til å stole på vår egen tankegang, som fører til at vi stoler på våre følelser. Og så handler vi ut fra følelsene.

`Hvorfor tror du det var så lett for Saul å følge sin egen dømmekraft selv om han husket Guds klare instruks? Hvorfor stoler vi på oss selv enda vi vet vi er skrøpelige og har ufullkommen kunnskap? Hva kan vi gjøre for å lære å stole mer på Herrens bud enn på oss selv?`


text:
using System.Windows;
using System.Windows.Controls;

namespace Gold_Client.View
{
    public partial class LoginControl
    {
        public LoginControl()
        {
            //LoginPresenter presenter = new LoginPresenter();
            //DataContext = presenter;
            InitializeComponent();
        }

        private void PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (DataContext != null)
            { ((dynamic)DataContext).SecurePassword = ((PasswordBox)sender).SecurePassword; }
        }
    }
}


text:
<?php

class Mage_Index_Block_Adminhtml_Notifications extends Mage_Adminhtml_Block_Template
{
    /**
     * Get array of index names which require data reindex
     *
     * @return array
     */
    public function getProcessesForReindex()
    {
        $res = array();
        $processes = Mage::getSingleton('index/indexer')->getProcessesCollection()->addEventsStats();
        /** @var $process Mage_Index_Model_Process */
        foreach ($processes as $process) {
            if (($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX
                || $process->getEvents() > 0) && $process->getIndexer()->isVisible()
            ) {
                $res[] = $process->getIndexer()->getName();
            }
        }
        return $res;
    }

    /**
     * Get index management url
     *
     * @return string
     */
    public function getManageUrl()
    {
        return $this->getUrl('adminhtml/process/list');
    }

    /**
     * ACL validation before html generation
     *
     * @return string
     */
    protected function _toHtml()
    {
        if (Mage::getSingleton('admin/session')->isAllowed('system/index')) {
            return parent::_toHtml();
        }
        return '';
    }
}


text:
import * as types from './../consts/actionTypes';

export function switchPeriod(period) {
  return {
    type: types.SWITCH_PERIOD,
    period,
  };
}

export function addStock(target) {
  return {
    type: types.ADD_STOCK,
    target,
  };
}

export function fetchLatestRequest(target) {
  return {
    type: types.FETCH_LATEST_REQUEST,
    target,
  };
}

export function fetchLatestSucceeded(response) {
  return {
    type: types.FETCH_LATEST_SUCCEEDED,
    response,
    // receivedAt: Date.now(),
  };
}

export function fetchLatestFailed(error) {
  return {
    type: types.FETCH_LATEST_FAILED,
    error,
    // receivedAt: Date.now(),
  };
}

export function fetchTrendSucceeded(response) {
  return {
    type: types.FETCH_TREND_SUCCEEDED,
    response,
    receivedAt: Date.now(),
  };
}

export function fetchTrendFailed(error) {
  return {
    type: types.FETCH_TREND_FAILED,
    error,
    receivedAt: Date.now(),
  };
}

export function loadFocus(persisted) {
  return {
    type: types.LOAD_FOCUS,
    data: persisted,
  };
}

export function addFocus(target) {
  return {
    type: types.ADD_FOCUS,
    target,
  };
}

export function removeFocus(target) {
  return {
    type: types.REMOVE_FOCUS,
    target,
  };
}

export function openSearchbar() {
  return {
    type: types.OPEN_SEARCHBAR,
  };
}

export function closeSearchbar() {
  return {
    type: types.CLOSE_SEARCHBAR,
  };
}

export function searchFor(word) {
  return {
    type: types.SEARCH_FOR,
    word,
  };
}

export function gotSearchResult(result) {
  return {
    type: types.GOT_SEARCHED_RESULT,
    result,
  };
}


text:
> Comment component of Kreta

[![SensioLabsInsight](https://insight.sensiolabs.com/projects/c23fe5fc-20f5-435c-9f0d-172d6ff87328/mini.png)](https://insight.sensiolabs.com/projects/c23fe5fc-20f5-435c-9f0d-172d6ff87328)
[![Build Status](https://travis-ci.org/kreta-plugins/Comment.svg?branch=master)](https://travis-ci.org/kreta-plugins/Comment)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/kreta-plugins/Comment/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/kreta-plugins/Comment/?branch=master)
[![Total Downloads](https://poser.pugx.org/kreta/comment/downloads)](https://packagist.org/packages/kreta/comment)
[![Latest Stable Version](https://poser.pugx.org/kreta/comment/v/stable.svg)](https://packagist.org/packages/kreta/comment)
[![Latest Unstable Version](https://poser.pugx.org/kreta/comment/v/unstable.svg)](https://packagist.org/packages/kreta/comment)

##Tests
This library is completely tested by **[PHPSpec][1], SpecBDD framework for PHP**.

Because you want to contribute or simply because you want to throw the tests, you have to type the following command
in your terminal.
```
$ vendor/bin/phpspec run -fpretty
```
##Contributing
This library follows PHP coding standards, so pull requests need to execute the Fabien Potencier's [PHP-CS-Fixer][5]
and Marc Morera's [PHP-Formatter][6]. Furthermore, if the PR creates some not-PHP file remember that you have to put
the license header manually. In order to simplify we provide a Composer script that wraps all the commands related with
this process.
```bash
$ composer run-script cs
```

There is also a policy for contributing to this project. Pull requests must be explained step by step to make the
review process easy in order to accept and merge them. New methods or code improvements must come paired with
[PHPSpec][1] tests.

If you would like to contribute it is a good point to follow Symfony contribution standards, so please read the
[Contributing Code][2] in the project documentation. If you are submitting a pull request, please follow the guidelines
in the [Submitting a Patch][3] section and use the [Pull Request Template][4].

If you have any doubt or maybe you want to share some opinion, you can use our **Gitter chat**.

[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kreta/kreta?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

##Credits
Kreta comment is created by:
>
**@benatespina** - [benatespina@gmail.com](mailto:benatespina@gmail.com)<br>
**@gorkalaucirica** - [gorka.lauzirika@gmail.com](mailto:gorka.lauzirika@gmail.com)

##Licensing Options
[![License](https://poser.pugx.org/kreta/comment/license.svg)](https://github.com/kreta-plugins/Comment/blob/master/LICENSE)

[1]: http://www.phpspec.net/
[2]: http://symfony.com/doc/current/contributing/code/index.html
[3]: http://symfony.com/doc/current/contributing/code/patches.html#check-list
[4]: http://symfony.com/doc/current/contributing/code/patches.html#make-a-pull-request
[5]: http://cs.sensiolabs.org/
[6]: https://github.com/mmoreram/php-formatter


text:
from lib.common import helpers

class Module:

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Invoke-Inveigh',

            'Author': ['Kevin Robertson'],

            'Description': ('Inveigh is a Windows PowerShell LLMNR/NBNS spoofer/man-in-the-middle tool.'),

            'Background' : True,

            'OutputExtension' : None,

            'NeedsAdmin' : True,

            'OpsecSafe' : True,

            'MinPSVersion' : '2',

            'Comments': [
                'https://github.com/Kevin-Robertson/Inveigh'
            ]
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                'Description'   :   'Agent to run module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'IP' : {
                'Description'   :   'Specific local IP address for listening. This IP address will also be used for LLMNR/NBNS spoofing if the SpooferIP parameter is not set.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferIP' : {
                'Description'   :   'Specific IP address for LLMNR/NBNS spoofing. This parameter is only necessary when redirecting victims to a system other than the Inveigh host.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferHostsReply' : {
                'Description'   :   'Comma separated list of requested hostnames to respond to when spoofing with LLMNR and NBNS.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferHostsIgnore' : {
                'Description'   :   'Comma separated list of requested hostnames to ignore when spoofing with LLMNR and NBNS.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferIPsReply' : {
                'Description'   :   'Comma separated list of source IP addresses to respond to when spoofing with LLMNR and NBNS.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferIPsIgnore' : {
                'Description'   :   'Comma separated list of source IP addresses to ignore when spoofing with LLMNR and NBNS.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SpooferRepeat' : {
                'Description'   :   'Enable/Disable repeated LLMNR/NBNS spoofs to a victim system after one user challenge/response has been captured (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'LLMNR' : {
                'Description'   :   'Enable/Disable LLMNR spoofing (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'LLMNRTTL' : {
                'Description'   :   'Custom LLMNR TTL in seconds for the response packet.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'NBNS' : {
                'Description'   :   'Enable/Disable NBNS spoofing (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'NBNSTTL' : {
                'Description'   :   'Custom NBNS TTL in seconds for the response packet.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'NBNSTypes' : {
                'Description'   :   'Comma separated list of NBNS types to spoof.',
                'Required'      :   False,
                'Value'         :   '00,20'
            },
            'HTTP' : {
                'Description'   :   'Enable/Disable HTTP challenge/response capture (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'HTTPAuth' : {
                'Description'   :   'HTTP server authentication type. This setting does not apply to wpad.dat requests (Anonymous,Basic,NTLM).',
                'Required'      :   False,
                'Value'         :   'NTLM'
            },
            'HTTPBasicRealm' : {
                'Description'   :   'Realm name for Basic authentication. This parameter applies to both HTTPAuth and WPADAuth.',
                'Required'      :   False,
                'Value'         :   'IIS'
            },
            'HTTPResponse' : {
                'Description'   :   'String or HTML to serve as the default HTTP response. This response will not be used for wpad.dat requests. Do not wrap in quotes and use PowerShell character escapes where necessary.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'WPADAuth' : {
                'Description'   :   'HTTP server authentication type for wpad.dat requests. Setting to Anonymous can prevent browser login prompts (Anonymous,Basic,NTLM).',
                'Required'      :   False,
                'Value'         :   'NTLM'
            },
            'WPADEmptyFile' : {
                'Description'   :   'Enable/Disable serving a proxyless, all direct, wpad.dat file for wpad.dat requests (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'WPADIP' : {
                'Description'   :   'Proxy server IP to be included in a basic wpad.dat response for WPAD enabled browsers. This parameter must be used with WPADPort.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'WPADPort' : {
                'Description'   :   'Proxy server port to be included in a basic wpad.dat response for WPAD enabled browsers. This parameter must be used with WPADIP.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'WPADDirectHosts' : {
                'Description'   :   'Comma separated list of hosts to list as direct in the wpad.dat file. Listed hosts will not be routed through the defined proxy. Add the Empire host to avoid catching Empire HTTP traffic.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'SMB' : {
                'Description'   :   'Enable/Disable SMB challenge/response capture (Y/N).',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'Challenge' : {
                'Description'   :   'Specific 16 character hex NTLM challenge for use with the HTTP listener. If left blank, a random challenge will be generated for each request.',
                'Required'      :   False,
                'Value'         :   ''
            },
            'MachineAccounts' : {
                'Description'   :   'Enable/Disable showing NTLM challenge/response captures from machine accounts (Y/N).',
                'Required'      :   False,
                'Value'         :   'N'
            },
            'ConsoleStatus' : {
                'Description'   :   'Interval in minutes for auto-displaying all unique captured hashes and credentials. (Y/N)',
                'Required'      :   False,
                'Value'         :   ''
            },
            'ConsoleUnique' : {
                'Description'   :   'Enable/Disable displaying challenge/response hashes for only unique IP, domain/hostname, and username combinations.',
                'Required'      :   False,
                'Value'         :   'Y'
            },
            'RunTime' : {
                'Description'   :   'Run time duration in minutes.',
                'Required'      :   False,
                'Value'         :   ''
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def generate(self):

        # read in the common module source code
        moduleSource = self.mainMenu.installPath + "/data/module_source/collection/Invoke-Inveigh.ps1"

        try:
            f = open(moduleSource, 'r')
        except:
            print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
            return ""

        moduleCode = f.read()
        f.close()

        script = moduleCode

        # set defaults for Empire
        script += "\n" + 'Invoke-Inveigh -Tool "2" '

        for option,values in self.options.iteritems():
            if option.lower() != "agent":
                if values['Value'] and values['Value'] != '':
                    if values['Value'].lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        if "," in str(values['Value']):
                            quoted = '"' + str(values['Value']).replace(',', '","') + '"'
                            script += " -" + str(option) + " " + quoted
                        else:
                            script += " -" + str(option) + " \"" + str(values['Value']) + "\""

        return script


text:
var raf = require('raf');

var jobs = [];
var id = null;

module.exports = queue;

// Queue asynchronous workers to fire on the next available animation frame.
function queue(job) {
  jobs.push(job);

  // If the id is set there is a job execution happening, don't invoke next in
  // this case, it will be called when the currently executing job is done.
  if (!id) {
    id = raf(next);
  }

}

// Call the next job in the queue (if available).
function next() {
  if (jobs.length === 0) {
    // Allows the next call to `queue(...)` to kick off the newly added job.
    id = null;
    return;
  }

  var job = jobs.shift();
  job(done);

  function done(err) {
    if (err) {
      throw err;
    }

    id = raf(next);
  }
}


text:
title: Set up a Client Credentials Grant using the Management API
description: How to set up a Client Credentials Grant using the Management API.
crews: crew-2
---

# Set up a Client Credentials Grant using the Management API

If you do not want to use the Auth0 Dashboard to create a Resource Server or you need to create one programmatically, you can use our Management API v2.

You will need the following:

- A Management APIv2 token with the appropriate scopes. For details on how to get one refer to [The Auth0 Management APIv2 Token](/api/management/v2/tokens).
- The Client information (`Client_Id` and `Client_Secret`) for the Non Interactive Client that should already be created and visible in your [Auth0 dashboard](${manage_url}/#/clients).

## 1. Create your Resource Server

Let's start by creating the Resource Server. This is the entity that represents the API that you want to issue access tokens for, identified by a friendly name and a URN identifier.

The following restrictions apply to the identifier:
- It must be a valid URN.
- It cannot be modified after creation.
- It must be unique throughout your tenant.

We recommend using your public API endpoint as an identifier.

To create a Resource Server send a `POST` request to the [/resource-servers endpoint of the Management APIv2](/api/management/v2#!/Resource_Servers/post_resource_servers) with an `access_token` that has the resource server scope (`scope:resource_server`).

The following example uses _"My Sample API"_ as the name and _"https://my-api-uri"_ as the identifier.

```har
{
  "method": "POST",
  "url": "https://${account.namespace}/api/v2/resource-servers",
  "headers": [
    { "name": "Content-Type", "value": "application/json" },
    { "name": "authorization", "value": "Bearer Auth0_MGMT_API_ACCESS_TOKEN" }
  ],
  "postData": {
    "mimeType": "application/json",
    "text": "{\"name\":\"My Sample API\",\"identifier\": \"https://my-api-urn\",\"signing_alg\": \"RS256\",\"scopes\": [{ \"value\": \"sample-scope\", \"description\": \"Description for Sample Scope\"}]}"
  }
}
```

**NOTE:** You can include multiple scopes. This array represents the universe of scopes your API will support. You can modify this later by issuing a `PATCH` operation.

Sample response:

```json
{
    "id": "56f0131ffdf1c311694f4cc7",
    "name": "My Sample API",
    "identifier": "https://my-api-urn",
    "scopes": [
        {
            "value": "sample-scope",
            "description": "Description for Sample Scope"
        }
    ],
    "signing_alg": "RS256",
    "signing_secret": "FF1prn9UxZotnolsDVwEJhqqyRmwdSu5",
    "token_lifetime": 86400
}
```

Note the following:
- The `identifier` value (`https://my-api-urn`) will be used from now on as the `audience` for any OAuth 2.0 grant, that wants to access this API.
- The algorithm that your API will use to sign tokens will be the __RS256__ (`signing_alg`).
- The secret used to sign the tokens will be `FF1prn9UxZotnolsDVwEJhqqyRmwdSu5` (`signing_secret`).
- The generated tokens will expire after `86400` seconds (`token_lifetime`).

## 2. Authorize the Client

Now that the API and the Client are defined in Auth0, you can create a trust relationship between them. To do so, authorize the Client to access the API, while defining the scopes that should be given to the Client (meaning the actions the Client will be able to perform on the API).

To authorize your Client send a `POST` request to the [/client-grants endpoint of the Management APIv2](/api/management/v2#!/Client_Grants/post_client_grants) with an `access_token` that has the create client grants scope (`create:client_grantss`).

The following example authorizes the Client with Id `${account.clientId}`, to access the API with Identifier `https://my-api-urn`, while granting the scope `sample-scope`.

```har
{
  "method": "POST",
  "url": "https://${account.namespace}/api/v2/client-grants",
  "headers": [
    { "name": "Content-Type", "value": "application/json" },
    { "name": "authorization", "value": "Bearer Auth0_MGMT_API_ACCESS_TOKEN" }
  ],
  "postData": {
    "mimeType": "application/json",
    "text": "{\"client_id\": \"${account.clientId}\",\"audience\": \"https://my-api-urn\",\"scope\":[\"sample-scope\"]}"
  }
}
```

Sample response:

```json
{
    "id": "cgr_JGa6ZckLjnt60rWe",
    "client_id": "${account.clientId}",
    "audience": "https://test-api",
    "scope": [
        "sample-scope"
    ]
}
```

## 3. That's it!

Now that all the elements are in place, you can request access tokens for your API from Auth0.

For details on how to do so, refer to [Execute a Client Credentials Grant](/api-auth/tutorials/client-credentials).


text:
/*
 * Jooel Korpi <jooel.korpi@solita.fi> 11.3.2015
 */
"use strict";
var network = angular.module("network", []);

network.factory("Neo4j", ["$http", "config", function ($http, config) {
        return {
            /*
             * $param query = Query statement
             * $param successCB = Callback for success
             */
            singleQuery: function (query, successCB, errorCB, content) {
                var conf = {
                    method: "POST",
                    url: "http://" + config.server + ":" + config.port + "/db/data/transaction/commit",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": "Basic " + config.authToken
                    },
                    data: {"statements": [{"statement": query,
                                "resultDataContents": content}]}
                };
                $http(conf).success(successCB).error(errorCB);
            },
            // Trying to get simple paths algorithm working, but at the moment it
            // doesn't work
            allSimplePaths: function (origin, target, depth, successCB, errorCB) {
                var conf = {
                    method: "POST",
                    url: "http://" + config.server + ":" + config.port + "/db/data/node/" + origin + "/paths",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": "Basic " + config.authToken
                    },
                    data: {
                        "to": "http://" + config.server + ":" + config.port + "/db/data/node/" + target,
                        "max_depth": depth,
                        "relationships": {
                            "type": "TARGET",
                            "direction": "out"
                        },
                        "algorithm": "allSimplePaths"
                    }
                };
                $http(conf).success(successCB).error(errorCB);
            },
            /*
             * $param labels = String array of labels to be added
             * $param attrs = Array of objects which have key and value attributes
             * $param success = Callback for success
             * $param error = Callback for error
             */
            createNode: function (labels, attrs, success, error) {
                var query = "CREATE (n";
                labels.forEach(function (label) {
                    query += ":" + label;
                });
                query += "{";
                attrs.forEach(function (attr) {
                    query += attr.key + ":'" + attr.value + "',";
                });
                if (query.substr(query.length - 1, 1) === ",") {
                    query = query.substr(0, query.length - 1);
                }
                query += "}) RETURN id(n)";
                this.singleQuery(query, success, error);
            },
            createLink: function (type, source, target, attrs, success, error) {
                var query = "MATCH n, m WHERE id(n) = " + source + " AND id(m) = " + target +
                        " WITH n,m CREATE (n)-[r:" + type;
                query += "{";
                attrs.forEach(function (attr) {
                    query += attr.key + ":'" + attr.value + "',";
                });
                if (query.substr(query.length - 1, 1) === ",") {
                    query = query.substr(0, query.length - 1);
                }
                query += "}]->(m) RETURN id(r)";
                this.singleQuery(query, success, error);
            },
            // Helper functions for per line retrieval of nodes and links
            M: function (mapping, subject) {
                return "{id: id(" + mapping + "),labels: labels(" + mapping + "),node: " + mapping + ", subject:" + subject + ".subjectArea}";
            },
            T: function (table) {
                return "{id: id(" + table + "),labels: labels(" + table + "),node: " + table + "}";
            },
            L: function (link) {
                return "{id: id(" + link + "),type: type(" + link + "), startNode: id(startNode(" + link + ")), endNode: id(endNode(" + link + "))}";
            },
            // Get paths between two nodes. Either back or forward connections
            paths: function (mode, nodeOrigin, nodeChild, success, error) {
                var query = "";
                if (mode === "TO") {
                    query = "MATCH p=n-[*..8]->m WHERE id(n)=" + nodeOrigin + " AND id(m)=" + nodeChild + " AND NONE (r in relationships(p) WHERE type(r)='LOOKUP') AND NONE (n IN nodes(p) WHERE size(filter(x IN nodes(p) WHERE n = x))> 1) RETURN p";
                } else if (mode === "FROM") {
                    query = "MATCH p=n<-[*..8]-m WHERE id(n)=" + nodeOrigin + " AND id(m)=" + nodeChild + " AND NONE (r in relationships(p) WHERE type(r)='LOOKUP') AND NONE (n IN nodes(p) WHERE size(filter(x IN nodes(p) WHERE n = x))> 1) RETURN p";
                } else {
                    console.log("wrong mode: " + mode);
                }
                this.singleQuery(query, success, error, ["graph"]);

            }
        };
    }]);


text:
require 'json'
require_dependency "#{Rails.root}/lib/wiki_api"

#= This class is for getting data directly from the Wikimedia Commons API.
class Commons
  def initialize(query, update_service = nil)
    @query = query
    @update_service = update_service
  end
  ###################
  # Request methods #
  ###################

  # Get user contribution data that corresponds to new file uploads.
  def self.get_uploads(users, start_date: nil, end_date: nil, update_service: nil)
    upload_query = build_upload_query(users, start_date, end_date)
    uploads = new(upload_query, update_service).fetch_all_uploads
    uploads
  end

  # Get data about how files are being used across Wikimedia sites.
  def self.get_usages(commons_uploads, update_service: nil)
    usage_query = build_usage_query commons_uploads
    usages = new(usage_query, update_service).get_image_data('globalusage', 'gucontinue')
    usages
  end

  def self.find_missing_files(commons_uploads)
    missing_query = build_info_query(commons_uploads)
    pages = new(missing_query).get_image_data('pageid', '')
    missing_pages = pages.select { |page| page['missing'] }
    missing_page_ids = missing_pages.map { |page| page['pageid'] }
    commons_uploads.select { |file| missing_page_ids.include? file.id }
  end

  def self.get_urls(commons_uploads, update_service: nil)
    url_query = build_url_query commons_uploads
    file_urls = new(url_query, update_service).get_image_data('imageinfo', 'iicontinue')
    file_urls
  end

  ##################
  # Query builders #
  ##################

  def self.build_upload_query(users, start_date, end_date)
    usernames = users.map(&:username)
    upload_query = { list: 'usercontribs',
                     ucuser: usernames,
                     ucnamespace: 6, # File: namespace
                     ucshow: 'new', # New pages ~= new uploads
                     uclimit: 500, # 500 is max for non-bots
                     continue: '' }
    # The Mediawiki API starts from the 'ucstart' and works backwards to 'ucend'
    # so we put the start_date for ucend and vice versa.
    upload_query[:ucend] = start_date.strftime('%Y%m%d%H%M%S') if start_date
    upload_query[:ucstart] = end_date.strftime('%Y%m%d%H%M%S') if end_date
    upload_query
  end

  def self.build_usage_query(commons_uploads)
    file_ids = commons_uploads.map(&:id)
    usage_query = { prop: 'globalusage',
                    pageids: file_ids,
                    gulimit: 500, # 500 is max for non-bots
                    gufilterlocal: 'true', # Don't return local Commons usage
                    guprop: 'namespace', # Fetch NS for each usage
                    continue: '' }
    usage_query
  end

  def self.build_info_query(commons_uploads)
    file_ids = commons_uploads.map(&:id)
    info_query = { pageids: file_ids,
                   continue: '' }
    info_query
  end

  def self.build_url_query(commons_uploads)
    file_ids = commons_uploads.map(&:id)
    url_query = { prop: 'imageinfo',
                  iiprop: 'url',
                  iiurlheight: 480,
                  pageids: file_ids,
                  iilimit: 50, # 50 is max when iiurlheight is used.
                  continue: '' }
    url_query
  end

  ##########################
  # Instance query methods #
  ##########################

  def fetch_all_uploads
    @uploads = []
    @continue = true
    until @continue.nil?
      response = api_get
      return @uploads unless response # fall back gracefully if the query fails
      @uploads += response.data['usercontribs']
      @continue = response['continue'] # nil if there is no continue
      @query['uccontinue'] = @continue['uccontinue'] if @continue
    end

    @uploads
  end

  def get_image_data(prop, continue_param)
    @continue_param = continue_param
    @prop = prop

    @image_data = []
    @continue = true
    until @continue.nil?
      response = api_get
      return @image_data if response.blank?
      parse_image_data_and_update_continue(response)
    end
    @image_data
  end

  def parse_image_data_and_update_continue(response)
    results = response.data['pages']
    # Account for the different format returned when only a single, missing
    # page is queried, which looks like: [{"pageid"=>0, "missing"=>""}]
    results = results.values unless results.is_a?(Array)
    results.each do |r|
      @image_data << r if r[@prop].present?
    end
    @continue = response['continue'] # nil if there is no continue
    return if @continue.nil?

    # Workaround for MediaWiki bug where continue runs the same query infinitely
    # https://phabricator.wikimedia.org/T101532
    @continue = nil if @query[@continue_param] == @continue[@continue_param]

    @query[@continue_param] = @continue[@continue_param] if @continue
  end

  ###################
  # Private methods #
  ###################
  private

  def api_get
    WikiApi.new(CommonsWiki.new, @update_service).query(@query)
  end
end