text:
package com.intellij.vcs.log.ui.actions;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi;
import com.intellij.util.Function;
import com.intellij.util.IconUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.VcsLogUi;
import com.intellij.vcs.log.graph.PermanentGraph;
import icons.VcsLogIcons;
import org.jetbrains.annotations.NotNull;

import java.awt.*;

public class IntelliSortChooserPopupAction extends DumbAwareAction {
  public IntelliSortChooserPopupAction() {
    super("IntelliSort", "Change IntelliSort Type", IconUtil.flip(VcsLogIcons.Branch, false));
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    final VcsLogUi logUI = e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI);

    ActionGroup settingsGroup =
      new DefaultActionGroup(ContainerUtil.map(PermanentGraph.SortType.values(), new Function<PermanentGraph.SortType, AnAction>() {
        @Override
        public AnAction fun(PermanentGraph.SortType sortType) {
          return new SelectIntelliSortTypeAction(logUI, sortType);
        }
      }));

    ListPopup popup = JBPopupFactory.getInstance()
      .createActionGroupPopup(null, settingsGroup, e.getDataContext(), JBPopupFactory.ActionSelectionAid.MNEMONICS, true,
                              ToolWindowContentUi.POPUP_PLACE);
    Component component = e.getInputEvent().getComponent();
    if (component instanceof ActionButtonComponent) {
      popup.showUnderneathOf(component);
    }
    else {
      popup.showInCenterOf(component);
    }
  }

  @Override
  public void update(AnActionEvent e) {
    super.update(e);
    VcsLogUi logUI = e.getData(VcsLogDataKeys.VCS_LOG_UI);
    e.getPresentation().setEnabled(logUI != null);
    if (logUI != null) {
      String description = "IntelliSort: " + logUI.getBekType().getName();
      e.getPresentation().setDescription(description);
      e.getPresentation().setText(description);
    }
  }

  private static class SelectIntelliSortTypeAction extends ToggleAction implements DumbAware {
    private final PermanentGraph.SortType mySortType;
    private final VcsLogUi myUI;

    public SelectIntelliSortTypeAction(VcsLogUi logUi, PermanentGraph.SortType sortType) {
      super(sortType.getName(), sortType.getDescription() + ".", null);
      myUI = logUi;
      mySortType = sortType;
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
      super.update(e);
      e.getPresentation().setEnabled(myUI.areGraphActionsEnabled());
    }

    @Override
    public boolean isSelected(AnActionEvent e) {
      return myUI.getBekType().equals(mySortType);
    }

    @Override
    public void setSelected(AnActionEvent e, boolean state) {
      if (state) {
        myUI.setBekType(mySortType);
      }
    }
  }
}


text:
namespace More.Windows.Interactivity
{
    using More.Composition;
    using More.Windows.Input;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Windows;

    /// <summary>
    /// Represents an <see cref="System.Windows.Interactivity.TriggerAction">interactivity action</see> that can be used to show the <see cref="Interaction">interaction</see>
    /// from an <see cref="IInteractionRequest.Requested">interaction request</see> in a <see cref="Window">view</see>.
    /// </summary>
    public partial class WindowAction : System.Windows.Interactivity.TriggerAction<FrameworkElement>
    {
        readonly Dictionary<Type, Delegate> attachMethods = new Dictionary<Type, Delegate>();

        /// <summary>
        /// Gets the dependency property of the view name.
        /// </summary>
        /// <value>A <see cref="DependencyProperty"/> object.</value>
        public static readonly DependencyProperty ViewNameProperty =
            DependencyProperty.Register( nameof( ViewName ), typeof( string ), typeof( WindowAction ), new PropertyMetadata( (object) null ) );

        /// <summary>
        /// Gets the dependency property of the view <see cref="Type">type</see>.
        /// </summary>
        /// <value>A <see cref="DependencyProperty"/> object.</value>
        public static readonly DependencyProperty ViewTypeProperty =
            DependencyProperty.Register( nameof( ViewType ), typeof( Type ), typeof( WindowAction ), new PropertyMetadata( (object) null ) );

        /// <summary>
        /// Gets the dependency property indicating whether the view is modal.
        /// </summary>
        /// <value>A <see cref="DependencyProperty"/> object.</value>
        public static readonly DependencyProperty IsModalProperty =
            DependencyProperty.Register( nameof( IsModal ), typeof( bool ), typeof( WindowAction ), new PropertyMetadata( true ) );

        /// <summary>
        /// Gets the dependency property for the view <see cref="Style">style</see>.
        /// </summary>
        /// <value>A <see cref="DependencyProperty"/> object.</value>
        public static readonly DependencyProperty StyleProperty =
            DependencyProperty.Register( nameof( Style ), typeof( Style ), typeof( WindowAction ), new PropertyMetadata( (object) null ) );

        /// <summary>
        /// Gets the dependency property for the view <see cref="DataTemplate">content template</see>.
        /// </summary>
        /// <value>A <see cref="DependencyProperty"/> object.</value>
        public static readonly DependencyProperty ContentTemplateProperty =
            DependencyProperty.Register( nameof( ContentTemplate ), typeof( DataTemplate ), typeof( WindowAction ), new PropertyMetadata( (object) null ) );

        /// <summary>
        /// Gets or sets a value indicating whether the provided cancel command is bound to the window close button.
        /// </summary>
        /// <value>True if the provided <see cref="Interaction.CancelCommand">cancel command</see> is
        /// bound to the window close button. The default value is <c>false</c>.</value>
        /// <remarks>The associated <see cref="Window">window</see> is usually closed after any command is executed. If an action is
        /// conditional or should be cancelled, the command should not raise the <see cref="INotifyCommandChanged.Executed"/> event.
        /// In the scenario where a user clicks the standard window close button, no command is executed by default. To handle that
        /// scenario, set this property to <c>true</c> in order to automatically bind the
        /// <see cref="Interaction.CancelCommand">cancel command</see> to the
        /// <see cref="WindowCloseBehavior.CloseCommand"/> which will be applied to the underlying <see cref="Window">window</see>
        /// <see cref="System.Windows.Interactivity.BehaviorCollection">behaviors</see>.</remarks>
        public bool BindCancelToClose { get; set; }

        /// <summary>
        /// Gets or sets the name of the view the action shows.
        /// </summary>
        /// <value>The view name associated with the <see cref="Window">window</see> that the action shows.</value>
        public string ViewName
        {
            get => (string) GetValue( ViewNameProperty );
            set => SetValue( ViewNameProperty, value );
        }

        /// <summary>
        /// Gets or sets the type of window the action shows.
        /// </summary>
        /// <value>The view <see cref="Type">type</see> of the <see cref="Window">window</see> that the action shows.</value>
        public Type ViewType
        {
            get => (Type) GetValue( ViewTypeProperty );
            set => SetValue( ViewTypeProperty, value );
        }

        /// <summary>
        /// Gets or sets a value indicating whether the action shows a modal window.
        /// </summary>
        /// <value>True if the action shows a modal <see cref="Window">window</see>; otherwise, false to show
        /// a modeless <see cref="Window">window</see>. The default value is true.</value>
        public bool IsModal
        {
            get => (bool) GetValue( IsModalProperty );
            set => SetValue( IsModalProperty, value );
        }

        /// <summary>
        /// Gets or sets the style applied to the window shown by the action.
        /// </summary>
        /// <value>The <see cref="Style">style</see> applied to the <see cref="Window">window</see>
        /// shown by the action.</value>
        public Style Style
        {
            get => (Style) GetValue( StyleProperty );
            set => SetValue( StyleProperty, value );
        }

        /// <summary>
        /// Gets or sets the content template applied to the window shown by the action.
        /// </summary>
        /// <value>The <see cref="DataTemplate">content template</see> applied to the
        /// <see cref="Window">window</see> shown by the action.</value>
        public DataTemplate ContentTemplate
        {
            get => (DataTemplate) GetValue( ContentTemplateProperty );
            set => SetValue( ContentTemplateProperty, value );
        }

        /// <summary>
        /// Creates the window used by the action.
        /// </summary>
        /// <returns>A new <see cref="Window"/> object or null if <see cref="ViewType"/> is null.</returns>
        /// <remarks>If the <see cref="Window">window</see> specified by the <see cref="ViewType">window type</see>
        /// is a composed <see cref="Window">window</see>, the default implementation will first use the
        /// <see cref="ServiceProvider.Current">service provider</see> to retrieve it.  If the view is not found,
        /// then the fallback method will be <see cref="Activator.CreateInstance(Type)"/>.</remarks>
        protected virtual Window CreateWindow()
        {
            Contract.Ensures( Contract.Result<Window>() != null );

            var window = default( Window );

            if ( ViewType == null )
            {
                window = new Window();
            }
            else
            {
                var services = ServiceProvider.Current;

                if ( !services.TryGetService( ViewType, out var view, ViewName ) )
                {
                    view = Activator.CreateInstance( ViewType );

                    if ( services.TryGetService( out ICompositionService composer ) )
                    {
                        composer.Compose( view );
                    }
                }

                if ( ( window = view as Window ) == null )
                {
                    window = new Window() { Content = view };
                }
            }

            window.Owner = Window.GetWindow( AssociatedObject );
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            return window;
        }

        static Delegate CreateAttachDelegate( Window window, Interaction interaction )
        {
            Contract.Requires( window != null );
            Contract.Requires( interaction != null );

            var viewType = window.GetType();
            var viewModelType = interaction.GetType();
            var interfaces = viewType.GetInterfaces();
            var view = typeof( IView<,> );
            var query = from i in interfaces
                        where i.IsGenericType && i.GetGenericTypeDefinition().Equals( view )
                        let vm = i.GetGenericArguments()[1]
                        where vm.IsAssignableFrom( viewModelType )
                        select i;
            var @interface = query.FirstOrDefault();

            if ( @interface == null )
            {
                return null;
            }

            var mapping = viewType.GetInterfaceMap( @interface );
            var delegateType = typeof( Action<,> ).MakeGenericType( viewType, viewModelType );
            var attach = mapping.TargetMethods[0].CreateDelegate( delegateType );

            return attach;
        }

        /// <summary>
        /// Invokes the triggered action.
        /// </summary>
        /// <param name="args">The <see cref="InteractionRequestedEventArgs"/> event data provided by the corresponding trigger.</param>
        [SuppressMessage( "Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Validated by a code contract." )]
        protected virtual void Invoke( InteractionRequestedEventArgs args )
        {
            Arg.NotNull( args, nameof( args ) );

            var window = CreateWindow();

            if ( window == null )
            {
                return;
            }

            if ( ContentTemplate != null )
            {
                window.ContentTemplate = ContentTemplate;
            }

            if ( Style != null )
            {
                window.Style = Style;
            }

            var attach = attachMethods.GetOrAdd( window.GetType(), () => CreateAttachDelegate( window, args.Interaction ) );

            if ( attach == null )
            {
                if ( window.Content == null )
                {
                    window.Content = args.Interaction;
                }

                if ( window.DataContext == null )
                {
                    window.DataContext = args.Interaction;
                }
            }
            else
            {
                attach.DynamicInvoke( window, args.Interaction );
            }

            using ( new CommandMediator( window, args.Interaction, BindCancelToClose ) )
            {
                if ( IsModal )
                {
                    window.ShowDialog();
                }
                else
                {
                    window.Show();
                }
            }
        }

        /// <summary>
        /// Invokes the triggered action.
        /// </summary>
        /// <param name="parameter">The parameter supplied from the corresponding trigger.</param>
        /// <remarks>This method is not meant to be called directly by your code.</remarks>
        protected sealed override void Invoke( object parameter )
        {
            if ( parameter is InteractionRequestedEventArgs args )
            {
                Invoke( args );
            }
        }

        /// <summary>
        /// Occurs when the action is about to be detached.
        /// </summary>
        protected override void OnDetaching()
        {
            attachMethods.Clear();
            base.OnDetaching();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import qs from 'qs';
import callApi from '../../util/apiCaller';
import { defaultRequestCatchHandler } from '../Error/ErrorActions';

// Export Constants
export const ADD_WIKI = 'ADD_WIKI';
export const ADD_WIKIS = 'ADD_WIKIS';
export const SET_UI_WIKI_FORM = 'SET_UI_WIKI_FORM';

// Export Actions
export function addWiki(wiki) {
  return { type: ADD_WIKI, wiki };
}

export function addWikis(wikis) {
  return { type: ADD_WIKIS, wikis };
}

export function setUIWikiForm(form) {
  return { type: SET_UI_WIKI_FORM, form };
}

export function fetchWiki(idOrName, rootWikiId = null) {
  return dispatch => {
    const uri = rootWikiId
      ? `rootWikis/${rootWikiId}/wikis/${encodeURIComponent(idOrName)}`
      : `wikis/${idOrName}`;
    return callApi(uri)
      .then(data => {
        dispatch(addWiki(data.wiki));
        return data.wiki;
      })
      .catch(err => defaultRequestCatchHandler(dispatch, err));
  };
}

export function fetchWikiByRouterProps(routerProps) {
  const { wikiId, wikiName, rootWikiId } = routerProps.match.params;
  if (rootWikiId) {
    return fetchWiki(wikiName, rootWikiId);
  } else {
    return fetchWiki(wikiId);
  }
}

export function fetchWikis(
  rootWikiId,
  {
    page = 1,
    limit = 10,
    sort = '-updatedAt',
    rootWikiGroupTree: rootWikiGroupTreeInput = 'all',
  } = {},
  reqConfig = {}
) {
  const rootWikiGroupTree = rootWikiGroupTreeInput.toJSON
    ? rootWikiGroupTreeInput.toJSON()
    : rootWikiGroupTreeInput;
  const query = qs.stringify({ page, limit, sort, rootWikiGroupTree });
  const url = `rootWikis/${rootWikiId}/wikis?${query}`;
  return dispatch => {
    return callApi(url, 'get', null, reqConfig)
      .then(body => {
        dispatch(addWikis(body.wikis));
        return body.wikis;
      })
      .catch(err => defaultRequestCatchHandler(dispatch, err));
  };
}

export function addWikiRequest(wiki) {
  return dispatch => {
    return callApi('wikis', 'post', { wiki })
      .then(body => {
        dispatch(addWiki(body.wiki));
        return body.wiki;
      })
      .catch(err => defaultRequestCatchHandler(dispatch, err));
  };
}

export function updateWikiRequest(wikiId, update) {
  return dispatch => {
    return callApi(`wikis/${wikiId}`, 'patch', update)
      .then(body => {
        dispatch(addWiki(body.wiki));
        return body.wiki;
      })
      .catch(err => defaultRequestCatchHandler(dispatch, err));
  };
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using VsChromium.Core.Linq;
using VsChromium.Core.Utility;

namespace VsChromium.Wpf {
  public class StringListViewModel : INotifyPropertyChanged {
    private readonly ObservableCollection<string> _items = new ObservableCollection<string>();
    private string _selectedItem;

    public StringListViewModel() {
    }

    public StringListViewModel(IEnumerable<string> initialItems) {
      initialItems.ForAll(_items.Add);
    }

    public ICollection<string> Items {
      get {
        return _items;
      }
    }

    public string SelectedItem {
      get { return _selectedItem; }
      set {
        if (_selectedItem == value)
          return;

        _selectedItem = value;
        OnPropertyChanged(ReflectionUtils.GetPropertyName(this, x => x.SelectedItem));
      }
    }

    /// <summary>
    /// Called when updating the data source. We add the item in the list of items
    /// if we don't have it yet.
    /// </summary>
    public string NewItem {
      set {
        if (string.IsNullOrEmpty(value)) {
          SelectedItem = null;
          return;
        }

        if (!_items.Contains(value))
          _items.Insert(0, value);

        SelectedItem = value;
      }
      get {
        return _selectedItem;
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName) {
      var handler = PropertyChanged;
      if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
  }
}


text:
package org.http4s
package dsl
package impl

import cats.{Applicative, Monad}
import org.http4s.headers._
import ResponseGenerator.addEntityLength
import cats.arrow.FunctionK

trait ResponseGenerator extends Any {
  def status: Status
}

private[impl] object ResponseGenerator {
  def addEntityLength[G[_]](entity: Entity[G], headers: Headers): Headers =
    entity.length match {
      case Some(l) => `Content-Length`.fromLong(l).fold(_ => headers, c => headers.put(c))
      case None => headers
    }
}

/**
  *  Helper for the generation of a [[org.http4s.Response]] which will not contain a body
  *
  * While it is possible to for the [[org.http4s.Response]] manually, the EntityResponseGenerators
  * offer shortcut syntax to make intention clear and concise.
  *
  * @example {{{
  * val resp: F[Response] = Status.Continue()
  * }}}
  */
trait EmptyResponseGenerator[F[_], G[_]] extends Any with ResponseGenerator {
  def apply(headers: Header*)(implicit F: Applicative[F]): F[Response[G]] =
    F.pure(Response(status, headers = Headers(headers.toList)))
}

/** Helper for the generation of a [[org.http4s.Response]] which may contain a body
  *
  * While it is possible to construct the [[org.http4s.Response]]
  * manually, the EntityResponseGenerators offer shortcut syntax to
  * make intention clear and concise.
  *
  * @example {{{
  * val resp: IO[Response] = Ok("Hello world!")
  * }}}
  */
trait EntityResponseGenerator[F[_], G[_]] extends Any with ResponseGenerator {
  def liftG: FunctionK[G, F]

  def apply(headers: Header*)(implicit F: Applicative[F]): F[Response[G]] =
    F.pure(Response[G](status, headers = Headers(`Content-Length`.zero :: headers.toList)))

  def apply[A](body: G[A])(implicit F: Monad[F], w: EntityEncoder[G, A]): F[Response[G]] =
    F.flatMap(liftG(body))(apply[A](_))

  def apply[A](body: A, headers: Header*)(
      implicit F: Applicative[F],
      w: EntityEncoder[G, A]): F[Response[G]] = {
    val h = w.headers ++ Headers(headers.toList)
    val entity = w.toEntity(body)
    F.pure(Response[G](status = status, headers = addEntityLength(entity, h), body = entity.body))
  }
}

/** Helper for the generation of a [[org.http4s.Response]] which may contain
  * a Location header and may contain a body.
  *
  * A 300, 301, 302, 303, 307 and 308 status SHOULD contain a Location header, which
  * distinguishes this from other `EntityResponseGenerator`s.
  */
trait LocationResponseGenerator[F[_], G[_]] extends Any with EntityResponseGenerator[F, G] {
  @deprecated("Use `apply(Location(location))` instead", "0.18.0-M2")
  def apply(location: Uri)(implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](
        status = status,
        headers = Headers(`Content-Length`.zero :: Location(location) :: Nil)))

  def apply(location: Location, headers: Header*)(implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](status, headers = Headers(`Content-Length`.zero :: location :: headers.toList)))

  def apply[A](location: Location, body: A, headers: Header*)(
      implicit F: Applicative[F],
      w: EntityEncoder[G, A]): F[Response[G]] = {
    val h = w.headers ++ Headers(location +: headers.toList)
    val entity = w.toEntity(body)
    F.pure(Response[G](status = status, headers = addEntityLength(entity, h), body = entity.body))
  }
}

/** Helper for the generation of a [[org.http4s.Response]] which must contain
  * a WWW-Authenticate header and may contain a body.
  *
  * A 401 status MUST contain a `WWW-Authenticate` header, which
  * distinguishes this from other `ResponseGenerator`s.
  */
trait WwwAuthenticateResponseGenerator[F[_], G[_]] extends Any with ResponseGenerator {
  @deprecated("Use ``apply(`WWW-Authenticate`(challenge, challenges)`` instead", "0.18.0-M2")
  def apply(challenge: Challenge, challenges: Challenge*)(
      implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](
        status = status,
        headers =
          Headers(`Content-Length`.zero :: `WWW-Authenticate`(challenge, challenges: _*) :: Nil)
      ))

  def apply(authenticate: `WWW-Authenticate`, headers: Header*)(
      implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](
        status,
        headers = Headers(`Content-Length`.zero :: authenticate :: headers.toList)))

  def apply[A](authenticate: `WWW-Authenticate`, body: A, headers: Header*)(
      implicit F: Applicative[F],
      w: EntityEncoder[G, A]): F[Response[G]] = {
    val h = w.headers ++ Headers(authenticate +: headers.toList)
    val entity = w.toEntity(body)
    F.pure(Response[G](status = status, headers = addEntityLength(entity, h), body = entity.body))
  }
}

/** Helper for the generation of a [[org.http4s.Response]] which must contain
  * an Allow header and may contain a body.
  *
  * A 405 status MUST contain an `Allow` header, which
  * distinguishes this from other `ResponseGenerator`s.
  */
trait AllowResponseGenerator[F[_], G[_]] extends Any with ResponseGenerator {

  def apply(allow: Allow, headers: Header*)(implicit F: Applicative[F]): F[Response[G]] =
    F.pure(Response[G](status, headers = Headers(`Content-Length`.zero +: allow +: headers.toList)))

  def apply[A](allow: Allow, body: A, headers: Header*)(
      implicit F: Applicative[F],
      w: EntityEncoder[G, A]): F[Response[G]] = {
    val h = w.headers ++ Headers(allow +: headers.toList)
    val entity = w.toEntity(body)
    F.pure(Response[G](status = status, headers = addEntityLength(entity, h), body = entity.body))
  }

}

/** Helper for the generation of a [[org.http4s.Response]] which must contain
  * a Proxy-Authenticate header and may contain a body.
  *
  * A 407 status MUST contain a `Proxy-Authenticate` header, which
  * distinguishes this from other `EntityResponseGenerator`s.
  */
trait ProxyAuthenticateResponseGenerator[F[_], G[_]] extends Any with ResponseGenerator {
  @deprecated("Use ``apply(`Proxy-Authenticate`(challenge, challenges)`` instead", "0.18.0-M2")
  def apply(challenge: Challenge, challenges: Challenge*)(
      implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](
        status = status,
        headers =
          Headers(`Content-Length`.zero :: `Proxy-Authenticate`(challenge, challenges: _*) :: Nil)
      ))

  def apply(authenticate: `Proxy-Authenticate`, headers: Header*)(
      implicit F: Applicative[F]): F[Response[G]] =
    F.pure(
      Response[G](
        status,
        headers = Headers(`Content-Length`.zero +: authenticate +: headers.toList)))

  def apply[A](authenticate: `Proxy-Authenticate`, body: A, headers: Header*)(
      implicit F: Applicative[F],
      w: EntityEncoder[G, A]): F[Response[G]] = {
    val h = w.headers ++ Headers(authenticate +: headers.toList)
    val entity = w.toEntity(body)
    F.pure(Response[G](status = status, headers = addEntityLength(entity, h), body = entity.body))
  }
}


text:
package com.changjiudai.servlet;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.changjiudai.trans.Cagent;

@WebServlet(name = "getImgCode", urlPatterns={"/getCode", "/login", "/exportXlsx"})
public class ImgCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(ImgCodeServlet.class);

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		logger.info("request.getServletPath(): " + request.getServletPath());

		if("/getCode".equals(request.getServletPath())){
			try {

				Cagent agent = new Cagent();
				agent.getImgCodeUrl();

				response.getWriter().write(agent.getImgCodePath());

				HttpSession session = request.getSession();
				logger.info("session get img: " + session);

				//override
				session.removeAttribute("agent");
				session.setAttribute("agent", agent);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("/login".equals(request.getServletPath())){
			HttpSession session = request.getSession();
			logger.info("session login: " + session);
			Cagent agent = (Cagent) session.getAttribute("agent");

			if(agent != null){

				String imgCode = request.getParameter("imgCode");
				String username = request.getParameter("username");
				String password = request.getParameter("password");

				logger.info("login get imgCode: " + imgCode);

				try {
					boolean result = agent.loginAndSign(username, password, imgCode);
					if(result){
						response.getWriter().write("login true");
					}else{
						response.getWriter().write("login false");
					}
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}else{
				logger.info("agent in session is null!!");
			}

		}else if("/exportXlsx".equals(request.getServletPath())){
			HttpSession session = request.getSession();
			logger.info("session login: " + session);
			Cagent agent = (Cagent) session.getAttribute("agent");

			if(agent != null){

				boolean result;
				try {
					result = agent.exportReport();
					if(result){
						response.getWriter().write(agent.getReportPath());
					}else{
						response.getWriter().write("export false");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}else{
				logger.info("agent in session is null!!");
			}

		}else{
			try {
				response.getWriter().write("other request...");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}


text:
CFLAGS += -g -O0 -std=gnu99 -fPIC -Wall -Wextra -Werror \
	  -Wno-unused-parameter -Wno-missing-field-initializers
CPPFLAGS += -I./ext

ifdef WITH_ASAN
	LDFLAGS += -fsanitize=address
	CFLAGS += -fsanitize=address
endif

ifdef WITH_COVERAGE
	LDFLAGS += -coverage
	CFLAGS += -coverage
endif

ifdef WITH_VALGRIND
	VALGRIND := valgrind --leak-check=full --show-reachable=yes --track-origins=yes
	TEST_OPT := --no-exec
endif

TARGETS = testaes testmodes testsha1 testsha2 testsha3 testsalsa20 \
	  testcurve25519 testpoly1305 testnorx testchacha20poly1305 \
	  testdrbg
all: $(TARGETS)

SOURCES = aes.o sha256.o sha512.o chash.o hmac.o pbkdf2.o modes.o eax.o \
	  gf128.o blockwise.o cmac.o salsa20.o chacha20.o curve25519.o \
	  gcm.o cbcmac.o ccm.o sha3.o sha1.o poly1305.o \
	  norx.o chacha20poly1305.o drbg.o ocb.o

testaes: $(SOURCES) testaes.o
testmodes: $(SOURCES) testmodes.o
testsha1: $(SOURCES) testsha1.o
testsha2: $(SOURCES) testsha2.o
testsha3: $(SOURCES) testsha3.o
testsalsa20: $(SOURCES) testsalsa20.o
testcurve25519: $(SOURCES) testcurve25519.o
testpoly1305: $(SOURCES) testpoly1305.o
testnorx: $(SOURCES) testnorx.o
testchacha20poly1305: $(SOURCES) testchacha20poly1305.o
testdrbg: $(SOURCES) testdrbg.o

clean:
	rm -f *.o *.pyc $(TARGETS) *.gcov *.gcda *.gcno

test: $(TARGETS)
	for x in $(TARGETS) ; do \
		echo "Running $$x" ; \
		$(VALGRIND) ./$$x $(TEST_OPT) ; \
	done

cover: test
	gcov *.c
	echo 'Lines with missing coverage:'
	grep '#####' *.gcov | grep -vE '(cutest|testutil).h.gcov'


text:
package org.apache.commons.io.filefilter;

import java.io.File;
import java.io.Serializable;

/**
 * A {@link IOFileFilter} that accepts all non-null
 * {@link File}s that exist
 * @see File#exists()
 * @author Lyor G.
 * @since Jun 5, 2013 3:25:17 PM
 */
public class ExistFileFilter extends AbstractFileFilter implements Serializable {
    private static final long serialVersionUID = -7946873743417468857L;
    public static final ExistFileFilter EXIST=new ExistFileFilter();
    public static final IOFileFilter NOT_EXIST=new NotFileFilter(EXIST);

    protected ExistFileFilter () {
        super();
    }

    @Override
    public boolean accept(File f) {
        if ((f == null) || (!f.exists())) {
            return false;   // debug breakpoint
        } else {
            return true;
        }
    }
}


text:
from __future__ import print_function
import itertools

# Registry Access, , access packages in the registry, internal
from yotta.lib import registry_access
from yotta.lib import settings
from yotta.lib import version

def addOptions(parser):
    parser.add_argument(
        'type', choices=['module', 'target', 'both'], nargs='?', default='both',
        help="What to search (software modules, build targets, or both)"
    )
    parser.add_argument(
        'query', type=str, nargs=1, default='',
        help='Search query text. All items that contain the specified words '+
             'in their description, name, or keywords will be returned.'
    )
    parser.add_argument(
        '-k', '--keyword', default=[], action='append', dest='kw',
        help='Additional keywords to constrain the search. All specified '+
             'keywords must exist in an item\'s keywords list for it to '+
             'be returned.'
    )
    parser.add_argument(
        '-l', '--limit', default=10, type=int,
        help='Limit the number of results returned.'
    )
    parser.add_argument(
        '-s', '--short', default=False, action='store_true',
        help='Use short output format.'
    )

def lengthLimit(s, l):
    if len(s) > l:
        return s[:l-3] + '...'
    return s

def formatResult(result, plain=False, short=False, indent=''):
    if not plain:
        # colorama, BSD 3-Clause license, cross-platform terminal colours, pip install colorama
        import colorama
        DIM    = colorama.Style.DIM       #pylint: disable=no-member
        BRIGHT = colorama.Style.BRIGHT    #pylint: disable=no-member
        NORMAL = colorama.Style.NORMAL    #pylint: disable=no-member
        GREEN  = colorama.Fore.GREEN      #pylint: disable=no-member
        BLUE   = colorama.Fore.BLUE       #pylint: disable=no-member
        RED    = colorama.Fore.RED        #pylint: disable=no-member
        YELLOW = colorama.Fore.YELLOW     #pylint: disable=no-member
        RESET  = colorama.Style.RESET_ALL #pylint: disable=no-member
    else:
        DIM = BRIGHT = NORMAL = GREEN = BLUE = RED = YELLOW = RESET = u''

    def formatKeyword(keyword):
        if keyword.endswith('official'):
            return BRIGHT + GREEN + keyword + RESET
        else:
            return BRIGHT + keyword + NORMAL

    def formatAuthor(author):
        if isinstance(author, dict):
            return author.get('name', '<name unknown>') + ' ' + author.get('email', '<email unknown')
        else:
            return author

    # --short:
    # module-name module-version: description description

    # not --short:
    # module-name module-version
    #    description description description
    #    keyword, keyword, keyword
    #    author, author

    v = version.Version(result['version'])
    if v.major() < 1:
        if v.minor() < 1:
            ver_string = RED + result['version'] + RESET
        else:
            ver_string = YELLOW + result['version'] + RESET
    else:
        ver_string = GREEN + result['version'] + RESET

    name_string = BRIGHT+result['name']+NORMAL

    if 'description' in result:
        description = result['description']
        description_colour = ''
    else:
        description = '<description missing>'
        description_colour = RED

    if short:
        description = description_colour + lengthLimit(description, 160).replace('\n', ' ') + RESET
    else:
        description = description_colour + lengthLimit(description, 800).replace('\n', indent+' ').rstrip('\n') + RESET

    if short:
        return indent+u'%s %s: %s%s' % (name_string, ver_string, description, RESET)
    else:
        r = indent+(u'%s %s:\n' % (name_string, ver_string)) +\
            indent+(u'    %s\n' % (description))
        if 'keywords' in result and result['keywords']:
            r += indent+(u'    %s\n' % (', '.join([formatKeyword(k) for k in result['keywords']])))

        if 'author' in result and result['author']:
            authors = [result['author']]
        elif 'maintainers' in result and len(result['maintainers']):
            authors = result['maintainers']
        else:
            authors = []
        if len(authors):
            r += indent+(u'    %s\n' % (DIM + (', '.join([formatAuthor(a) for a in authors])) + RESET))

        return r.rstrip('\n')

def execCommand(args, following_args):
    success = False
    for result in itertools.islice(registry_access.search(query=args.query, keywords=args.kw, registry=args.registry), args.limit):
        success= True
        if args.type == 'both' or args.type == result['type']:
            print(formatResult(result, args.plain, short=args.short))
    for repo in filter(lambda s: 'type' in s and s['type'] == 'registry', settings.get('sources') or []) :
        count = 0
        print('')
        print('additional results from %s:' % repo['url'])
        for result in itertools.islice(registry_access.search(query=args.query, keywords=args.kw, registry=repo['url']), args.limit):
            success= True
            if args.type == 'both' or args.type == result['type']:
                print(formatResult(result, args.plain, indent='  ', short=args.short))
    # exit status: success if we found something, otherwise fail
    return 0 if success else 1


text:
/** @author Brian Cavalier */
/** @author John Hann */

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

	// Sniff "best" async scheduling option
	// Prefer process.nextTick or MutationObserver, then check for
	// vertx and finally fall back to setTimeout

	/*jshint maxcomplexity:6*/
	/*global process,document,setTimeout,MutationObserver,WebKitMutationObserver*/
	var nextTick, MutationObs;

	if (typeof process !== 'undefined' && process !== null &&
		typeof process.nextTick === 'function') {
		nextTick = function(f) {
			process.nextTick(f);
		};

	} else if (MutationObs =
		(typeof MutationObserver === 'function' && MutationObserver) ||
		(typeof WebKitMutationObserver === 'function' && WebKitMutationObserver)) {
		nextTick = (function (document, MutationObserver) {
			var scheduled;
			var el = document.createElement('div');
			var o = new MutationObserver(run);
			o.observe(el, { attributes: true });

			function run() {
				var f = scheduled;
				scheduled = void 0;
				f();
			}

			return function (f) {
				scheduled = f;
				el.setAttribute('class', 'x');
			};
		}(document, MutationObs));

	} else {
		nextTick = (function(cjsRequire) {
			var vertx;
			try {
				// vert.x 1.x || 2.x
				vertx = cjsRequire('vertx');
			} catch (ignore) {}

			if (vertx) {
				if (typeof vertx.runOnLoop === 'function') {
					return vertx.runOnLoop;
				}
				if (typeof vertx.runOnContext === 'function') {
					return vertx.runOnContext;
				}
			}

			// capture setTimeout to avoid being caught by fake timers
			// used in time based tests
			var capturedSetTimeout = setTimeout;
			return function (t) {
				capturedSetTimeout(t, 0);
			};
		}(require));
	}

	return nextTick;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));


text:
package com.karuslabs.commons.world;

import org.bukkit.Location;
import org.bukkit.util.Vector;

import static com.karuslabs.commons.world.Vectors.rotate;

public abstract class BoundLocation {

    protected Location location;
    protected PathVector offset;
    protected boolean relative;

    public BoundLocation(BoundLocation location) {
        this(location.location.clone(), location.offset.clone(), location.relative);
    }

    public BoundLocation(Location location, PathVector offset, boolean relative) {
        this.location = location;
        this.offset = offset;
        this.relative = relative;
    }

    public void addOffset(Vector offset, float yaw, float pitch) {
        this.offset.add(offset);
        this.offset.yaw(yaw);
        this.offset.pitch(pitch);
        updateOffset();
    }

    public void updateOffset() {
        if (relative) {
            location.add(rotate(offset, location));

        } else {
            location.add(offset);
        }
    }

    public abstract boolean validate();

    public abstract void update();

    public void setDirection(Vector direction) {
        location.setDirection(direction);
        updateDirection();
    }

    public void updateDirection() {
        if (relative) {
            location.setYaw(location.getYaw() + offset.yaw());
            location.setPitch(location.getPitch() + offset.pitch());

        } else {
            location.setYaw(offset.yaw());
            location.setPitch(offset.pitch());
        }
    }

    public Location getLocation() {
        return location;
    }

    public PathVector getOffset() {
        return offset;
    }

    public boolean isRelative() {
        return relative;
    }

    public void setRelative(boolean relative) {
        this.relative = relative;
    }

    public static abstract class Builder<GenericBuilder extends Builder, GenericLocation extends BoundLocation> {

        protected GenericLocation location;

        public Builder(GenericLocation location) {
            this.location = location;
        }

        public GenericBuilder offset(PathVector offset) {
            location.offset = offset;
            return getThis();
        }

        public GenericBuilder relative(boolean relative) {
            location.relative = relative;
            return getThis();
        }

        protected abstract GenericBuilder getThis();

        public GenericLocation build() {
            return location;
        }

    }

}


text:
package com.navercorp.pinpoint.plugin.mybatis;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mybatis.spring.SqlSessionTemplate;

import javax.sql.DataSource;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author HyunGil Jeong
 */
public class SqlSessionTemplateITBase extends SqlSessionTestBase {

    private static final ExecutorType EXECUTOR_TYPE = ExecutorType.SIMPLE;

    @Mock
    private SqlSessionFactory sqlSessionFactory;

    @Mock
    private SqlSession sqlSessionProxy;

    private SqlSessionTemplate sqlSessionTemplate;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        Configuration configuration = mock(Configuration.class);
        TransactionFactory transactionFactory = mock(TransactionFactory.class);
        DataSource dataSource = mock(DataSource.class);
        Environment environment = new Environment("test", transactionFactory, dataSource);
        when(configuration.getEnvironment()).thenReturn(environment);
        when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration);
        when(this.sqlSessionFactory.openSession(EXECUTOR_TYPE)).thenReturn(this.sqlSessionProxy);
        this.sqlSessionTemplate = new SqlSessionTemplate(this.sqlSessionFactory, EXECUTOR_TYPE);
    }

    @Override
    protected SqlSession getSqlSession() {
        return this.sqlSessionTemplate;
    }

    @Test
    public void methodCallWithNullSqlIdShouldOnlyTraceMethodName() throws Exception {
        super.testAndVerifyInsertWithNullParameter();
    }

    @Test
    public void selectShouldBeTraced() throws Exception {
        super.testAndVerifySelect();
    }

    @Test
    public void selectOneShouldBeTraced() throws Exception {
        super.testAndVerifySelectOne();
    }

    @Test
    public void selectListShouldBeTraced() throws Exception {
        super.testAndVerifySelectList();
    }

    @Test
    public void selectMapShouldBeTraced() throws Exception {
        super.testAndVerifySelectMap();
    }

    @Test
    public void insertShouldBeTraced() throws Exception {
        super.testAndVerifyInsert();
    }

    @Test
    public void updateShouldBeTraced() throws Exception {
        super.testAndVerifyUpdate();
    }

    @Test
    public void deleteShouldBeTraced() throws Exception {
        super.testAndVerifyDelete();
    }
}


text:
<?php

namespace Classes\Generators;

use Classes\ClassMethod;
use Classes\ClassProperty;
use Classes\MethodParameter;

class ClassPropertyGenerator implements GeneratorInterface
{
    /**
     * @var ClassProperty
     */
    private $classProperty;

    public function __construct(ClassProperty $classProperty)
    {
        $this->classProperty = $classProperty;
    }

    /**
     * @return string
     */
    public function generate()
    {
        $output = '';

        $output .= PHP_EOL.$this->generateGetter()->generate().PHP_EOL;
        $output .= PHP_EOL.$this->generateSetter()->generate().PHP_EOL;

        if ($this->classProperty->getType() == 'array') {
            $output .= PHP_EOL.$this->generateAdd()->generate().PHP_EOL;
        }

        return $output;
    }

    /**
     * @return ClassMethod
     */
    protected function generateGetter()
    {
        $getter = new ClassMethod('get'.ucfirst($this->classProperty->getName()));
        $getter->setDescription('Getter of '.$this->classProperty->getName());
        $getter->setReturn($this->classProperty->getName());
        $getter->setReturnType($this->classProperty->getType());
        $getter->setBody('  return $this->'.$this->classProperty->getName().';');

        return $getter;
    }

    /**
     * @return ClassMethod
     */
    protected function generateSetter()
    {
        $setter = new ClassMethod('set'.ucfirst($this->classProperty->getName()));
        $setter->setDescription('Setter of '.$this->classProperty->getName());
        $setterParam = new MethodParameter($this->classProperty->getName(), $this->classProperty->getType());
        $setter->addParameter($setterParam);

        $body = <<<BODY
	\$this->{$this->classProperty->getName()} = \${$this->classProperty->getName()};
BODY;

        $setter->setBody($body);

        return $setter;
    }

    /**
     * @return ClassMethod
     */
    protected function generateAdd()
    {
        $setter = new ClassMethod('add'.ucfirst($this->classProperty->getName()));
        $setter->setDescription('Add item to '.$this->classProperty->getName());
        $setterParam = new MethodParameter($this->classProperty->getName(), 'mixed');
        $setter->addParameter($setterParam);

        $body = <<<BODY
	\$this->{$this->classProperty->getName()} = \${$this->classProperty->getName()};
BODY;

        $setter->setBody($body);

        return $setter;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }
}


text:
        <bx_if:show_thumb_image>

        </bx_if:show_thumb_image>
        <bx_if:show_thumb_letter>

__letter__

        </bx_if:show_thumb_letter>
        <bx_if:show_online>

        </bx_if:show_online>

        __title__


text:
package com.groupon.seleniumgridextras;

import com.groupon.seleniumgridextras.tasks.ExecuteOSTask;
import com.groupon.seleniumgridextras.tasks.RebootNode;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class RebootNodeTest {

  private ExecuteOSTask task;
  private String windowsCommand;

  @Before
  public void setUp() throws Exception {
    task = new RebootNode();
    windowsCommand = "shutdown -r -t 1 -f";
  }

  @Test
  public void testGetDescription() throws Exception {
    assertEquals("Restart the host node", task.getDescription());
  }

  @Test
  public void testGetEndpoint() throws Exception {
    assertEquals("/reboot", task.getEndpoint());
  }

  @Test
  public void testgetWindowsCommand() throws Exception {
    assertEquals(windowsCommand, task.getWindowsCommand());
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.apache.edgent.function.Consumer (Edgent v0.4.0)</title>
<meta name="date" content="2016-07-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.edgent.function.Consumer

Packages that use Consumer

Package
Description

org.apache.edgent.connectors.command

Command / OS Process connector.

org.apache.edgent.connectors.jdbc

JDBC based database stream connector.

org.apache.edgent.connectors.pubsub.service

Publish subscribe service.

org.apache.edgent.connectors.serial

Serial port connector API.

org.apache.edgent.connectors.wsclient.javax.websocket.runtime

org.apache.edgent.function

Functional interfaces for lambda expressions.

org.apache.edgent.metrics.oplets

org.apache.edgent.oplet

Oplets API.

org.apache.edgent.oplet.core

Core primitive oplets.

org.apache.edgent.oplet.functional

Oplets that process tuples using functions.

org.apache.edgent.oplet.plumbing

Oplets that control the flow of tuples.

org.apache.edgent.oplet.window

Oplets using windows.

org.apache.edgent.runtime.etiao

A runtime for executing an Edgent streaming topology, designed as an embeddable library
 so that it can be executed in a simple Java application.

org.apache.edgent.streamscope

Stream Oscilloscope - package for instrumenting streams to capture tuples.

org.apache.edgent.streamscope.oplets

org.apache.edgent.topology

Functional api to build a streaming topology.

org.apache.edgent.topology.spi

org.apache.edgent.topology.spi.graph

org.apache.edgent.window

Window API.

Uses of Consumer in org.apache.edgent.connectors.command

Methods in org.apache.edgent.connectors.command that return Consumer

Modifier and Type
Method and Description

static Consumer<java.lang.String>
CommandStreams.commandWriter(java.lang.ProcessBuilder cmd)

Create a Consumer<String> to write UTF8 string data to a command's input.

Uses of Consumer in org.apache.edgent.connectors.jdbc

Methods in org.apache.edgent.connectors.jdbc with parameters of type Consumer

Modifier and Type
Method and Description

void
ResultsHandler.handleResults(T tuple,
             java.sql.ResultSet resultSet,
             java.lang.Exception exc,
             Consumer<R> consumer)

Process the ResultSet and add 0 or more tuples to consumer.

Uses of Consumer in org.apache.edgent.connectors.pubsub.service

Methods in org.apache.edgent.connectors.pubsub.service that return Consumer

Modifier and Type
Method and Description

<T> Consumer<T>
PublishSubscribeService.getPublishDestination(java.lang.String topic,
                     java.lang.Class<? super T> streamType)

Get the destination for a publisher.

<T> Consumer<T>
ProviderPubSub.getPublishDestination(java.lang.String topic,
                     java.lang.Class<? super T> streamType)

Methods in org.apache.edgent.connectors.pubsub.service with parameters of type Consumer

Modifier and Type
Method and Description

<T> void
PublishSubscribeService.addSubscriber(java.lang.String topic,
             java.lang.Class<T> streamType,
             Consumer<T> subscriber)

Add a subscriber to a published topic.

<T> void
ProviderPubSub.addSubscriber(java.lang.String topic,
             java.lang.Class<T> streamType,
             Consumer<T> subscriber)

void
PublishSubscribeService.removeSubscriber(java.lang.String topic,
                Consumer<?> subscriber)

void
ProviderPubSub.removeSubscriber(java.lang.String topic,
                Consumer<?> subscriber)

Uses of Consumer in org.apache.edgent.connectors.serial

Methods in org.apache.edgent.connectors.serial with parameters of type Consumer

Modifier and Type
Method and Description

void
SerialDevice.setInitializer(Consumer<SerialPort> initializer)

Set the initialization function for this port.

Uses of Consumer in org.apache.edgent.connectors.wsclient.javax.websocket.runtime

Classes in org.apache.edgent.connectors.wsclient.javax.websocket.runtime that implement Consumer

Modifier and Type
Class and Description

class
WebSocketClientBinaryReceiver<T>

class
WebSocketClientBinarySender<T>

class
WebSocketClientReceiver<T>

class
WebSocketClientSender<T>

Fields in org.apache.edgent.connectors.wsclient.javax.websocket.runtime declared as Consumer

Modifier and Type
Field and Description

protected Consumer<T>
WebSocketClientReceiver.eventHandler

Methods in org.apache.edgent.connectors.wsclient.javax.websocket.runtime with parameters of type Consumer

Modifier and Type
Method and Description

void
WebSocketClientReceiver.accept(Consumer<T> eventHandler)

Uses of Consumer in org.apache.edgent.function

Methods in org.apache.edgent.function that return Consumer

Modifier and Type
Method and Description

static <T> Consumer<T>
Functions.discard()

A Consumer that discards all items passed to it.

static <T> Consumer<T>
Functions.synchronizedConsumer(Consumer<T> function)

Return a thread-safe version of a Consumer function.

Methods in org.apache.edgent.function with parameters of type Consumer

Modifier and Type
Method and Description

static <T> java.lang.Runnable
Functions.delayedConsume(Consumer<T> consumer,
              T value)

Create a Runnable that calls
 consumer.accept(value) when run() is called.

static <T> Consumer<T>
Functions.synchronizedConsumer(Consumer<T> function)

Return a thread-safe version of a Consumer function.

Uses of Consumer in org.apache.edgent.metrics.oplets

Classes in org.apache.edgent.metrics.oplets that implement Consumer

Modifier and Type
Class and Description

class
CounterOp<T>

A metrics oplet which counts the number of tuples peeked at.

class
RateMeter<T>

A metrics oplet which measures current tuple throughput and one-, five-,
 and fifteen-minute exponentially-weighted moving averages.

class
SingleMetricAbstractOplet<T>

Base for metrics oplets which use a single metric object.

Uses of Consumer in org.apache.edgent.oplet

Methods in org.apache.edgent.oplet that return types with arguments of type Consumer

Modifier and Type
Method and Description

java.util.List<? extends Consumer<I>>
Oplet.getInputs()

Get the input stream data handlers for this oplet.

java.util.List<? extends Consumer<O>>
OpletContext.getOutputs()

Get the mechanism to submit tuples on an output port.

Uses of Consumer in org.apache.edgent.oplet.core

Classes in org.apache.edgent.oplet.core that implement Consumer

Modifier and Type
Class and Description

class
FanOut<T>

class
Peek<T>

Oplet that allows a peek at each tuple and always forwards a tuple onto
 its single output port.

class
Pipe<I,O>

Pipe oplet with a single input and output.

class
Split<T>

Split a stream into multiple streams depending
 on the result of a splitter function.

Methods in org.apache.edgent.oplet.core that return Consumer

Modifier and Type
Method and Description

protected Consumer<T>
FanIn.consumer(int iportIndex)

Create a Consumer for the input port that invokes the
 receiver and submits a generated tuple, if any, to the output.

protected Consumer<T>
Source.getDestination()

protected Consumer<O>
Pipe.getDestination()

protected Consumer<U>
FanIn.getDestination()

protected Consumer<T>
Sink.getSinker()

Get the sink function that processes each tuple.

Methods in org.apache.edgent.oplet.core that return types with arguments of type Consumer

Modifier and Type
Method and Description

java.util.List<Consumer<T>>
Split.getInputs()

java.util.List<Consumer<java.lang.Void>>
Source.getInputs()

java.util.List<Consumer<T>>
Sink.getInputs()

java.util.List<Consumer<I>>
Pipe.getInputs()

java.util.List<? extends Consumer<T>>
FanOut.getInputs()

java.util.List<? extends Consumer<T>>
FanIn.getInputs()

Methods in org.apache.edgent.oplet.core with parameters of type Consumer

Modifier and Type
Method and Description

protected void
Sink.setSinker(Consumer<T> sinker)

Set the sink function.

Constructors in org.apache.edgent.oplet.core with parameters of type Consumer

Constructor and Description

Sink(Consumer<T> sinker)

Create a Sink oplet.

Uses of Consumer in org.apache.edgent.oplet.functional

Classes in org.apache.edgent.oplet.functional that implement Consumer

Modifier and Type
Class and Description

class
Events<T>

Generate tuples from events.

class
Filter<T>

class
FlatMap<I,O>

Map an input tuple to 0-N output tuples.

class
Map<I,O>

Map an input tuple to 0-1 output tuple

Methods in org.apache.edgent.oplet.functional that return Consumer

Modifier and Type
Method and Description

protected Consumer<T>
Peek.getPeeker()

Constructors in org.apache.edgent.oplet.functional with parameters of type Consumer

Constructor and Description

Events(Consumer<Consumer<T>> eventSetup)

Peek(Consumer<T> peeker)

Peek oplet using a function to peek.

Constructor parameters in org.apache.edgent.oplet.functional with type arguments of type Consumer

Constructor and Description

Events(Consumer<Consumer<T>> eventSetup)

Uses of Consumer in org.apache.edgent.oplet.plumbing

Classes in org.apache.edgent.oplet.plumbing that implement Consumer

Modifier and Type
Class and Description

class
Isolate<T>

Isolate upstream processing from downstream
 processing guaranteeing tuple order.

class
PressureReliever<T,K>

Relieve pressure on upstream oplets by discarding tuples.

class
UnorderedIsolate<T>

Isolate upstream processing from downstream
 processing without guaranteeing tuple order.

Uses of Consumer in org.apache.edgent.oplet.window

Classes in org.apache.edgent.oplet.window that implement Consumer

Modifier and Type
Class and Description

class
Aggregate<T,U,K>

Aggregate a window.

Uses of Consumer in org.apache.edgent.runtime.etiao

Classes in org.apache.edgent.runtime.etiao that implement Consumer

Modifier and Type
Class and Description

class
SettableForwarder<T>

A forwarding Streamer whose destination
 can be changed.

Methods in org.apache.edgent.runtime.etiao that return Consumer

Modifier and Type
Method and Description

Consumer<T>
SettableForwarder.getDestination()

Get the destination.

Methods in org.apache.edgent.runtime.etiao that return types with arguments of type Consumer

Modifier and Type
Method and Description

java.util.List<? extends Consumer<I>>
Invocation.getInputs()

Returns the list of input stream forwarders for this invocation.

java.util.List<? extends Consumer<O>>
InvocationContext.getOutputs()

Methods in org.apache.edgent.runtime.etiao with parameters of type Consumer

Modifier and Type
Method and Description

void
SettableForwarder.setDestination(Consumer<T> destination)

Change the destination.

void
Invocation.setTarget(int port,
         Consumer<O> target)

Disconnects the specified port and reconnects it to the specified target.

Constructors in org.apache.edgent.runtime.etiao with parameters of type Consumer

Constructor and Description

SettableForwarder(Consumer<T> destination)

Create with the specified destination.

Constructor parameters in org.apache.edgent.runtime.etiao with type arguments of type Consumer

Constructor and Description

InvocationContext(java.lang.String id,
                 JobContext job,
                 RuntimeServices services,
                 int inputCount,
                 java.util.List<? extends Consumer<O>> outputs,
                 java.util.List<OutputPortContext> outputContext)

Creates an InvocationContext with the specified parameters.

Uses of Consumer in org.apache.edgent.streamscope

Classes in org.apache.edgent.streamscope that implement Consumer

Modifier and Type
Class and Description

class
StreamScope<T>

A Stream "oscilloscope" for capturing stream tuples for analysis / debug.

Uses of Consumer in org.apache.edgent.streamscope.oplets

Constructors in org.apache.edgent.streamscope.oplets with parameters of type Consumer

Constructor and Description

StreamScope(Consumer<T> streamScope)

Create a new instance.

Uses of Consumer in org.apache.edgent.topology

Methods in org.apache.edgent.topology with parameters of type Consumer

Modifier and Type
Method and Description

<T> TStream<T>
Topology.events(Consumer<Consumer<T>> eventSetup)

Declare a stream populated by an event system.

TStream<T>
TStream.peek(Consumer<T> peeker)

Declare a stream that contains the same contents as this stream while
 peeking at each element using peeker.

TSink<T>
TStream.sink(Consumer<T> sinker)

Sink (terminate) this stream using a function.

Method parameters in org.apache.edgent.topology with type arguments of type Consumer

Modifier and Type
Method and Description

<T> TStream<T>
Topology.events(Consumer<Consumer<T>> eventSetup)

Declare a stream populated by an event system.

Uses of Consumer in org.apache.edgent.topology.spi

Methods in org.apache.edgent.topology.spi with parameters of type Consumer

Modifier and Type
Method and Description

TSink<T>
AbstractTStream.sink(Consumer<T> sinker)

Uses of Consumer in org.apache.edgent.topology.spi.graph

Methods in org.apache.edgent.topology.spi.graph with parameters of type Consumer

Modifier and Type
Method and Description

<T> TStream<T>
GraphTopology.events(Consumer<Consumer<T>> eventSetup)

TStream<T>
ConnectorStream.peek(Consumer<T> peeker)

Method parameters in org.apache.edgent.topology.spi.graph with type arguments of type Consumer

Modifier and Type
Method and Description

<T> TStream<T>
GraphTopology.events(Consumer<Consumer<T>> eventSetup)

Uses of Consumer in org.apache.edgent.window

Methods in org.apache.edgent.window that return Consumer

Modifier and Type
Method and Description

static <T,K,L extends java.util.List<T>>
Consumer<Partition<T,K,L>>
Policies.evictAll()

Returns a Consumer representing an evict determiner that evict all tuples
 from the window.

static <T,K> Consumer<Partition<T,K,java.util.List<T>>>
Policies.evictAllAndScheduleEvictWithProcess(long time,
                                   java.util.concurrent.TimeUnit unit)

An eviction policy which processes the window, evicts all tuples, and
 schedules the next eviction after the appropriate interval.

static <T,K> Consumer<Partition<T,K,InsertionTimeList<T>>>
Policies.evictOlderWithProcess(long time,
                     java.util.concurrent.TimeUnit unit)

An eviction policy which evicts all tuples that are older than a specified time.

static <T,K,L extends java.util.List<T>>
Consumer<Partition<T,K,L>>
Policies.evictOldest()

Returns an evict determiner that evicts the oldest tuple.

Consumer<Partition<T,K,L>>
Window.getEvictDeterminer()

Returns the window's eviction determiner.

Methods in org.apache.edgent.window with parameters of type Consumer

Modifier and Type
Method and Description

static <T,K,L extends java.util.List<T>>
Window<T,K,L>
Windows.window(BiFunction<Partition<T,K,L>,T,java.lang.Boolean> insertionPolicy,
      BiConsumer<Partition<T,K,L>,T> contentsPolicy,
      Consumer<Partition<T,K,L>> evictDeterminer,
      BiConsumer<Partition<T,K,L>,T> triggerPolicy,
      Function<T,K> keyFunction,
      Supplier<L> listSupplier)

Create a window using the passed in policies.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Apache Edgent (incubating)

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation. All Rights Reserved - 54ea8ac-20160726-1240


text:
{% extends "base.html" %}

{% block title %}Rochester Videos | {{ block.super }}{% endblock %}

{% block bodyclass %}{{ block.super }}flatpage {{ flatpage.title|slugify }}{% endblock %}
{% load fb_versions %}

{% block smmeta %}
    <meta name="description" content="A bi-monthly magazine in Rochester, New York. We tell the hidden and untold story of Rochester's innovators, artists, entrepreneurs, dreamers, and doers.">

    <meta property='og:title' content='Post. This is Rochester'>
    <meta name="description" content="A bi-monthly magazine in Rochester, New York. We tell the hidden and untold story of Rochester's innovators, artists, entrepreneurs, dreamers, and doers.">
    <meta property='og:url' content='http://{{ site.domain }}{{ flatpage.url }}'>
    <meta property='og:image' content='https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-ash4/1000837_175802752593615_1524246974_n.jpg'>

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@postrochester">
    <meta name="twitter:creator" content="@postrochester">
    <meta name="twitter:title" content="Post. This is Rochester">
    <meta name="twitter:description" content="A bi-monthly magazine in Rochester, New York. We tell the hidden and untold story of Rochester's innovators, artists, entrepreneurs, dreamers, and doers.">
    <meta name='twitter:image' content='https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-ash4/1000837_175802752593615_1524246974_n.jpg'>
{% endblock %}

{% block headernav %}
{% load article_tags %}
{% banner request %}
{% endblock %}

{% block content %}

Post Videos

Short documentaries created by the POST team.

   {% for video in post_videos %}

{{ video.title }}

   {% endfor %}

{% if ad1 %}

Special thanks to our underwriters:

{% endif %}

Community Videos

A curated collection of locally-focused documentaries.

   {% for video in community_videos %}

{{ video.title|truncatechars:31 }}

   {% endfor %}

{% if ad2 %}

Special thanks to our underwriters:

{% endif %}

{% endblock %}

{% block inlinejs %}

{% endblock %}


text:
package de.terrestris.shogun2.dao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.PropertyProjection;
import org.hibernate.criterion.Restrictions;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.transform.DistinctRootEntityResultTransformer;
import org.hibernate.transform.Transformers;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import de.terrestris.shogun2.model.PersistentObject;
import de.terrestris.shogun2.model.User;
import de.terrestris.shogun2.model.UserGroup;
import de.terrestris.shogun2.model.security.PermissionCollection;
import de.terrestris.shogun2.paging.PagingResult;
import de.terrestris.shogun2.util.entity.EntityUtil;

/**
 * The superclass for all data access objects. Provides basic CRUD
 * functionality and a logger instance for all subclasses.
 *
 * @author Nils Bühner
 */
@Repository("genericDao")
public class GenericHibernateDao<E extends PersistentObject, ID extends Serializable> {

    /**
     * The LOGGER instance (that will be available in all subclasses)
     */
    protected final Logger LOG = Logger.getLogger(getClass());

    /**
     * Represents the class of the entity
     */
    private final Class<E> entityClass;

    @Value("${hibernate.cache.use_query_cache}")
    private Boolean useQueryCache;

    /**
     * Default constructor
     */
    @SuppressWarnings("unchecked")
    public GenericHibernateDao() {
        this((Class<E>) PersistentObject.class);
    }

    /**
     * Constructor
     *
     * @param clazz
     */
    protected GenericHibernateDao(Class<E> clazz) {
        this.entityClass = clazz;
    }

    /**
     * Hibernate SessionFactory
     */
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * Obtains the current session.
     *
     * @return
     */
    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * Return the real object from the database. Returns null if the object does
     * not exist.
     *
     * @param id
     * @return The object from the database or null if it does not exist
     * @see http://www.mkyong.com/hibernate/different-between-session-get-and-session-load/
     */
    public E findById(ID id) {
        LOG.trace("Finding " + entityClass.getSimpleName() + " with ID " + id);
        return (E) getSession().get(entityClass, id);
    }

    /**
     * Returns a list of entity objects that have field named
     * fieldName, which has an object fieldEntity
     * as value.
     *
     * @param fieldName   The name of the field
     * @param fieldEntity The element that should be set as value
     * @param criterion   Additional criterions to apply (optional)
     * @return The list of objects
     */
    @SuppressWarnings("unchecked")
    public List<E> findAllWhereFieldEquals(String fieldName, Object fieldEntity,
                                           Criterion... criterion) {

        Class<?> fieldEntityType = null;

        if (fieldEntity != null) {
            fieldEntityType = fieldEntity.getClass();
        }

        final boolean isField = EntityUtil.isField(entityClass, fieldName, fieldEntityType, true);

        if (!isField) {
            String errorMsg = String.format(
                "There is no field '%s' in the type '%s' that accepts instances of '%s'",
                fieldName,
                entityClass.getName(),
                fieldEntityType.getName()
            );
            throw new IllegalArgumentException(errorMsg);
        }

        Criteria criteria = createDistinctRootEntityCriteria(criterion);

        if (fieldEntity == null) {
            criteria.add(Restrictions.isNull(fieldName));
        } else {
            criteria.add(Restrictions.eq(fieldName, fieldEntity));
        }
        criteria.setCacheable(this.useQueryCache);

        return (List<E>) criteria.list();
    }

    /**
     * Returns a list of entity objects that have a collection named
     * fieldName, which contains the passed
     * subElement.
     *

     * The can e.g. be used to return all applications that contain a certain layer.
     *
     * @param fieldName  The name of the collection field
     * @param subElement The element that should be contained in the collection
     * @param criterion  Additional criterions to apply (optional)
     * @return The list of objects
     */
    @SuppressWarnings("unchecked")
    public List<E> findAllWithCollectionContaining(String fieldName, PersistentObject subElement,
                                                   Criterion... criterion) {
        final Class<? extends PersistentObject> subElementType = subElement.getClass();

        final boolean isCollectionField = EntityUtil.isCollectionField(entityClass, fieldName, subElementType, true);

        if (!isCollectionField) {
            String errorMsg = String.format(
                "There is no collection field '%s' with element type '%s' in the type '%s'",
                fieldName,
                subElementType.getName(),
                entityClass.getName()
            );
            throw new IllegalArgumentException(errorMsg);
        }

        Criteria criteria = createDistinctRootEntityCriteria(criterion);
        criteria.createAlias(fieldName, "sub");
        criteria.add(Restrictions.eq("sub.id", subElement.getId()));
        return (List<E>) criteria.list();
    }

    /**
     * Return a proxy of the object (without hitting the database). This should
     * only be used if it is assumed that the object really exists and where
     * non-existence would be an actual error.
     *
     * @param id
     * @return
     * @see http://www.mkyong.com/hibernate/different-between-session-get-and-session-load/
     */
    public E loadById(ID id) {
        LOG.trace("Loading " + entityClass.getSimpleName() + " with ID " + id);
        return (E) getSession().load(entityClass, id);
    }

    /**
     * Returns all Entities by calling findByCriteria(), i.e. without arguments.
     *
     * @return All entities
     * @see GenericHibernateDao#findByCriteria(Criterion...)
     */
    public List<E> findAll() throws HibernateException {
        LOG.trace("Finding all instances of " + entityClass.getSimpleName());
        return findByCriteria();
    }

    /**
     * Saves or updates the passed entity.
     *
     * @param e The entity to save or update in the database.
     */
    public void saveOrUpdate(E e) {
        final Integer id = e.getId();
        final boolean hasId = id != null;
        String createOrUpdatePrefix = hasId ? "Updating" : "Creating a new";
        String idSuffix = hasId ? " with ID " + id : "";

        LOG.trace(createOrUpdatePrefix + " instance of " + entityClass.getSimpleName()
            + idSuffix);

        e.setModified(DateTime.now());
        getSession().saveOrUpdate(e);
    }

    /**
     * Deletes the passed entity.
     *
     * @param e The entity to remove from the database.
     */
    public void delete(E e) {
        LOG.trace("Deleting " + entityClass.getSimpleName() + " with ID " + e.getId());
        getSession().delete(e);
    }

    /**
     * Unproxy the entity (and eagerly fetch properties).
     */
    @SuppressWarnings("unchecked")
    public E unproxy(E e) {
        if (e == null) {
            throw new NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(e);

        if (e instanceof HibernateProxy) {
            e = (E) ((HibernateProxy) e).getHibernateLazyInitializer().getImplementation();
        }

        return e;
    }

    /**
     * Detach an entity from the hibernate session
     *
     * @param e
     */
    public void evict(E e) {
        LOG.trace("Detaching " + entityClass.getSimpleName() + " with ID " + e.getId() + " from hibernate session");
        getSession().evict(e);
    }

    /**
     * Gets the results, that match a variable number of passed criterions. Call
     * this method without arguments to find all entities.
     *
     * @param criterion A variable number of hibernate criterions
     * @return Entities matching the passed hibernate criterions
     */
    @SuppressWarnings("unchecked")
    public List<E> findByCriteria(Criterion... criterion) throws HibernateException {
        LOG.trace("Finding instances of " + entityClass.getSimpleName()
            + " based on " + criterion.length + " criteria");

        Criteria criteria = createDistinctRootEntityCriteria(criterion);
        return criteria.list();
    }

    /**
     * Gets the results, that match a variable number of passed criterions, but return a
     * stripped version of the entities, where only the fieldNames in restrictFieldNames
     * have their actual values set.
     *

     * You can call this with restrictFieldNames = null to get the full
     * entities back.
     *

     * You can call this method without criterion arguments to find all entities (stripped down to
     * the restrictFieldNames).
     *

     * If this is called as findByCriteriaRestricted(null) the return value equals the
     * return value of findByCriteria().
     *
     * @param restrictFieldNames
     * @param criterion
     * @return
     * @throws HibernateException
     */
    @SuppressWarnings("unchecked")
    public List<E> findByCriteriaRestricted(List<String> restrictFieldNames, Criterion... criterion) throws HibernateException {
        LOG.trace("Finding instances of " + entityClass.getSimpleName()
            + " based on " + criterion.length + " criteria");

        Criteria criteria = createDistinctRootEntityCriteria(criterion);

        if (restrictFieldNames != null) {
            ProjectionList projectionList = Projections.projectionList();
            for (String restrictFieldName : restrictFieldNames) {
                PropertyProjection pp = Projections.property(restrictFieldName);
                projectionList.add(pp, restrictFieldName);
            }
            criteria.setProjection(projectionList);
            criteria.setResultTransformer(
                Transformers.aliasToBean(entityClass)
            );
        }

        return criteria.list();
    }

    /**
     * Gets the unique result, that matches a variable number of passed
     * criterions.
     *
     * @param criterion A variable number of hibernate criterions
     * @return Entity matching the passed hibernate criterions
     * @throws HibernateException if there is more than one matching result
     */
    @SuppressWarnings("unchecked")
    public E findByUniqueCriteria(Criterion... criterion) throws HibernateException {
        LOG.trace("Finding one unique " + entityClass.getSimpleName()
            + " based on " + criterion.length + " criteria");

        Criteria criteria = createDistinctRootEntityCriteria(criterion);
        return (E) criteria.uniqueResult();
    }

    /**
     * Gets the results, that match a variable number of passed criterions,
     * considering the paging- and sort-info at the same time.
     *
     * @param firstResult Starting index for the paging request.
     * @param maxResults  Max number of result size.
     * @param criterion   A variable number of hibernate criterions
     * @return
     */
    @SuppressWarnings("unchecked")
    public PagingResult<E> findByCriteriaWithSortingAndPaging(Integer firstResult,
                                                              Integer maxResults, List<Order> sorters, Criterion... criterion) throws HibernateException {

        int nrOfSorters = sorters == null ? 0 : sorters.size();

        LOG.trace("Finding instances of " + entityClass.getSimpleName()
            + " based on " + criterion.length + " criteria"
            + " with " + nrOfSorters + " sorters");

        Criteria criteria = createDistinctRootEntityCriteria(criterion);

        // add paging info
        if (maxResults != null) {
            LOG.trace("Limiting result set size to " + maxResults);
            criteria.setMaxResults(maxResults);
        }
        if (firstResult != null) {
            LOG.trace("Setting the first result to be retrieved to "
                + firstResult);
            criteria.setFirstResult(firstResult);
        }

        // add sort info
        if (sorters != null) {
            for (Order sortInfo : sorters) {
                criteria.addOrder(sortInfo);
            }
        }

        return new PagingResult<E>(criteria.list(), getTotalCount(criterion));
    }

    /**
     * This method returns a {@link Map} that maps {@link PersistentObject}s
     * to PermissionCollections for the passed {@link User}. I.e. the keySet
     * of the map is the collection of all {@link PersistentObject}s where the
     * user has at least one permission and the corresponding value contains
     * the {@link PermissionCollection} for the passed user on the entity.
     *
     * @param user
     * @return
     */
    @SuppressWarnings({"unchecked"})
    public Map<PersistentObject, PermissionCollection> findAllUserPermissionsOfUser(User user) {

        Criteria criteria = getSession().createCriteria(PersistentObject.class);

        // by only setting the alias, we will only get those entities where
        // there is at least one permission set...
        // it is hard (or even impossible in this scenario) to create a
        // restriction that filters for permissions of the given user only.
        // using HQL here is no option as the PersistentObject is
        // a MappedSuperclass (without table).
        // another efficient way would be a SQL query, but then the SQL
        // would be written in an explicit SQL dialect...
        criteria.createAlias("userPermissions", "up");
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        List<PersistentObject> entitiesWithPermissions = criteria.list();

        Map<PersistentObject, PermissionCollection> userPermissions = new HashMap<PersistentObject, PermissionCollection>();

        // TODO find a better way than iterating over all entities of the system
        // that have at least one permission (for any user) (see comment above)
        for (PersistentObject entity : entitiesWithPermissions) {
            Map<User, PermissionCollection> entityUserPermissions = entity.getUserPermissions();
            if (entityUserPermissions.containsKey(user)) {
                userPermissions.put(entity, entityUserPermissions.get(user));
            }
        }

        return userPermissions;
    }

    /**
     * This method returns a {@link Map} that maps {@link PersistentObject}s
     * to PermissionCollections for the passed {@link UserGroup}. I.e. the keySet
     * of the map is the collection of all {@link PersistentObject}s where the
     * user group has at least one permission and the corresponding value contains
     * the {@link PermissionCollection} for the passed user group on the entity.
     *
     * @param userGroup
     * @return
     */
    @SuppressWarnings({"unchecked"})
    public Map<PersistentObject, PermissionCollection> findAllUserGroupPermissionsOfUserGroup(UserGroup userGroup) {

        Criteria criteria = getSession().createCriteria(PersistentObject.class);

        // by only setting the alias, we will only get those entities where
        // there is at least one permission set...
        // it is hard (or even impossible in this scenario) to create a
        // restriction that filters for permissions of the given user group only.
        // using HQL here is no option as the PersistentObject is
        // a MappedSuperclass (without table).
        // another efficient way would be a SQL query, but then the SQL
        // would be written in an explicit SQL dialect...
        criteria.createAlias("groupPermissions", "gp");
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        List<PersistentObject> entitiesWithPermissions = criteria.list();

        Map<PersistentObject, PermissionCollection> userGroupPermissions = new HashMap<PersistentObject, PermissionCollection>();

        // TODO find a better way than iterating over all entities of the system
        // that have at least one permission (for any user) (see comment above)
        for (PersistentObject entity : entitiesWithPermissions) {
            Map<UserGroup, PermissionCollection> entityUserGroupPermissions = entity.getGroupPermissions();
            if (entityUserGroupPermissions.containsKey(userGroup)) {
                userGroupPermissions.put(entity, entityUserGroupPermissions.get(userGroup));
            }
        }

        return userGroupPermissions;
    }

    /**
     * Helper method: Creates a criteria for the {@link #entityClass} of this dao.
     * The query results will be handled with a
     * {@link DistinctRootEntityResultTransformer}. The criteria will contain
     * all passed criterions.
     *
     * @return
     */
    protected Criteria createDistinctRootEntityCriteria(Criterion... criterion) {
        Criteria criteria = getSession().createCriteria(entityClass);
        addCriterionsToCriteria(criteria, criterion);
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        criteria.setCacheable(this.useQueryCache);
        return criteria;
    }

    /**
     * Returns the total count of db entries for the current type.
     *
     * @param criterion
     * @return
     */
    public Number getTotalCount(Criterion... criterion) throws HibernateException {
        Criteria criteria = getSession().createCriteria(entityClass);
        addCriterionsToCriteria(criteria, criterion);
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }

    /**
     * Helper method: Adds all criterions to the criteria (if not null).
     *
     * @param criteria
     * @param criterion
     */
    private void addCriterionsToCriteria(Criteria criteria, Criterion... criterion) {
        if (criteria != null) {
            for (Criterion c : criterion) {
                if (c != null) {
                    criteria.add(c);
                }
            }
        }
    }

    /**
     * @return the entityClass
     */
    public Class<E> getEntityClass() {
        return entityClass;
    }

}


text:
package otlpexporter // import "go.opentelemetry.io/collector/exporter/otlpexporter"

import (
	"context"

	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/configcompression"
	"go.opentelemetry.io/collector/config/configgrpc"
	"go.opentelemetry.io/collector/consumer"
	"go.opentelemetry.io/collector/exporter/exporterhelper"
)

const (
	// The value of "type" key in configuration.
	typeStr = "otlp"
)

// NewFactory creates a factory for OTLP exporter.
func NewFactory() component.ExporterFactory {
	return component.NewExporterFactory(
		typeStr,
		createDefaultConfig,
		component.WithTracesExporter(createTracesExporter, component.StabilityLevelStable),
		component.WithMetricsExporter(createMetricsExporter, component.StabilityLevelStable),
		component.WithLogsExporter(createLogsExporter, component.StabilityLevelBeta),
	)
}

func createDefaultConfig() component.Config {
	return &Config{
		ExporterSettings: config.NewExporterSettings(component.NewID(typeStr)),
		TimeoutSettings:  exporterhelper.NewDefaultTimeoutSettings(),
		RetrySettings:    exporterhelper.NewDefaultRetrySettings(),
		QueueSettings:    exporterhelper.NewDefaultQueueSettings(),
		GRPCClientSettings: configgrpc.GRPCClientSettings{
			Headers: map[string]string{},
			// Default to gzip compression
			Compression: configcompression.Gzip,
			// We almost read 0 bytes, so no need to tune ReadBufferSize.
			WriteBufferSize: 512 * 1024,
		},
	}
}

func createTracesExporter(
	ctx context.Context,
	set component.ExporterCreateSettings,
	cfg component.Config,
) (component.TracesExporter, error) {
	oce, err := newExporter(cfg, set)
	if err != nil {
		return nil, err
	}
	oCfg := cfg.(*Config)
	return exporterhelper.NewTracesExporter(ctx, set, cfg,
		oce.pushTraces,
		exporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),
		exporterhelper.WithTimeout(oCfg.TimeoutSettings),
		exporterhelper.WithRetry(oCfg.RetrySettings),
		exporterhelper.WithQueue(oCfg.QueueSettings),
		exporterhelper.WithStart(oce.start),
		exporterhelper.WithShutdown(oce.shutdown))
}

func createMetricsExporter(
	ctx context.Context,
	set component.ExporterCreateSettings,
	cfg component.Config,
) (component.MetricsExporter, error) {
	oce, err := newExporter(cfg, set)
	if err != nil {
		return nil, err
	}
	oCfg := cfg.(*Config)
	return exporterhelper.NewMetricsExporter(ctx, set, cfg,
		oce.pushMetrics,
		exporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),
		exporterhelper.WithTimeout(oCfg.TimeoutSettings),
		exporterhelper.WithRetry(oCfg.RetrySettings),
		exporterhelper.WithQueue(oCfg.QueueSettings),
		exporterhelper.WithStart(oce.start),
		exporterhelper.WithShutdown(oce.shutdown),
	)
}

func createLogsExporter(
	ctx context.Context,
	set component.ExporterCreateSettings,
	cfg component.Config,
) (component.LogsExporter, error) {
	oce, err := newExporter(cfg, set)
	if err != nil {
		return nil, err
	}
	oCfg := cfg.(*Config)
	return exporterhelper.NewLogsExporter(ctx, set, cfg,
		oce.pushLogs,
		exporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),
		exporterhelper.WithTimeout(oCfg.TimeoutSettings),
		exporterhelper.WithRetry(oCfg.RetrySettings),
		exporterhelper.WithQueue(oCfg.QueueSettings),
		exporterhelper.WithStart(oce.start),
		exporterhelper.WithShutdown(oce.shutdown),
	)
}


text:
#ifndef QLIBRARYINFO_H
#define QLIBRARYINFO_H

#include <QtCore/qstring.h>
#include <QtCore/qdatetime.h>

QT_BEGIN_NAMESPACE

class QStringList;

class Q_CORE_EXPORT QLibraryInfo
{
public:
    static QString licensee();
    static QString licensedProducts();

#ifndef QT_NO_DATESTRING
    static QDate buildDate();
#endif //QT_NO_DATESTRING

    static const char * build() Q_DECL_NOTHROW;

    static bool isDebugBuild();

    enum LibraryLocation
    {
        PrefixPath = 0,
        DocumentationPath,
        HeadersPath,
        LibrariesPath,
        LibraryExecutablesPath,
        BinariesPath,
        PluginsPath,
        ImportsPath,
        Qml2ImportsPath,
        ArchDataPath,
        DataPath,
        TranslationsPath,
        ExamplesPath,
        TestsPath,
        // Insert new values above this line
        // Please read the comments in qlibraryinfo.cpp before adding
#ifdef QT_BOOTSTRAPPED
        // These are not subject to binary compatibility constraints
        SysrootPath,
        HostPrefixPath,
        HostBinariesPath,
        HostLibrariesPath,
        HostDataPath,
        TargetSpecPath,
        HostSpecPath,
        LastHostPath = HostSpecPath,
#endif
        SettingsPath = 100
    };
    static QString location(LibraryLocation); // ### Qt 6: consider renaming it to path()
#ifdef QT_BOOTSTRAPPED
    enum PathGroup { FinalPaths, EffectivePaths, EffectiveSourcePaths };
    static QString rawLocation(LibraryLocation, PathGroup);
#endif

    static QStringList platformPluginArguments(const QString &platformName);

private:
    QLibraryInfo();
};

QT_END_NAMESPACE

#endif // QLIBRARYINFO_H