text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Copyright (c) 2004 World Wide Web Consortium,
 *
 * (Massachusetts Institute of Technology, European Research Consortium for
 * Informatics and Mathematics, Keio University). All Rights Reserved. This
 * work is distributed under the W3C(r) Software License [1] in the hope that
 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
 */

package org.w3c.dom.ls;

import org.w3c.dom.traversal.NodeFilter;

/**
 *  LSSerializerFilters provide applications the ability to
 * examine nodes as they are being serialized and decide what nodes should
 * be serialized or not. The LSSerializerFilter interface is
 * based on the NodeFilter interface defined in [DOM Level 2 Traversal and      Range]
 * .
 *
 Document, DocumentType,
 * DocumentFragment, Notation, Entity
 * , and children of Attr nodes are not passed to the filter.
 * The child nodes of an EntityReference node are only passed
 * to the filter if the EntityReference node is skipped by the
 * method LSParserFilter.acceptNode().
 *
 When serializing an Element, the element is passed to the
 * filter before any of its attributes are passed to the filter. Namespace
 * declaration attributes, and default attributes (except in the case when "
 * discard-default-content" is set to false), are never passed
 * to the filter.
 *
 The result of any attempt to modify a node passed to a
 * LSSerializerFilter is implementation dependent.
 *
 DOM applications must not raise exceptions in a filter. The effect of
 * throwing exceptions from a filter is DOM implementation dependent.
 *
 For efficiency, a node passed to the filter may not be the same as the
 * one that is actually in the tree. And the actual node (node object
 * identity) may be reused during the process of filtering and serializing a
 * document.
 *
See also the Document Object Model (DOM) Level 3 Load
and Save Specification.
 */
public interface LSSerializerFilter extends NodeFilter {
    /**
     *  Tells the LSSerializer what types of nodes to show to the
     * filter. If a node is not shown to the filter using this attribute, it
     * is automatically serialized. See NodeFilter for
     * definition of the constants. The constants SHOW_DOCUMENT
     * , SHOW_DOCUMENT_TYPE, SHOW_DOCUMENT_FRAGMENT
     * , SHOW_NOTATION, and SHOW_ENTITY are
     * meaningless here, such nodes will never be passed to a
     * LSSerializerFilter.
     *
 Unlike [DOM Level 2 Traversal and      Range]
     * , the SHOW_ATTRIBUTE constant indicates that the
     * Attr nodes are shown and passed to the filter.
     *
 The constants used here are defined in [DOM Level 2 Traversal and      Range]
     * .
     */
    public int getWhatToShow();

}


text:
Raspberry Pi Zero 8x8x8 LED Cube with Android component to go with it

____

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import url
from django.contrib.auth.views import password_change

from . import views

urlpatterns = [
    url(r'^$', views.UserList.as_view(), name='user_list'),
    url(r'^edit/$', views.UserUpdate.as_view(), name='user_profile_edit'),
    url(r'^change-password/$', password_change, name='user_change_password', kwargs={
        'template_name': 'users/password_change_form.html',
        'post_change_redirect':  '/users/edit/',
    }),
    url(r'^membership/$', views.MembershipCreate.as_view(), name='user_membership_create'),
    url(r'^membership/edit/$', views.MembershipUpdate.as_view(), name='user_membership_edit'),
    url(r'^membership/thanks/$', views.MembershipThanks.as_view(), name='user_membership_thanks'),
    url(r'^(?P<slug>[-_\w\@\.]+)/$', views.UserDetail.as_view(), name='user_detail'),
]


text:
package org.olat.lms.search.indexer.webfeed;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.olat.data.basesecurity.Identity;
import org.olat.data.basesecurity.Roles;
import org.olat.data.commons.filter.Filter;
import org.olat.data.commons.filter.FilterFactory;
import org.olat.data.commons.vfs.VFSContainer;
import org.olat.data.repository.RepositoryEntry;
import org.olat.lms.commons.context.BusinessControl;
import org.olat.lms.commons.context.ContextEntry;
import org.olat.lms.course.ICourse;
import org.olat.lms.course.nodes.CourseNode;
import org.olat.lms.search.SearchResourceContext;
import org.olat.lms.search.document.FeedItemDocument;
import org.olat.lms.search.document.FeedNodeDocument;
import org.olat.lms.search.document.OlatDocument;
import org.olat.lms.search.indexer.OlatFullIndexer;
import org.olat.lms.search.indexer.repository.course.CourseNodeIndexer;
import org.olat.lms.webfeed.Feed;
import org.olat.lms.webfeed.FeedManager;
import org.olat.lms.webfeed.Item;
import org.olat.lms.webfeed.Path;
import org.olat.system.logging.log4j.LoggerHelper;

/**
 * Indexer for feed course nodes
 *

 * Initial Date: Aug 18, 2009

 *
 * @author gwassmann
 */
public abstract class FeedCourseNodeIndexer extends CourseNodeIndexer {

    private static final Logger log = LoggerHelper.getLogger();

    /**
     * org.olat.lms.search.indexer.OlatFullIndexer)
     */
    @Override
    public void doIndex(final SearchResourceContext searchResourceContext, final ICourse course, final CourseNode node, final OlatFullIndexer indexer) throws IOException {
        final RepositoryEntry repositoryEntry = node.getReferencedRepositoryEntry();

        // we won't index external feeds
        final VFSContainer feedContainer = FeedManager.getInstance().getFeedContainer(repositoryEntry.getOlatResource());
        final Feed feedShallow = FeedManager.getInstance().readFeedFile(feedContainer);
        if (feedShallow.isExternal()) {
            log.info("Omit indexing external feed: " + repositoryEntry.getDisplayname());
            return;
        }

        // used for log messages
        String repoEntryName = "*name not available*";
        try {
            repoEntryName = repositoryEntry.getDisplayname();
            if (log.isDebugEnabled()) {
                log.info("Indexing: " + repoEntryName);
            }

            // Set the document type, e.g. type.repository.entry.FileResource.BLOG
            final SearchResourceContext nodeSearchContext = new SearchResourceContext(searchResourceContext);
            nodeSearchContext.setBusinessControlFor(node);
            nodeSearchContext.setDocumentType(getDocumentTypeName());

            // Create the olatDocument for the feed course node itself
            final Feed feed = FeedManager.getInstance().getFeed(repositoryEntry.getOlatResource());
            final OlatDocument feedNodeDoc = new FeedNodeDocument(feed, nodeSearchContext);
            indexer.addDocument(feedNodeDoc.getLuceneDocument());

            // Make sure images are displayed properly
            final String mapperBaseURL = Path.getFeedBaseUri(feed, null, course.getResourceableId(), node.getIdent());
            final Filter mediaUrlFilter = FilterFactory.getBaseURLToMediaRelativeURLFilter(mapperBaseURL);

            // Only index items. Feed itself is indexed by RepositoryEntryIndexer.
            for (final Item item : feed.getPublishedItems()) {
                final OlatDocument itemDoc = new FeedItemDocument(item, nodeSearchContext, mediaUrlFilter);
                indexer.addDocument(itemDoc.getLuceneDocument());
            }
        } catch (final NullPointerException e) {
            log.error("Error indexing feed:" + repoEntryName, e);
        }
    }

    /**
     * org.olat.data.basesecurity.Identity, org.olat.data.basesecurity.Roles)
     */
    @Override
    public boolean checkAccess(ContextEntry courseNodeContextEntry, BusinessControl businessControl, Identity identity, Roles roles, boolean isCourseOwner) {
        return true;
    }

}


text:
package com.rao.loveyou.ui.activity.guild;

import android.graphics.Canvas;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;

import java.util.List;

/**
 * @auther rjl
 * @time 2017/8/28.
 * @descr
 */

public class GuildCallBack extends ItemTouchHelper.SimpleCallback {
    private static final String TAG = "GuildCallBack";
    private List<String> mList;
    private RecyclerView mRecyclerView;
    private GuildAdapter mGuildAdapter;

    public GuildCallBack(int dragDirs, int swipeDirs, List<String> list, RecyclerView recyclerView, GuildAdapter guildAdapter) {
        super(dragDirs, swipeDirs);
        mList = list;
        mRecyclerView = recyclerView;
        mGuildAdapter = guildAdapter;
    }

    public GuildCallBack(int dragDirs, int swipeDirs) {
        super(dragDirs, swipeDirs);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        //获取当前位置的数据
        String itemBean = mList.remove(viewHolder.getAdapterPosition());
        //添加到集合中
        mList.add(0, itemBean);
        //刷新数据
        mGuildAdapter.notifyDataSetChanged();
        //顶层view旋转复位
        viewHolder.itemView.setRotation(0);

        Log.i(TAG, "onSwiped: ");
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

        //view移动的距离
        double swipValue = Math.sqrt(dX * dX + dY * dY);
        //判断是否可以被回收的阀值
        float threshold = getThreshold(viewHolder);
        //移动的比例系数
        double fraction = swipValue / threshold;
        if (fraction > 1) {
            fraction = 1;
        }
        //现在对每个view进行缩放,位移
        int childCount = recyclerView.getChildCount();
      //  Log.i(TAG, "onChildDraw: childCount: " + childCount);

        for (int i = 0; i < childCount; i++) {
            View view = recyclerView.getChildAt(i);
            int level = childCount - i - 1;
          //  Log.i(TAG, "onChildDraw: level: " + level);
            //除了顶层之外,其他view睡着滑动,缩放和平移
            if (level > 0) {
                view.setScaleX((float) (1 - GuildConfig.SCANE_GAP * level + fraction * GuildConfig.SCANE_GAP));
                if (level < GuildConfig.MAX_SHOW_COUNT - 1) {
                    view.setScaleY((float) (1 - GuildConfig.SCANE_GAP * level + fraction * GuildConfig.SCANE_GAP));
                    view.setTranslationY(-(float) (GuildConfig.TRANS_Y_GAP * level - fraction * GuildConfig.TRANS_Y_GAP));

                }
            } else {
                float xFraction = dX / getThreshold(viewHolder);
                if (xFraction > 1) {
                    xFraction = 1;
                } else if (xFraction < -1) {
                    xFraction = -1;
                }
                view.setRotation(xFraction * GuildConfig.MAX_ROATE);
            }
        }

        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    /**
     * 水平方向可以回收的阀值
     * @param viewHolder
     * @return
     */
    private float getThreshold(RecyclerView.ViewHolder viewHolder) {
        return mRecyclerView.getWidth() * getSwipeThreshold(viewHolder);
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Converters;
using Microsoft.ServiceBus.Messaging;

namespace Microsoft.Azure.WebJobs.ServiceBus.Bindings
{
    internal class ConverterValueBinder<TInput> : IOrderedValueBinder
    {
        private readonly ServiceBusEntity _entity;
        private readonly IConverter<TInput, BrokeredMessage> _converter;
        private readonly Guid _functionInstanceId;

        public ConverterValueBinder(ServiceBusEntity entity, IConverter<TInput, BrokeredMessage> converter,
            Guid functionInstanceId)
        {
            _entity = entity;
            _converter = converter;
            _functionInstanceId = functionInstanceId;
        }

        public BindStepOrder StepOrder
        {
            get { return BindStepOrder.Enqueue; }
        }

        public Type Type
        {
            get { return typeof(TInput); }
        }

        public object GetValue()
        {
            return default(TInput);
        }

        public string ToInvokeString()
        {
            return _entity.MessageSender.Path;
        }

        public Task SetValueAsync(object value, CancellationToken cancellationToken)
        {
            BrokeredMessage message = _converter.Convert((TInput)value);
            Debug.Assert(message != null);
            return _entity.SendAndCreateQueueIfNotExistsAsync(message, _functionInstanceId, cancellationToken);
        }
    }
}


text:
struct Module {
	Module() {}
	virtual ~Module() {}

	virtual void init() = 0;
	virtual void run() = 0;
	virtual void learn() {}

private:
	Module(const Module &);
	Module & operator=(const Module &);
};

#endif // MODULE_H


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

        <TITLE>
            com.toedter.calendar (JCalendar API)
        </TITLE>

        <META NAME="date" CONTENT="2011-09-07">

        <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

                            Overview
                          Package
                            Class
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV PACKAGE
                     NEXT PACKAGE

                    FRAMES
                     NO FRAMES

                        All Classes

        Package com.toedter.calendar

                    Interface Summary

            IDateEditor
            All date editors that should be used by a JDateChooser have to implement this
                interface.

            IDateEvaluator
            Implementations of this interface can be added to various JCalendar
                components to check if certain dates are valid for selection.

                    Class Summary

            DateUtil
            A utility class for some date operations.

            JCalendar
            JCalendar is a bean for entering a date by choosing the year, month and day.

            JCalendarBeanInfo
            A BeanInfo class for JCalendar.

            JDateChooser
            A date chooser containing a date editor and a button, that makes a JCalendar
                visible for choosing a date.

            JDateChooserBeanInfo
            A BeanInfo class for the JDateChooser panel.

            JDateChooserCellEditor
            A CellEditor for tables, using a JDateChooser.

            JDayChooser
            JDayChooser is a bean for choosing a day.

            JDayChooserBeanInfo
            A BeanInfo class for the JDayChooser bean.

            JMonthChooser
            JMonthChooser is a bean for choosing a month.

            JMonthChooserBeanInfo
            A BeanInfo class for the JMonthChooser bean.

            JSpinnerDateEditor
            JSpinnerDateEditor is a date editor based on a JSpinner.

            JTextFieldDateEditor
            JTextFieldDateEditor is the default editor used by JDateChooser.

            JYearChooser
            JYearChooser is a bean for choosing a year.

            JYearChooserBeanInfo
            A BeanInfo class for the JYearChooser bean.

            MinMaxDateEvaluator

                            Overview
                          Package
                            Class
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV PACKAGE
                     NEXT PACKAGE

                    FRAMES
                     NO FRAMES

                        All Classes

    Copyright � 1999 - 2011 Kai Toedter.


text:
//This file is part of Myoddweb.Piger.
//
//    Myoddweb.Piger is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Myoddweb.Piger is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Myoddweb.Piger.  If not, see<https://www.gnu.org/licenses/gpl-3.0.en.html>.
#include "stdafx.h"
#include "MessageDlg.h"
#include "MemDC.h"

#define MAX_TRANSPARENCY (unsigned char)255
#define DEFAULT_TRANSPARENCY (unsigned char)127

/**
 * \brief the constructor
 * \see CDialog::CDialog
 */
MessageDlg::MessageDlg()
  : CommonWnd( L"MessageDlg" ),
    FadeWnd(),
    _totalMilisecondsToShowMessage(0),
    _elapseMiliSecondsBeforeFadeOut(0)
{
  _completeRect = { 0,0,0,0 };
}

MessageDlg::~MessageDlg()
{
  Stop();
  CommonWnd::Close();
}

/**
 * \brief called when the window is being created, we can then set our own values.
 * \see CDialog::Create
 * \param sText the text we want to display
 * \param elapseMiliSecondsBeforeFadeOut how long we want to display the message for before we fade out.
 * \param totalMilisecondsToShowMessage how long we want the message to be displayed including before fading out.
 */
void MessageDlg::Create(const std::wstring& sText, const long elapseMiliSecondsBeforeFadeOut, const long totalMilisecondsToShowMessage)
{
  //  save the value
  _totalMilisecondsToShowMessage = totalMilisecondsToShowMessage;
  _mStdMessage = sText;
  _elapseMiliSecondsBeforeFadeOut = elapseMiliSecondsBeforeFadeOut;

  __super::Create();
}

/**
 * \brief Initialise the fading window.
 */
void MessageDlg::InitWindowPos()
{
  //  get the size of the windows
  const auto hdc = ::GetDC( GetSafeHwnd() );

  //  get the font that we will be using for display
  //  because of the XML config this is only really used for size.
  const auto pOldFont = SelDisplayFont( hdc, 35 );

  RECT r = {0,0,0,0};
  myodd::html::html(hdc, _mStdMessage.c_str() , _mStdMessage.length(), &r, DT_DEFAULT | DT_CALCRECT );

  //  clean up old fonts
  if ( pOldFont != nullptr )
  {
    SelectObject( hdc, pOldFont );
  }

  ::ReleaseDC( nullptr, hdc );

  const auto width   = GetSystemMetrics( SM_CXFULLSCREEN ) / 2;
  const auto height  = GetSystemMetrics( SM_CYFULLSCREEN ) / 2;

  int widthM   = abs( r.right - r.left);
  int heightM  = abs( r.bottom - r.top);

  //  pad a little
  widthM  += 2 * static_cast<int>(::myodd::config::Get(L"commands\\pad.x", 2));
  heightM += 2 * static_cast<int>(::myodd::config::Get(L"commands\\pad.y", 2));

  //  move the window to the top left hand corner
  SetWindowPos(GetSafeHwnd(),
                HWND_TOPMOST,
                (width - widthM/2),
                (height - heightM/2),
                (widthM),
                (heightM),
                SWP_HIDEWINDOW );

  // save the full rectangle
  _completeRect = { 0,0, widthM, heightM };
}

/**
 * \brief Check if anything is running
 * \return if we are still busy
 */
bool MessageDlg::IsRunning() const
{
  return _worker.Running();
}

/**
 * \brief the timer to fade the window from time to time.
 * \param owner the timer event number
 */
void MessageDlg::Fade(MessageDlg* owner )
{
  // make it thread safe
  try
  {
    owner->DoFade();
  }
  catch ( ... )
  {
    // ignore the errors.
    // something broke ... somewhere.
  }

  // close it
  owner->CloseFromThread();
}

/**
 * \brief do the actual fading.
 */
void MessageDlg::DoFade() const
{
  // if we do not want to show the message, we might as well hide it right away.
  if ((_totalMilisecondsToShowMessage+_elapseMiliSecondsBeforeFadeOut) <= 0)
  {
    return;
  }

  // where we want the transparancy to start from, (we will end at zero)
  const auto startTransparency = GetStartTransparency();

  // if we want to show the message for a total of _totalMilisecondsToShowMessage
  // but we want to wait for _elapseMiliSecondsBeforeFadeOut before we go
  // how many milliseconds do we have before we need to fade out.
  const auto timeLeftForFadeOutMilliseconds = _totalMilisecondsToShowMessage - _elapseMiliSecondsBeforeFadeOut;

  // and given that we have 'startTransparency' steps to fade out in
  // the number of milliseconds between each steps is ...
  // the sleep time _could_ be zero
  const auto waitTimeBetweenFadeStepsInMilliseconds = static_cast<long>(static_cast<double>(timeLeftForFadeOutMilliseconds) / static_cast<double>(startTransparency));

  // show the message without any fadding.
  for (auto timeToSleptInMilliseconds = 0;
    timeToSleptInMilliseconds < _elapseMiliSecondsBeforeFadeOut;
    timeToSleptInMilliseconds += (waitTimeBetweenFadeStepsInMilliseconds <= 0 ? 1 : waitTimeBetweenFadeStepsInMilliseconds)
    )
  {
    // if we have been asked to stop ... then stop right away.
    if (Stopped())
    {
      return;
    }

    // then show the window a little.
    ShowMessageWithNoFadding(waitTimeBetweenFadeStepsInMilliseconds);
  }

  // we can now start fading down toward 'hidden' so the total time
  // should be near our target time of '_totalMilisecondsToShowMessage'
  for (auto currentTransparancy = startTransparency;
       currentTransparancy > 0;
       --currentTransparancy)
  {
    // if we have been asked to stop ... then stop right away.
    if (Stopped())
    {
      return;
    }

    // set the transparancy
    SetTransparency(currentTransparancy);

    // show the message a little bit more.
    ShowMessageWithNoFadding(waitTimeBetweenFadeStepsInMilliseconds);
  }
}

void MessageDlg::ShowMessageWithNoFadding(const long milliseconds) const
{
  if (milliseconds <= 0)
  {
    return;
  }

  // sleep a little.
  std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));

  // pump the message
  myodd::wnd::MessagePump( GetSafeHwnd() );
}

/**
 * \brief we cannot close the window from inside a thread
 *        so we post a message here, so the owning thread can call destroy window.
 */
void MessageDlg::CloseFromThread()
{
  CommonWnd::Close();

  // close it
  //_worker.WaitForAllWorkers([&]()
  // {
  //   myodd::wnd::MessagePump(GetSafeHwnd());
  //   myodd::wnd::MessagePump(nullptr);
  //   return true;
  // });
}

/**
 * \brief function called every time we are repainting the window.
 * \see CDialog::OnPaint
 */
void MessageDlg::OnPaint()
{
  const auto mainHdc = GetDC(GetSafeHwnd());
  const auto myDc = new ActionMonitorMemDC(CDC::FromHandle(mainHdc ));
  const auto hdc = myDc->GetSafeHdc();

  try
  {
    // show the background
    RedrawBackground(hdc);

    // the text
    RedrawMessage(hdc);
  }
  catch(...)
  {
    // something broke
    // but we must still free thr resources.
  }

  delete myDc;
  ReleaseDC(GetSafeHwnd(), mainHdc );
}

/**
 * \brief draw the message in the device context.
 * \param hdc the handle to the device context we are working in.
 */
void MessageDlg::RedrawMessage(const HDC hdc)
{
  //  get the font that we will be using for display
  //  because of the XML config this is only really used for size.
  const auto pOldFont = SelDisplayFont(hdc, 35 );

  RECT r = { 0,0,0,0 };
  myodd::html::html(hdc, _mStdMessage.c_str(), _mStdMessage.length(), &r, DT_DEFAULT | DT_CALCRECT);

  //  pad a little
  r.left += static_cast<int>(::myodd::config::Get(L"commands\\pad.x", 2));
  r.top += static_cast<int>(::myodd::config::Get(L"commands\\pad.y", 2));

  myodd::html::html(hdc, _mStdMessage.c_str(), _mStdMessage.length(), &r, DT_DEFAULT);

  //  clean up old fonts
  if (pOldFont != nullptr)
  {
    SelectObject(hdc, pOldFont);
  }
}

/**
 * \brief draw the background in the device context.
 *        this is the un-faded background.
 *        the fade wnd will do the fading for us.
 * \param hdc the handle to the device context we are working in.
 */
void MessageDlg::RedrawBackground( const HDC hdc) const
{
  SetBkMode(hdc, TRANSPARENT);

  const auto colour = ::GetSysColor(COLOR_3DFACE);
  const auto hBrush = CreateSolidBrush(colour);
  FillRect(hdc, &_completeRect, hBrush);

  DeleteObject(hBrush);
}

/**
 * \brief initialise the dialog.
 */
bool MessageDlg::OnInitDialog()
{
  // call the parent now
  if( !CommonWnd::OnInitDialog() )
  {
    return false;
  }

  HideTaskBar();

  // tell the fade window who the parent window is.
  SetFadeParent( GetSafeHwnd() );

  // move the window at the right place/size
  InitWindowPos();

  // all done.
  return true;
}

/**
 * \brief start the thread to fade the window.
 */
void MessageDlg::Show()
{
  // fade the window a little.
  ShowWindow(GetSafeHwnd(), SW_SHOW);
  ::UpdateWindow(GetSafeHwnd());
  SetTransparency( GetStartTransparency() );

  // start the worker.
  _worker.QueueWorker(&MessageDlg::Fade, this);
}

/**
 * \brief get the start transparency and make sure that it falls within range.
 * \return safe start transparency
 */
unsigned char MessageDlg::GetStartTransparency()
{
  const auto transparency = ::myodd::config::Get(L"commands\\transparency", DEFAULT_TRANSPARENCY);
  if( transparency < 0 )
  {
    return DEFAULT_TRANSPARENCY;
  }
  return transparency > MAX_TRANSPARENCY ? DEFAULT_TRANSPARENCY : transparency;
}

/**
 * \brief kill the window and wait for it to complete.
 *        this is a static function so we can call it with workers.
 * \param owner the owner of the window we are closing.
 */
void MessageDlg::Close(MessageDlg* owner)
{
  try
  {
    owner->FadeCloseWindow();
  }
  catch(...)
  {
    // it is posible that the deleted window
    // tried to close the message
  }
}

/**
 * \brief kill the window and wait for it to complete.
 */
void MessageDlg::FadeCloseWindow()
{
  // are we done already?
  if ( !IsRunning() )
  {
    // close the window.
    CloseFromThread();
    return;
  }

  // stop all
  Stop();

  // pump the remaining messages

  // wait for all the workers to finish.
  _worker.WaitForAllWorkers([&]()
  {
    myodd::wnd::MessagePump(GetSafeHwnd() );
    if (GetSafeHwnd() != nullptr)
    {
      myodd::wnd::MessagePump(nullptr);
    }
    return true;
  });
}


text:
package org.apache.pinot.core.operator.streaming;

import com.google.protobuf.ByteString;
import java.io.IOException;
import org.apache.pinot.common.proto.Server;
import org.apache.pinot.common.utils.CommonConstants.Query.Response;
import org.apache.pinot.common.utils.DataTable;

public class StreamingResponseUtils {
  private StreamingResponseUtils() {
  }

  public static Server.ServerResponse getDataResponse(DataTable dataTable)
      throws IOException {
    return getResponse(dataTable, Response.ResponseType.DATA);
  }

  public static Server.ServerResponse getMetadataResponse(DataTable dataTable)
      throws IOException {
    return getResponse(dataTable, Response.ResponseType.METADATA);
  }

  public static Server.ServerResponse getNonStreamingResponse(DataTable dataTable)
      throws IOException {
    return getResponse(dataTable, Response.ResponseType.NON_STREAMING);
  }

  private static Server.ServerResponse getResponse(DataTable dataTable, String responseType)
      throws IOException {
    return Server.ServerResponse.newBuilder().putMetadata(Response.MetadataKeys.RESPONSE_TYPE, responseType)
        .setPayload(ByteString.copyFrom(dataTable.toBytes())).build();
  }
}


text:
namespace base {
class Value;
}

namespace extensions {

class ChromeosInfoPrivateGetFunction : public ExtensionFunction {
 public:
  ChromeosInfoPrivateGetFunction();

 protected:
  ~ChromeosInfoPrivateGetFunction() override;

  // ExtensionFunction:
  ResponseAction Run() override;

 private:
  // Returns a newly allocate value, or null.
  std::unique_ptr<base::Value> GetValue(const std::string& property_name);

  DECLARE_EXTENSION_FUNCTION("chromeosInfoPrivate.get", CHROMEOSINFOPRIVATE_GET)
};

class ChromeosInfoPrivateSetFunction : public ExtensionFunction {
 public:
  ChromeosInfoPrivateSetFunction();

 protected:
  ~ChromeosInfoPrivateSetFunction() override;

  // ExtensionFunction:
  ResponseAction Run() override;

 private:
  DECLARE_EXTENSION_FUNCTION("chromeosInfoPrivate.set", CHROMEOSINFOPRIVATE_SET)
};

}  // namespace extensions

#endif  // CHROME_BROWSER_CHROMEOS_EXTENSIONS_INFO_PRIVATE_API_H_


text:
import mock

from quantum.db import api as db
from quantum.openstack.common import importutils
from quantum.plugins.cisco.common import cisco_constants as const
from quantum.plugins.cisco.nexus import cisco_nexus_plugin_v2
from quantum.tests import base

NEXUS_IP_ADDRESS = '1.1.1.1'
NEXUS_USERNAME = 'username'
NEXUS_PASSWORD = 'password'
HOSTNAME = 'testhost'
INSTANCE = 'testvm'
NEXUS_PORTS = '1/10'
NEXUS_SSH_PORT = '22'
NEXUS_DRIVER = ('quantum.plugins.cisco.nexus.'
                'cisco_nexus_network_driver_v2.CiscoNEXUSDriver')

class TestCiscoNexusPlugin(base.BaseTestCase):

    def setUp(self):
        """Set up function."""
        super(TestCiscoNexusPlugin, self).setUp()
        self.tenant_id = "test_tenant_cisco1"
        self.net_name = "test_network_cisco1"
        self.net_id = 000007
        self.vlan_name = "q-" + str(self.net_id) + "vlan"
        self.vlan_id = 267
        self.second_net_name = "test_network_cisco2"
        self.second_net_id = 000005
        self.second_vlan_name = "q-" + str(self.second_net_id) + "vlan"
        self.second_vlan_id = 265
        self._nexus_switches = {
            (NEXUS_IP_ADDRESS, HOSTNAME): NEXUS_PORTS,
            (NEXUS_IP_ADDRESS, 'ssh_port'): NEXUS_SSH_PORT,
        }
        self._hostname = HOSTNAME

        def new_nexus_init(self):
            self._client = importutils.import_object(NEXUS_DRIVER)
            self._nexus_ip = NEXUS_IP_ADDRESS
            self._nexus_username = NEXUS_USERNAME
            self._nexus_password = NEXUS_PASSWORD
            self._nexus_ports = NEXUS_PORTS
            self._nexus_ssh_port = NEXUS_SSH_PORT
            self.credentials = {
                self._nexus_ip: {
                    'username': self._nexus_username,
                    'password': self._nexus_password
                }
            }
            db.configure_db()

        # Use a mock netconf client
        mock_ncclient = mock.Mock()
        self.patch_obj = mock.patch.dict('sys.modules',
                                         {'ncclient': mock_ncclient})
        self.patch_obj.start()

        with mock.patch.object(cisco_nexus_plugin_v2.NexusPlugin,
                               '__init__', new=new_nexus_init):
            self._cisco_nexus_plugin = cisco_nexus_plugin_v2.NexusPlugin()
            self._cisco_nexus_plugin._nexus_switches = self._nexus_switches

        self.addCleanup(self.patch_obj.stop)

    def test_create_networks(self):
        """Tests creation of two new Virtual Networks."""
        tenant_id = self.tenant_id
        net_name = self.net_name
        net_id = self.net_id
        vlan_name = self.vlan_name
        vlan_id = self.vlan_id
        second_net_name = self.second_net_name
        second_net_id = self.second_net_id
        second_vlan_name = self.second_vlan_name
        second_vlan_id = self.second_vlan_id

        new_net_dict = self._cisco_nexus_plugin.create_network(
            tenant_id, net_name, net_id,
            vlan_name, vlan_id, self._hostname, INSTANCE)
        self.assertEqual(new_net_dict[const.NET_ID], net_id)
        self.assertEqual(new_net_dict[const.NET_NAME], self.net_name)
        self.assertEqual(new_net_dict[const.NET_VLAN_NAME], self.vlan_name)
        self.assertEqual(new_net_dict[const.NET_VLAN_ID], self.vlan_id)

        new_net_dict = self._cisco_nexus_plugin.create_network(
            tenant_id, second_net_name, second_net_id,
            second_vlan_name, second_vlan_id, self._hostname,
            INSTANCE)

        self.assertEqual(new_net_dict[const.NET_ID], second_net_id)
        self.assertEqual(new_net_dict[const.NET_NAME], self.second_net_name)
        self.assertEqual(new_net_dict[const.NET_VLAN_NAME],
                         self.second_vlan_name)
        self.assertEqual(new_net_dict[const.NET_VLAN_ID], self.second_vlan_id)

    def test_nexus_delete_port(self):
        """Test deletion of a vlan."""
        self._cisco_nexus_plugin.create_network(
            self.tenant_id, self.net_name, self.net_id, self.vlan_name,
            self.vlan_id, self._hostname, INSTANCE)

        expected_instance_id = self._cisco_nexus_plugin.delete_port(
            INSTANCE, self.vlan_id)

        self.assertEqual(expected_instance_id, INSTANCE)


text:
using System;
using Server;
using Server.Items;

namespace Server.Mobiles
{
	[CorpseName( "a flesh golem corpse" )]
	public class FleshGolem : BaseCreature
	{
		public override WeaponAbility GetWeaponAbility()
		{
			return WeaponAbility.BleedAttack;
		}

		[Constructable]
		public FleshGolem() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
		{
			Name = "a flesh golem";
			Body = 304;
			BaseSoundID = 684;

			SetStr( 176, 200 );
			SetDex( 51, 75 );
			SetInt( 46, 70 );

			SetHits( 106, 120 );

			SetDamage( 18, 22 );

			SetDamageType( ResistanceType.Physical, 100 );

			SetResistance( ResistanceType.Physical, 50, 60 );
			SetResistance( ResistanceType.Fire, 25, 35 );
			SetResistance( ResistanceType.Cold, 15, 25 );
			SetResistance( ResistanceType.Poison, 60, 70 );
			SetResistance( ResistanceType.Energy, 30, 40 );

			SetSkill( SkillName.MagicResist, 50.1, 75.0 );
			SetSkill( SkillName.Tactics, 55.1, 80.0 );
			SetSkill( SkillName.Wrestling, 60.1, 70.0 );

			Fame = 1000;
			Karma = -1800;

			VirtualArmor = 34;
		}

		public override void GenerateLoot()
		{
			AddLoot( LootPack.Average );
		}

		public override bool BleedImmune{ get{ return true; } }
		public override int TreasureMapLevel{ get{ return 1; } }

		public FleshGolem( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 );
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}
}


text:
This repository contains the Dockerfile for a Ruby 2.1.5 image based on Debian Wheezy.

## Usage

This image has no default command, so it must be specified when running a container. For an interactive Bash shell:

``` bash
docker run -t -i sirhopcount/ruby2 /bin/bash
```

## License

    Author:: Adrian van Dongen (github@goodfellasonline.nl)
    Copyright:: Copyright (c) 2014 Adrian van Dongen
    License:: Apache License, Version 2.0

    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.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using AskAndAnswer;

namespace DB
{
    /// <summary>
    /// Summary description for clsDB
    /// This object uses the database connection defined in ConfigurationManager.ConnectionStrings[clsK.defaultConnStr].ConnectionString;
    /// </summary>
    public class clsDB
    {
        private SqlConnection m_c = new SqlConnection();

        private Int64 m_NAffectedRows = -1;
        /// <summary>
        /// Contains the number of rows affected when you call ExecuteNonQuery method
        /// </summary>
        public Int64 NAffectedRows
        {
            get
            {
                return m_NAffectedRows;
            }
        }

        public enum SPExMode
        {
            READER,
            SCALAR,
            NONQUERY
        }

        //Class variables
        //The connection string used in the project's Web.config file; used to connect to the Help Database
        private string m_connStr = ConfigurationManager.ConnectionStrings[AAAK.defaultConnStr].ConnectionString;

        private string m_errMsg = "";
        public string ErrMsg
        {
            get
            {
                return m_errMsg;
            }
        }
        /// <summary>
        /// Instatiate an instance of this object.
        /// </summary>
        /// <param name="newConnStr">Override the default value of this connection string, which is defined in clsK.defaultConnStr</param>
        public clsDB(string newConnStr = "")
        {
            if (newConnStr != "")
            {
                m_connStr = newConnStr;
            }
        }

        public SqlConnection getC()
        {
            return new SqlConnection(m_connStr);
        }

        public SqlConnection OpenConnection()
        {
            m_c = new SqlConnection(m_connStr);
            m_c.Open();
            return m_c;
        }
        public void CloseConnection()
        {
            m_c.Close();
        }

        /// <summary>
        /// Tests a connection to the database that uses connection string stored in m_connStr
        /// </summary>
        /// <returns></returns>
        public bool TestConnection()
        {
            try
            {
                using (var c = getC())
                {
                    c.Open();
                }
                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// Converts the database object into a string;
        /// If object is null, return ""
        /// </summary>
        /// <param name="dbVal"></param>
        /// <param name="valIfNull">Value to return if null, e.g., N/A.  Returns "" if unspecified</param>
        /// <returns></returns>
        public string Fld2Str(object dbVal, string valIfNull = "")
        {
            try
            {
                if (dbVal != DBNull.Value)
                {
                    return Convert.ToString(dbVal);
                } else
                {
                    return valIfNull;
                }
            } catch (Exception ex)
            {
                return "Error in Method Fld2str for " + dbVal.ToString() + " " + ex.Message;
            }
        }

        /// <summary>
        /// Returns a DBNull object for an empty string.
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public object EmptyStr2Null(string val)
        {
            try
            {
                if (val == "")
                {
                    return DBNull.Value;
                } else
                {
                    return val;
                }
            }
            catch (Exception ex)
            {
                return "Error in Method Fld2str for " + val + " " + ex.Message;
            }
        }
        /// <summary>
        /// Returns the result of a Stored Procedure; you must make sure the connection is open before calling this function
        /// </summary>
        /// <param name="storedProcName">Nameof stored procedure</param>
        /// <param name="ps">Collection of Parameters required by the Stored Procuedure.</param>
        /// <param name="executionMode">Execution mode of Stored Procedure.  This determines the type of object returned.</param>
        /// <returns></returns>
        public Object ExecuteSP(string storedProcName,
                                List<SqlParameter> ps,
                                SPExMode executionMode,
                                ref SqlCommand generatedSQLcmd)
        {
            try
            {
                //Create the command object
                SqlCommand cmd = new SqlCommand(storedProcName, m_c);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                //Add parameters from user-supplied list of parameters ps to the command
                if (ps != null)
                {
                    foreach (SqlParameter p in ps)
                    {
                        cmd.Parameters.Add(p);
                    }
                }

                generatedSQLcmd = cmd;
                //Open the connection

                    switch (executionMode)
                    {
                        case SPExMode.NONQUERY:
                            int y = (int)cmd.ExecuteNonQuery();
                            //cmd.ExecuteNonQuery();
                            return y;
                        case SPExMode.READER:
                            SqlDataReader dR = cmd.ExecuteReader();
                            return dR;
                        case SPExMode.SCALAR:
                            return cmd.ExecuteScalar();
                    }

                return null;
            }
            catch (Exception ex)
            {
                m_errMsg = (ex.Message + AAAK.vbCRLF + ex.StackTrace).Replace(AAAK.vbCRLF,"<br/>");
                return ex.Message;
            }
        }

        public Boolean ExecuteNonQuery(string nonQueryToExecute)
        {
            try
            {
                m_NAffectedRows = -1;
                using (m_c)
                {
                    if (m_c.State != ConnectionState.Open)
                    {
                        m_c.Open();
                    }
                    SqlCommand cmd = new SqlCommand(nonQueryToExecute, m_c);
                    m_NAffectedRows = cmd.ExecuteNonQuery();

                }
                return true;
            } catch (Exception ex)
            {
                m_errMsg = ex.Message + AAAK.vbCRLF + ex.StackTrace;
                return false;
            }
        }
        /// <summary>
        /// Converts a column name into an SQL Server Parameter name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string makeParameterName(string name)
        {
            return "@" + name;
        }

        /// <summary>
        /// Return an SQL output parameter
        /// </summary>
        /// <param name="parameterName">Name of parameter; you must supply "@"</param>
        /// <param name="dType">Data Type; use System.Data.SqlDbType type</param>
        /// <param name="size">Size of parameter; default is 1000000000</param>
        /// <returns></returns>
        public SqlParameter makeOutputParameter(string parameterName, SqlDbType dType, int size = 1000000000)
        {
            try
            {
                SqlParameter p = new SqlParameter();
                p.ParameterName = parameterName;
                p.Size = size;
                p.Direction = ParameterDirection.Output;
                return p;
            } catch (Exception ex)
            {
                return new SqlParameter();
            }
        }

        public SqlParameter makeReturnParameter(SqlDbType dType, string parameterName = "@returnVal")
        {
            try
            {
                SqlParameter p = new SqlParameter();
                p.ParameterName = parameterName;
                p.Direction = ParameterDirection.ReturnValue;
                return p;
            }
            catch (Exception ex)
            {
                return new SqlParameter();
            }
        }

        /// <summary>
        /// Converts an object from a database to a string.
        /// If the object is Null, return an empty string ("")
        /// </summary>
        /// <param name="dbVal"></param>
        /// <returns></returns>

        /// <summary>
        /// Puts the key value pair with fkAppID = appID that is defined in webKVP into the application object.
        /// To access the dictionary, use key "kvpd_[APPID]"
        /// To access the list, use key "kvpl_[APPID]"
        /// </summary>
        /// <param name="appID"></param>
        public void PutKVPInDictionary(Int64 appID)
        {
            try
            {
                Dictionary<string, string> d = new Dictionary<String, string>();
                List<string> l = new List<string>();
                clsDB myDB = new clsDB();
                SqlCommand cmd = new SqlCommand();
                List<SqlParameter> ps = new List<SqlParameter>();
                ps.Add(new SqlParameter("@" + DBK.fkGROUPID, appID));
                using (myDB.OpenConnection())
                {
                    using (SqlDataReader dR = (SqlDataReader)myDB.ExecuteSP(DBK.SP.spGETWEBKEYVALUEPAIRINFO, ps,
                        clsDB.SPExMode.READER, ref cmd))
                    {
                        if (dR != null && dR.HasRows)
                        {
                            while (dR.Read())
                            {
                                d.Add(Convert.ToString(dR[DBK.keyACTUALVALUE]), Convert.ToString(dR[DBK.valDISPLAYEDVALUE]));
                                l.Add(Convert.ToString(dR[DBK.keyACTUALVALUE]));
                                l.Add(Convert.ToString(dR[DBK.valDISPLAYEDVALUE]));
                            }

                        }
                    }
                }

                HttpContext.Current.Application["kvpd_" + Convert.ToString(appID)] = d;
                HttpContext.Current.Application["kvpl_" + Convert.ToString(appID)] = l;
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
        }

        /// <summary>
        /// Puts the key value pair that you obtain from a storedProcedure into the application object.
        /// To access the dictionary, use key "kvpd_[spName]"
        /// To access the list, use key "kvpl_[spName]"
        /// </summary>
        /// <param name="appID"></param>
        public void PutKVPInDictionary(string spName)
        {
            try
            {
                Dictionary<string, string> d = new Dictionary<String, string>();
                List<string> l = new List<string>();
                clsDB myDB = new clsDB();
                SqlCommand cmd = new SqlCommand();
                using (myDB.OpenConnection())
                {
                    using (SqlDataReader dR = (SqlDataReader)myDB.ExecuteSP(spName, null,
                        clsDB.SPExMode.READER, ref cmd))
                    {
                        if (dR != null && dR.HasRows)
                        {
                            while (dR.Read())
                            {
                                d.Add(Convert.ToString(dR[DBK.keyACTUALVALUE]), Convert.ToString(dR[DBK.valDISPLAYEDVALUE]));
                                l.Add(Convert.ToString(dR[DBK.keyACTUALVALUE]));
                                l.Add(Convert.ToString(dR[DBK.valDISPLAYEDVALUE]));
                            }

                        }
                    }
                }

                HttpContext.Current.Application["kvpd_" + spName] = d;
                HttpContext.Current.Application["kvpl_" + spName] = l;
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
        }
    }
}


text:
import utils

import forms

# width, dateFormat, renderer, hidden, align, type

class SimpleGrid(object):
    def to_grid(self, fields, rows, totalcount = None, json_add = {}, sort_field = 'id', sort_direction = 'DESC'):
        if not totalcount:
            totalcount = len(rows)
        jdict = {
            'success':True
           ,'metaData':{
                'root':'rows'
                ,'totalProperty':'totalCount'
                ,'successProperty':'success'
                ,'sortInfo':{
                   'field': sort_field
                   ,'direction': sort_direction
                }
                ,'fields':fields
                }
                ,'rows':rows
                ,'totalCount':totalcount
            }
        return utils.JSONserialise(jdict)

class VirtualField(object):
    def __init__(self, name):
        self.name = name

class ModelGrid(object):

    def __init__(self, model):
        self.model = model      # the model to use as reference
        self.fields = []        # holds the extjs fields
        self.base_fields = []   # holds the base model fields

        model_fields = self.model._meta._fields()
        excludes = getattr(self.Meta, 'exclude', [])
        # reorder cols if needed
        order = getattr(self.Meta, 'order', None)
        if order and len(order) > 0:
            for field in order:
                added = False
                for f in model_fields:
                    if f.name == field:
                        added = True
                        self.base_fields.append(f)
                if not added:
                    self.base_fields.append(VirtualField(field))
        else:
            self.base_fields = model_fields

        for field in self.base_fields:
            if field.name in excludes:
                continue
            if field.__class__.__name__ == VirtualField:
                self.fields.append(self.Meta.fields_conf[field.name])
                continue
            fdict = {'name':field.name, 'header': field.name}

            if getattr(field, 'verbose_name', None) and field.verbose_name != field.name:
                fdict['tooltip'] = u'%s' %  field.verbose_name

            if field.name == 'id':
                fdict['id']='id'
            if  field.__class__.__name__ == 'DateTimeField':
                fdict['type'] = 'datetime'
                fdict['xtype'] = 'datecolumn'
                fdict['dateFormat'] = 'Y-m-d H:i:s'
                fdict['format'] = 'Y-m-d H:i:s'

                #fdict['editor'] = "new Ext.ux.form.DateTime({hiddenFormat:'Y-m-d H:i', dateFormat:'Y-m-D', timeFormat:'H:i'})"
            if  field.__class__.__name__ == 'DateField':
                fdict['type'] = 'date'
                fdict['xtype'] = 'datecolumn'
                fdict['dateFormat'] = 'Y-m-d'
                fdict['format'] = 'Y-m-d'
                #fdict['renderer'] = 'Ext.util.'
                #fdict['editor'] = "new Ext.form.DateField({format:'Y-m-d'})"
            elif field.__class__.__name__ == 'IntegerField':
                fdict['xtype'] = 'numbercolumn'
                #fdict['editor'] = 'new Ext.form.NumberField()'
            elif field.__class__.__name__ == 'BooleanField':
                fdict['xtype'] = 'booleancolumn'
                #fdict['editor'] = 'new Ext.form.Checkbox()'
            elif field.__class__.__name__ == 'DecimalField':
                fdict['xtype'] = 'numbercolumn '
                fdict['renderer'] = 'function(v) {return (v.toFixed && v.toFixed(2) || 0);}'
                #fdict['editor'] = 'new Ext.form.NumberField()'
            elif  field.__class__.__name__ == 'ForeignKey':
                pass
                # renderer : display FK str
                # choices
            elif field.choices:
                #print 'FIELD CHOICES', field.choices
                a = {}
                for c in field.choices:
                    a[c[0]] = c[1]
                fdict['renderer'] = 'function(v) {a = %s; return a[v] || "";}' % utils.JSONserialise(a)
            if getattr(self.Meta, 'fields_conf', {}).has_key(field.name):
                fdict.update(self.Meta.fields_conf[field.name])

               # print fdict
            self.fields.append(fdict)
        #for field in self.model:
        #    print field

    def get_field(self, name):
        for f in self.fields:
            if f.get('name') == name:
                return f
        return None
    def get_base_field(self, name):
        for f in self.base_fields:
            if f.name == name:
                return f
        return None
    def get_fields(self, colModel):
        """ return this grid field list
            . can include hidden fields
            . A given colModel can order the fields and override width/hidden properties
        """
        # standard fields
        fields = self.fields
        # use the given colModel to order the fields
        if colModel and colModel.get('fields'):
            fields = []
            for f in colModel['fields']:
                for cf in self.fields:
                    if cf['name'] == f['name']:
                        config_field = cf
                        if f.get('width'):
                            config_field['width'] = f.get('width')
                        # force hidden=False if field present in given colModel
                        if f.get('hidden') == True:
                            config_field['hidden'] = True
                        else:
                            config_field['hidden'] = False
                        fields.append(config_field)
        return fields

    def get_rows(self, fields, queryset, start, limit):
        """
            return the row list from given queryset
            order the data based on given field list
            paging from start,limit
        """
        rows = []
        if queryset:
            if limit > 0:
                queryset = queryset[int(start):int(start) + int(limit)]
            fields_items = []
            for item in queryset:
                field_items = []
                rowdict = {}
                for field in fields:
                    val = getattr(item, field['name'], '')
                    if val:
                        if field.get('type', '') == 'date':
                            val = val.strftime(utils.DateFormatConverter(to_python = field['format'] ) )
                        elif field.get('type', '') == 'datetime':
                            val = val.strftime(utils.DateFormatConverter(to_python = field['format'] ) )
                        else:
                            val = utils.JsonCleanstr(val)
                    else:
                        if field.get('type', '') == 'float':
                            val = 0.0
                        elif field.get('type', '') == 'int':
                            val = 0
                        else:
                            val = ''
                    #astr = utils.JSONserialise_dict_item(field['name'], val)
                    rowdict[field['name']] = val
                    #field_items.append(astr)
                #fields_items.append('{%s}' % ','.join(field_items))
                rows.append(rowdict)
            #json += ','.join(fields_items)
            #json += ']\n'

        return rows

    def to_grid(self, queryset, start = 0, limit = 0, totalcount = None, json_add = {}, colModel = None, sort_field = 'id', sort_direction = 'DESC'):
        """ return the given queryset as an ExtJs grid config
            includes full metadata (columns, renderers, totalcount...)
            includes the rows data
            to be used in combination with Ext.ux.AutoGrid
        """
        if not totalcount:
            totalcount = queryset.count()

        base_fields = self.get_fields(colModel)

        # todo : stupid ?
        id_field = base_fields[0]['name']

        jsondict = {
             'succes':True
            ,'metaData':{
                 'root':'rows'
                ,'totalProperty':'totalCount'
                ,'successProperty':'success'
                ,'idProperty':id_field
                ,'sortInfo':{
                   "field": sort_field
                   ,"direction": sort_direction
                }
                ,'fields':base_fields
            }
            ,'rows':self.get_rows(base_fields, queryset, start, limit)
            ,'totalCount':totalcount
        }

        if json_add:
            jsondict.update(json_add)

        return utils.JSONserialise(jsondict)

    class Meta:
        exclude = []
        order = []
        fields_conf = {}

class EditableModelGrid(ModelGrid):
    def __init__(self, *args, **kwargs):
        super(EditableModelGrid, self).__init__(*args, **kwargs)
        # add editors
        for field in self.base_fields:
            field_conf = self.get_field(field.name)
            f = self.get_base_field(field.name)
           # print dir(f)
            #print 'base_field', f, f.widget
            if field_conf and not (getattr(self.Meta, 'fields_conf', {}).has_key(field.name) and self.Meta.fields_conf[field.name].has_key('editor')):
                field_conf['editor'] = forms.getFieldConfig(field.name, field)
                #print 'getFieldConfig editor', field.name, field_conf['editor']

    def update_instances_from_json(self, json, insert_new = True):
        """ udpate this grid model instances from provided json
            json example : update=[{"id":1, "username":"root2","first_name":"", "last_name":"bouqui", "is_staff":false, "is_superuser":true}]
            only modified data is sent from client
        """
        from django.utils import simplejson
        items = simplejson.loads(json)

        forms_items = []
        forms_valid = True
        errors = []
        for item_data in items:
            # get instance for this line
            # todo : dynamic pk
            pk = item_data.get('id', None)
            form_data = item_data.copy()
            del form_data['id']
            instance = self.model()
           # print pk, form_data
            if pk:
                # get the related instance
                instance = self.model.objects.get(pk = pk)
            else:
                if not insert_new:
                    # skip if new and dont insert
                    continue
            # get a ModelForm based on supplied fields
            # todo : force mandatory fields !

            form = forms.getExtJsModelForm(self.model, fields_list = form_data.keys())
            form = form(form_data, instance = instance)
            forms_items.append(form)
            if not form.is_valid():
                print 'invalid form', form.errors
                errors.append(form.errors)

        if not errors:
            for form in forms_items:
                form.save()
            return True
        else:
            # todo : detailed errors
            raise Exception(errors)


text:
<?php

namespace DonatelloZa\RakePlus;

use InvalidArgumentException;

class RakePlus
{
    /** @var string */
    protected $language = 'en_US';

    /** @var string */
    protected $language_file = "";

    /** @var string|null */
    private $pattern = null;

    /** @var array */
    private $phrase_scores = [];

    /** @var int */
    private $min_length = 0;

    /** @var bool */
    private $filter_numerics = true;

    /** @var string */
    private $sentence_regex;

    /** @var string */
    private $line_terminator;

    /** @var bool */
    public $mb_support = false;

    /** @var LangParseOptions */
    public $parseOptions;

    const ORDER_ASC = 'asc';

    const ORDER_DESC = 'desc';

    /**
     * RakePlus constructor. Instantiates RakePlus and extracts
     * the key phrases from the text if supplied.
     *
     * If $stopwords is a string the method will:
     *
     * 1) Determine if it is has a .pattern or .php extension and if
     *    so will attempt to load the stopwords from the specified path
     *    and filename.
     * 2) If it does not have a .pattern or .php extension, it will assume
     *    that a language string was specified and will then attempt to
     *    read the stopwords from lang/xxxx.pattern or lang/xxxx.php, where
     *    xxxx is the language string (default: en_US)
     *
     * If $stopwords os an array it will simply use the array of stopwords
     * as provided.
     *
     * If $stopwords is a derived instance of StopwordAbstract it will simply
     * retrieve the stopwords from the instance.
     *
     * @param string|null                           $text              Text to turn into keywords/phrases.
     * @param AbstractStopwordProvider|string|array $stopwords         Stopwords/language to use.
     * @param int                                   $phrase_min_length Minimum keyword/phrase length.
     * @param bool                                  $filter_numerics   Filter out numeric numbers.
     * @param null|LangParseOptions                 $parseOptions      Additional text parsing options, see:
     *                                                                 @LangParseOptions
     */
    public function __construct($text = null, $stopwords = 'en_US', $phrase_min_length = 0, $filter_numerics = true,
                                $parseOptions = null)
    {
        $this->mb_support = extension_loaded('mbstring');

        $this->setMinLength($phrase_min_length);
        $this->setFilterNumerics($filter_numerics);

        if ($parseOptions === null) {
            $this->parseOptions = LangParseOptions::create($stopwords);
        } else if ($parseOptions instanceof ILangParseOptions) {
            $this->parseOptions = $parseOptions;
        } else {
            throw new InvalidArgumentException("The \$parseOptions argument must be an instance of ILangParseOptions.");
        }

        $this->sentence_regex = $this->parseOptions->getSentenceRegex();
        $this->line_terminator = $this->parseOptions->getLineTerminator();

        if (!is_null($text)) {
            $this->extract($text, $stopwords);
        }
    }

    /**
     * Instantiates a RakePlus instance and extracts
     * the key phrases from the text.
     *
     * If $stopwords is a string the method will:
     *
     * 1) Determine if it is has a .pattern or .php extension and if
     *    so will attempt to load the stopwords from the specified path
     *    and filename.
     * 2) If it does not have a .pattern or .php extension, it will assume
     *    that a language string was specified and will then attempt to
     *    read the stopwords from lang/xxxx.pattern or lang/xxxx.php, where
     *    xxxx is the language string (default: en_US)
     *
     * If $stopwords os an array it will simply use the array of stopwords
     * as provided.
     *
     * If $stopwords is a derived instance of StopwordAbstract it will simply
     * retrieve the stopwords from the instance.
     *
     * @param string|null                           $text              Text to turn into keywords/phrases.
     * @param AbstractStopwordProvider|string|array $stopwords         Stopwords to use.
     * @param int                                   $phrase_min_length Minimum keyword/phrase length.
     * @param bool                                  $filter_numerics   Filter out numeric numbers.
     * @param null|LangParseOptions                 $parseOptions      Additional text parsing options, see:
     *                                                                 @LangParseOptions
     *
     * @return RakePlus
     */
    public static function create($text, $stopwords = 'en_US', $phrase_min_length = 0, $filter_numerics = true,
                                  $parseOptions = null)
    {
        return (new self($text, $stopwords, $phrase_min_length, $filter_numerics, $parseOptions));
    }

    /**
     * Extracts the key phrases from the text.
     *
     * If $stopwords is a string the method will:
     *
     * 1) Determine if it is has a .pattern or .php extension and if
     *    so will attempt to load the stopwords from the specified path
     *    and filename.
     * 2) If it does not have a .pattern or .php extension, it will assume
     *    that a language string was specified and will then attempt to
     *    read the stopwords from lang/xxxx.pattern or lang/xxxx.php, where
     *    xxxx is the language string (default: en_US)
     *
     * If $stopwords os an array it will simply use the array of stopwords
     * as provided.
     *
     * If $stopwords is a derived instance of StopwordAbstract it will simply
     * retrieve the stopwords from the instance.
     *
     * @param string                                $text
     * @param AbstractStopwordProvider|string|array $stopwords
     *
     * @return RakePlus
     */
    public function extract($text, $stopwords = 'en_US')
    {
        if ($text != '') {
            if (is_array($stopwords)) {
                $this->pattern = StopwordArray::create($stopwords)->pattern();
            } else if (is_string($stopwords)) {
                if (is_null($this->pattern) || ($this->language != $stopwords)) {
                    $extension = mb_strtolower(pathinfo($stopwords, PATHINFO_EXTENSION));
                    if (empty($extension)) {
                        // First try the .pattern file
                        $this->language_file = StopwordsPatternFile::languageFile($stopwords);
                        if (file_exists($this->language_file)) {
                            $this->pattern = StopwordsPatternFile::create($this->language_file)->pattern();
                        } else {
                            $this->language_file = StopwordsPHP::languageFile($stopwords);
                            $this->pattern = StopwordsPHP::create($this->language_file)->pattern();
                        }
                        $this->language = $stopwords;
                    } else if ($extension == 'pattern') {
                        $this->language = $stopwords;
                        $this->language_file = $stopwords;
                        $this->pattern = StopwordsPatternFile::create($this->language_file)->pattern();
                    } else if ($extension == 'php') {
                        $language_file = $stopwords;
                        $this->language = $stopwords;
                        $this->language_file = $language_file;
                        $this->pattern = StopwordsPHP::create($this->language_file)->pattern();
                    }
                }
            } elseif (is_subclass_of($stopwords, 'DonatelloZa\RakePlus\AbstractStopwordProvider')) {
                $this->pattern = $stopwords->pattern();
            } else {
                throw new InvalidArgumentException('Invalid stopwords list provided for RakePlus.');
            }

            if ($this->mb_support) {
                $sentences = $this->splitSentencesMb($text);
                $phrases = $this->getPhrasesMb($sentences, $this->pattern);
            } else {
                $sentences = $this->splitSentences($text);
                $phrases = $this->getPhrases($sentences, $this->pattern);
            }
            $word_scores = $this->calcWordScores($phrases);
            $this->phrase_scores = $this->calcPhraseScores($phrases, $word_scores);
        }

        return $this;
    }

    /**
     * Returns the extracted phrases.
     *
     * @return array
     */
    public function get()
    {
        return array_keys($this->phrase_scores);
    }

    /**
     * Returns the phrases and a score for each of
     * the phrases as an associative array.
     *
     * @return array
     */
    public function scores()
    {
        return $this->phrase_scores;
    }

    /**
     * Returns only the unique keywords within the
     * phrases instead of the full phrases itself.
     *
     * @return array
     */
    public function keywords()
    {
        $keywords = [];
        $phrases = $this->get();

        foreach ($phrases as $phrase) {
            $words = explode(' ', $phrase);
            foreach ($words as $word) {
                // This may look weird to the casual observer
                // but we do this since PHP will convert string
                // array keys that look like integers to actual
                // integers. This may cause problems further
                // down the line when a developer attempts to
                // append arrays to one another and one of them
                // have a mix of integer and string keys.
                if (!$this->filter_numerics || ($this->filter_numerics && !is_numeric($word))) {
                    if ($this->min_length === 0 || mb_strlen($word) >= $this->min_length) {
                        $keywords[$word] = $word;
                    }
                }
            }
        }

        return array_values($keywords);
    }

    /**
     * Sorts the phrases by score, use 'asc' or 'desc' to specify a
     * sort order.
     *
     * @param string $order Default is 'asc'
     *
     * @return $this
     */
    public function sortByScore($order = self::ORDER_ASC)
    {
        if ($order == self::ORDER_DESC) {
            arsort($this->phrase_scores);
        } else {
            asort($this->phrase_scores);
        }

        return $this;
    }

    /**
     * Sorts the phrases alphabetically, use 'asc' or 'desc' to specify a
     * sort order.
     *
     * @param string $order Default is 'asc'
     *
     * @return $this
     */
    public function sort($order = self::ORDER_ASC)
    {
        if ($order == self::ORDER_DESC) {
            krsort($this->phrase_scores);
        } else {
            ksort($this->phrase_scores);
        }

        return $this;
    }

    /**
     * Returns the current language being used.
     *
     * @return string
     */
    public function language()
    {
        return $this->language;
    }

    /**
     * Returns the language file that was loaded. Will
     * be null if no file is loaded.
     *
     * @return string|null
     */
    public function languageFile()
    {
        return $this->language_file;
    }

    /**
     * Splits the text into an array of sentences.
     *
     * @param string $text
     *
     * @return array
     */
    private function splitSentences($text)
    {
        return preg_split('/' . $this->sentence_regex . '/',
            preg_replace('/' . $this->line_terminator . '/', ' ', $text));
    }

    /**
     * Splits the text into an array of sentences. Uses mb_* functions.
     *
     * @param string $text
     *
     * @return array
     */
    private function splitSentencesMb($text)
    {
        return mb_split($this->sentence_regex,
            mb_ereg_replace($this->line_terminator, ' ', $text));
    }

    /**
     * Split sentences into phrases by using the stopwords.
     *
     * @param array  $sentences
     * @param string $pattern
     *
     * @return array
     */
    private function getPhrases(array $sentences, $pattern)
    {
        $results = [];

        foreach ($sentences as $sentence) {
            $phrases_temp = preg_replace($pattern, '|', $sentence);
            $phrases = explode('|', $phrases_temp);
            foreach ($phrases as $phrase) {
                $phrase = mb_strtolower(trim($phrase));
                if (!empty($phrase)) {
                    if (!$this->filter_numerics || ($this->filter_numerics && !is_numeric($phrase))) {
                        if ($this->min_length === 0 || mb_strlen($phrase) >= $this->min_length) {
                            $results[] = $phrase;
                        }
                    }
                }
            }
        }

        return $results;
    }

    /**
     * Split sentences into phrases by using the stopwords. Makes use of
     * PHP's mb_* functions.
     *
     * @param array  $sentences
     * @param string $pattern
     *
     * @return array
     */
    private function getPhrasesMb(array $sentences, $pattern)
    {
        $results = [];

        foreach ($sentences as $sentence) {
            $phrases_temp = mb_eregi_replace($pattern, '|', $sentence);
            $phrases = explode('|', $phrases_temp);
            foreach ($phrases as $phrase) {
                $phrase = mb_strtolower(preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $phrase));
                if (!empty($phrase)) {
                    if (!$this->filter_numerics || ($this->filter_numerics && !is_numeric($phrase))) {
                        if ($this->min_length === 0 || mb_strlen($phrase) >= $this->min_length) {
                            $results[] = $phrase;
                        }
                    }
                }
            }
        }

        return $results;
    }

    /**
     * Calculate a score for each word.
     *
     * @param array $phrases
     *
     * @return array
     */
    private function calcWordScores($phrases)
    {
        $frequencies = [];
        $degrees = [];

        foreach ($phrases as $phrase) {
            $words = $this->splitPhraseIntoWords($phrase);
            $words_count = count($words);
            $words_degree = $words_count - 1;

            foreach ($words as $w) {
                $frequencies[$w] = (isset($frequencies[$w])) ? $frequencies[$w] : 0;
                $frequencies[$w] += 1;
                $degrees[$w] = (isset($degrees[$w])) ? $degrees[$w] : 0;
                $degrees[$w] += $words_degree;
            }
        }

        foreach ($frequencies as $word => $freq) {
            $degrees[$word] += $freq;
        }

        $scores = [];
        foreach ($frequencies as $word => $freq) {
            $scores[$word] = (isset($scores[$word])) ? $scores[$word] : 0;
            $scores[$word] = $degrees[$word] / (float)$freq;
        }

        return $scores;
    }

    /**
     * Calculate score for each phrase by word scores.
     *
     * @param array $phrases
     * @param array $scores
     *
     * @return array
     */
    private function calcPhraseScores($phrases, $scores)
    {
        $keywords = [];

        foreach ($phrases as $phrase) {
            $keywords[$phrase] = (isset($keywords[$phrase])) ? $keywords[$phrase] : 0;
            $words = $this->splitPhraseIntoWords($phrase);
            $score = 0;

            foreach ($words as $word) {
                $score += $scores[$word];
            }

            $keywords[$phrase] = $score;
        }

        return $keywords;
    }

    /**
     * Split a phrase into multiple words and returns them
     * as an array.
     *
     * @param string $phrase
     *
     * @return array
     */
    private function splitPhraseIntoWords($phrase)
    {
        return array_filter(preg_split('/\W+/u', $phrase, -1, PREG_SPLIT_NO_EMPTY), function ($word) {
            return !is_numeric($word);
        });
    }

    /**
     * Returns the minimum number of letters each phrase/keyword must have.
     *
     * @return int
     */
    public function getMinLength()
    {
        return $this->min_length;
    }

    /**
     * Sets the minimum number of letters each phrase/keyword must have.
     *
     * @param int $min_length
     *
     * @return RakePlus
     */
    public function setMinLength($min_length)
    {
        if ((int)$min_length < 0) {
            throw new InvalidArgumentException('Minimum phrase length must be greater than or equal to 0.');
        }

        $this->min_length = (int)$min_length;
        return $this;
    }

    /**
     * Sets whether numeric-only phrases/keywords should be filtered
     * out or not.
     *
     * @param $filter_numerics
     *
     * @return RakePlus
     */
    public function setFilterNumerics($filter_numerics = true)
    {
        $this->filter_numerics = $filter_numerics;
        return $this;
    }

    /**
     * Returns whether numeric-only phrases/keywords will be filtered
     * out or not.
     *
     * @return bool
     */
    public function getFilterNumerics()
    {
        return $this->filter_numerics;
    }
}


text:
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)

using SharpDX.Direct3D9;

namespace Framefield.Core
{
    public class ContextSettings
    {
        public DisplayMode DisplayMode { get; set; }
        public int Sampling { get; set; }
        public double AspectRatio { get; set; }
        public bool FullScreen { get; set; }
        public bool Looped { get; set; }
        public bool VSyncEnabled { get; set; }
        public bool PreCacheEnabled { get; set; }

        public ContextSettings()
        {
            DisplayMode = new DisplayMode() { Width = 0, Height = 0, RefreshRate = 60, Format = Format.A8R8G8B8 };
            Sampling = 2;
            AspectRatio = 0;
            FullScreen = true;
            Looped = false;
            VSyncEnabled = true;
            PreCacheEnabled = true;
        }

        public void Validate()
        {
            if (DisplayMode.Width < 1 || DisplayMode.Height < 1)
            {
                DisplayMode = new DisplayMode() { Width = 1920, Height = 1080, RefreshRate = 60, Format = Format.A8R8G8B8 };
            }
            if (AspectRatio < 0.1)
            {
                AspectRatio = DisplayMode.AspectRatio;
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 67(4): 818 (1975)

#### Original name
Marasmius pallidocephalus Gilliam

### Remarks
null


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

<TITLE>
Uses of Interface gov.nih.nci.cabig.caaers.domain.Retireable
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
gov.nih.nci.cabig.caaers.domain.Retireable

Packages that use Retireable

gov.nih.nci.cabig.caaers

gov.nih.nci.cabig.caaers.domain

gov.nih.nci.cabig.caaers.web.study

Uses of Retireable in gov.nih.nci.cabig.caaers

Classes in gov.nih.nci.cabig.caaers with type parameters of type Retireable

 class
CollectionUtil<T extends Retireable>

Methods in gov.nih.nci.cabig.caaers with type parameters of type Retireable

static

<T extends Retireable>

java.util.List<T>

CollectionUtil.getActiveObjects(java.util.List<T> objects)

Uses of Retireable in gov.nih.nci.cabig.caaers.domain

Classes in gov.nih.nci.cabig.caaers.domain that implement Retireable

 class
AbstractMutableRetireableDomainObject

          The domain objects that are retire-able (soft delete-able) should subclass this class.

 class
AbstractStudyDisease<T extends DomainObject>

          The Class AbstractStudyDisease.

 class
AdverseEvent

          This class represents the Adverse Event domain object associated with the Adverse event report.

 class
AdverseEventReportingPeriod

          This class represents the Reporting Period associated to StudyParticipant Associations.

 class
CtepStudyDisease

          This class represents the CtepStudyDisease domain object associated with the Adverse event
 report.

 class
Epoch

          The Class Epoch.

 class
MeddraStudyDisease

          This class represents the MeddraStudyDisease domain object associated with the Adverse event
 report.

 class
OtherIntervention

          The Class OtherIntervention.

 class
SiteResearchStaff

          The Class SiteResearchStaff.

 class
StudyAgent

          This class represents the StudyAgent domain object associated with the Adverse event report.

 class
StudyCondition

          The Class StudyCondition.

 class
StudyCoordinatingCenter

          This class represents the StudyCoordinatingCenter domain object associated with the Adverse event
 report.

 class
StudyDevice

          Represents the Study Device Intervention.

 class
StudyFundingSponsor

          This class represents the StudyFundingSponsor domain object associated with the Adverse event
 report.

 class
StudyIntervention

          The parent class for all study interventions.

 class
StudyInvestigator

          This class represents the StudyInvestigator domain object associated with the Adverse event
 report.

 class
StudyOrganization

          This class encapsulates all types of organizations associated with a Study.

 class
StudyPersonnel

          This class represents the StudyPersonnel domain object associated with the Adverse event report.

 class
StudySite

          This class represents the StudySite domain object associated with the Adverse event report.

 class
TreatmentAssignment

          This class represents the TreatmentAssignment domain object associated with the Adverse event
 report.

Methods in gov.nih.nci.cabig.caaers.domain with parameters of type Retireable

static void
AbstractMutableRetireableDomainObject.retire(Retireable... retireables)

          This utility method could be used to mark the retired flag of a collection of Retireable objects.

Method parameters in gov.nih.nci.cabig.caaers.domain with type arguments of type Retireable

static void
AbstractMutableRetireableDomainObject.retire(java.util.Collection<? extends Retireable> retireables)

          This utility method could be used to mark the retired flag of a collection of Retireable objects.

Uses of Retireable in gov.nih.nci.cabig.caaers.web.study

Method parameters in gov.nih.nci.cabig.caaers.web.study with type arguments of type Retireable

 void
StudyCommand.delete(java.util.List<? extends Retireable> source,
       int index)

          This base method will delete or mark retire a retire-able object.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
use std::thread;
use std::time::*;

use engine_rocks::Compat;
use engine_traits::Peekable;
use kvproto::raft_serverpb::RaftLocalState;
use test_raftstore::*;
use tikv_util::config::ReadableDuration;

#[test]
fn test_one_node_leader_missing() {
    let mut cluster = new_server_cluster(0, 1);

    // 50ms election timeout.
    cluster.cfg.raft_store.raft_base_tick_interval = ReadableDuration::millis(10);
    cluster.cfg.raft_store.raft_election_timeout_ticks = 5;
    let base_tick_interval = cluster.cfg.raft_store.raft_base_tick_interval.0;
    let election_timeout = base_tick_interval * 5;
    cluster.cfg.raft_store.raft_store_max_leader_lease = ReadableDuration(election_timeout);
    // Use large peer check interval, abnormal and max leader missing duration to make a valid config,
    // that is election timeout x 2 < peer stale state check < abnormal < max leader missing duration.
    cluster.cfg.raft_store.peer_stale_state_check_interval = ReadableDuration(election_timeout * 3);
    cluster.cfg.raft_store.abnormal_leader_missing_duration =
        ReadableDuration(election_timeout * 4);
    cluster.cfg.raft_store.max_leader_missing_duration = ReadableDuration(election_timeout * 7);

    // Panic if the cluster does not has a valid stale state.
    let check_stale_state = "peer_check_stale_state";
    fail::cfg(check_stale_state, "panic").unwrap();

    cluster.start().unwrap();

    // Check stale state 3 times,
    thread::sleep(cluster.cfg.raft_store.peer_stale_state_check_interval.0 * 3);
    fail::remove(check_stale_state);
}

#[test]
fn test_node_update_localreader_after_removed() {
    let mut cluster = new_node_cluster(0, 6);
    let pd_client = cluster.pd_client.clone();
    // Disable default max peer number check.
    pd_client.disable_default_operator();
    let r1 = cluster.run_conf_change();

    // Add 4 peers.
    for i in 2..6 {
        pd_client.must_add_peer(r1, new_peer(i, i));
    }

    // Make sure peer 1 leads the region.
    cluster.must_transfer_leader(r1, new_peer(1, 1));
    let (key, value) = (b"k1", b"v1");
    cluster.must_put(key, value);
    assert_eq!(cluster.get(key), Some(value.to_vec()));

    // Make sure peer 2 is initialized.
    let engine_2 = cluster.get_engine(2);
    must_get_equal(&engine_2, key, value);

    // Pause peer 2 apply worker if it executes AddNode.
    let add_node_fp = "apply_on_add_node_1_2";
    fail::cfg(add_node_fp, "pause").unwrap();

    // Add peer 6.
    pd_client.must_add_peer(r1, new_peer(6, 6));

    // Isolate peer 2 from rest of the cluster.
    cluster.add_send_filter(IsolationFilterFactory::new(2));

    // Remove peer 2, so it will receive a gc msssage
    // after max_leader_missing_duration timeout.
    pd_client.must_remove_peer(r1, new_peer(2, 2));
    thread::sleep(cluster.cfg.raft_store.max_leader_missing_duration.0 * 2);

    // Continue peer 2 apply worker, so that peer 2 tries to
    // update region to its read delegate.
    fail::remove(add_node_fp);

    // Make sure peer 2 is removed in node 2.
    cluster.must_region_not_exist(r1, 2);
}

#[test]
fn test_stale_learner_restart() {
    let mut cluster = new_node_cluster(0, 2);
    cluster.pd_client.disable_default_operator();
    cluster.cfg.raft_store.raft_log_gc_threshold = 10;
    let r = cluster.run_conf_change();
    cluster
        .pd_client
        .must_add_peer(r, new_learner_peer(2, 1003));
    cluster.must_put(b"k1", b"v1");
    must_get_equal(&cluster.get_engine(2), b"k1", b"v1");
    // Simulates slow apply.
    fail::cfg("on_handle_apply_1003", "return").unwrap();
    cluster.must_put(b"k2", b"v2");
    must_get_equal(&cluster.get_engine(1), b"k2", b"v2");
    let state_key = keys::raft_state_key(r);
    let mut state: RaftLocalState = cluster
        .get_raft_engine(1)
        .c()
        .get_msg(&state_key)
        .unwrap()
        .unwrap();
    let last_index = state.get_last_index();
    let timer = Instant::now();
    while timer.elapsed() < Duration::from_secs(5) {
        state = cluster
            .get_raft_engine(2)
            .c()
            .get_msg(&state_key)
            .unwrap()
            .unwrap();
        if last_index <= state.get_hard_state().get_commit() {
            break;
        }
        thread::sleep(Duration::from_millis(10));
    }
    if state.last_index != last_index {
        panic!("store 2 has not catched up logs after 5 secs.");
    }
    cluster.shutdown();
    must_get_none(&cluster.get_engine(2), b"k2");
    fail::remove("on_handle_apply_1003");
    cluster.run_node(2).unwrap();
    must_get_equal(&cluster.get_engine(2), b"k2", b"v2");
}


text:
package org.apache.flink.api.java.operators.translation;

import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.operators.GenericDataSinkBase;
import org.apache.flink.api.common.operators.GenericDataSourceBase;
import org.apache.flink.api.common.operators.base.GroupReduceOperatorBase;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.aggregation.Aggregations;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.types.StringValue;

import org.junit.Test;

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

/** Tests for translation of aggregations. */
public class AggregateTranslationTest {

    @Test
    public void translateAggregate() {
        try {
            final int parallelism = 8;
            ExecutionEnvironment env = ExecutionEnvironment.createLocalEnvironment(parallelism);

            @SuppressWarnings("unchecked")
            DataSet<Tuple3<Double, StringValue, Long>> initialData =
                    env.fromElements(
                            new Tuple3<Double, StringValue, Long>(
                                    3.141592, new StringValue("foobar"), Long.valueOf(77)));

            initialData
                    .groupBy(0)
                    .aggregate(Aggregations.MIN, 1)
                    .and(Aggregations.SUM, 2)
                    .output(new DiscardingOutputFormat<Tuple3<Double, StringValue, Long>>());

            Plan p = env.createProgramPlan();

            GenericDataSinkBase<?> sink = p.getDataSinks().iterator().next();

            GroupReduceOperatorBase<?, ?, ?> reducer =
                    (GroupReduceOperatorBase<?, ?, ?>) sink.getInput();

            // check keys
            assertEquals(1, reducer.getKeyColumns(0).length);
            assertEquals(0, reducer.getKeyColumns(0)[0]);

            assertEquals(-1, reducer.getParallelism());
            assertTrue(reducer.isCombinable());

            assertTrue(reducer.getInput() instanceof GenericDataSourceBase<?, ?>);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            fail("Test caused an error: " + e.getMessage());
        }
    }
}


text:
FROM python:2.7
RUN apt-get update
RUN apt-get -y install python-dev
RUN pip install --no-cache-dir aerospike>=1.0.56 tornado
ADD . /code
WORKDIR /code
EXPOSE 8888
ENTRYPOINT ["python","/code/geoproxy"]


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "customer_interest_master".
 *
 * @property integer $id
 * @property integer $interest_id
 * @property integer $customer_id
 *
 * @property CustomerMaster $customer
 * @property InterestMaster $interest
 */
class CustomerInterestMaster extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'customer_interest_master';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['interest_id', 'customer_id'], 'required'],
            [['interest_id', 'customer_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'interest_id' => 'Interest ID',
            'customer_id' => 'Customer ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCustomer() {
        return $this->hasOne(CustomerMaster::className(), ['id' => 'customer_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getInterest() {
        return $this->hasOne(InterestMaster::className(), ['id' => 'interest_id']);
    }

}


text:
{% extends 'core/base.html' %}

{% block meta %}
<title>Chowist | Login</title>
{% endblock %}

{% block content %}

Login

        <form class="form-horizontal" action="" method="post">
          {% csrf_token %}
          {% include 'core/form_template.html' %}
          <button type="submit" class="btn btn-primary">Login</button>
        </form>

{% endblock %}


text:
"""
Generate requirements.txt from pydeps output...

Usage::

    pydeps <packagename> --max-bacon=0 \
           --show-raw-deps --nodot \
           --noshow | python pydeps2requirements.py

"""
import json
import sys
from collections import defaultdict

WIDTH = 80

# packages that are difficult to eliminate but shouldn't ever be part
# of a package's requirements.
skiplist = {
    '_markerlib', 'pkg_resources'
}

def dep2req(name, imported_by):
    """Convert dependency to requirement.
    """
    lst = [item for item in sorted(imported_by) if not item.startswith(name)]
    res = '%-15s # from: ' % name
    imps = ', '.join(lst)
    if len(imps) < WIDTH - 24:
        return res + imps
    return res + imps[:WIDTH - 24 - 3] + '...'

def pydeps2reqs(deps):
    """Convert a deps instance into requirements.
    """
    reqs = defaultdict(set)
    for k, v in deps.items():
        # not a built-in
        p = v['path']
        if p and not p.startswith(sys.real_prefix):
            if p.startswith(sys.prefix) and 'site-packages' in p:
                if not p.endswith('.pyd'):
                    if '/win32/' in p.replace('\\', '/'):
                        reqs['win32'] |= set(v['imported_by'])
                    else:
                        name = k.split('.', 1)[0]
                        if name not in skiplist:
                            reqs[name] |= set(v['imported_by'])

    if '_dummy' in reqs:
        del reqs['_dummy']
    return '\n'.join(dep2req(name, reqs[name]) for name in sorted(reqs))

def main():
    """Cli entrypoint.
    """
    if len(sys.argv) == 2:
        fname = sys.argv[1]
        data = json.load(open(fname, 'rb'))
    else:
        data = json.loads(sys.stdin.read())
    print pydeps2reqs(data)

if __name__ == "__main__":
    main()