text:
#ifndef SRS_PROTOCOL_KBPS_HPP
#define SRS_PROTOCOL_KBPS_HPP

/*
#include <srs_protocol_kbps.hpp>
*/

#include <srs_core.hpp>

#include <srs_protocol_io.hpp>

/**
* a kbps sample, for example, 1minute kbps,
* 10minute kbps sample.
*/
class SrsKbpsSample
{
public:
    int64_t bytes;
    int64_t time;
    int kbps;
public:
    SrsKbpsSample();
};

/**
* a slice of kbps statistic, for input or output.
* a slice contains a set of sessions, which has a base offset of bytes,
* where a slice is:
*       starttime(oldest session startup time)
*               bytes(total bytes of previous sessions)
*               io_bytes_base(bytes offset of current session)
*                       last_bytes(bytes of current session)
* so, the total send bytes now is:
*       send_bytes = bytes + last_bytes - io_bytes_base
* so, the bytes sent duration current session is:
*       send_bytes = last_bytes - io_bytes_base
* @remark use set_io to start new session.
* @remakr the slice is a data collection object driven by SrsKbps.
*/
class SrsKbpsSlice
{
private:
    union slice_io {
        ISrsProtocolStatistic* in;
        ISrsProtocolStatistic* out;
    };
public:
    // the slice io used for SrsKbps to invoke,
    // the SrsKbpsSlice itself never use it.
    slice_io io;
    // session startup bytes
    // @remark, use total_bytes() to get the total bytes of slice.
    int64_t bytes;
    // slice starttime, the first time to record bytes.
    int64_t starttime;
    // session startup bytes number for io when set it,
    // the base offset of bytes for io.
    int64_t io_bytes_base;
    // last updated bytes number,
    // cache for io maybe freed.
    int64_t last_bytes;
    // samples
    SrsKbpsSample sample_30s;
    SrsKbpsSample sample_1m;
    SrsKbpsSample sample_5m;
    SrsKbpsSample sample_60m;
public:
    // for the delta bytes.
    int64_t delta_bytes;
public:
    SrsKbpsSlice();
    virtual ~SrsKbpsSlice();
public:
    /**
    * get current total bytes.
    */
    virtual int64_t get_total_bytes();
    /**
    * resample all samples.
    */
    virtual void sample();
};

/**
* the interface which provices delta of bytes.
* for a delta, for example, a live stream connection, we can got the delta by:
*       IKbpsDelta* delta = ...;
*       delta->resample();
*       kbps->add_delta(delta);
*       delta->cleanup();
*/
class IKbpsDelta
{
public:
    IKbpsDelta();
    virtual ~IKbpsDelta();
public:
    /**
    * resample to generate the value of delta bytes.
    */
    virtual void resample() = 0;
    /**
    * get the send or recv bytes delta.
    */
    virtual int64_t get_send_bytes_delta() = 0;
    virtual int64_t get_recv_bytes_delta() = 0;
    /**
    * cleanup the value of delta bytes.
    */
    virtual void cleanup() = 0;
};

/**
 * to statistic the kbps of io.
 * itself can be a statistic source, for example, used for SRS bytes stat.
 * there are some usage scenarios:
 * 1. connections to calc kbps by sample():
 *       SrsKbps* kbps = ...;
 *       kbps->set_io(in, out)
 *       kbps->sample()
 *       kbps->get_xxx_kbps().
 *   the connections know how many bytes already send/recv.
 * 2. server to calc kbps by add_delta():
 *       SrsKbps* kbps = ...;
 *       kbps->set_io(NULL, NULL)
 *       for each connection in connections:
 *           IKbpsDelta* delta = connection; // where connection implements IKbpsDelta
 *           delta->resample()
 *           kbps->add_delta(delta)
 *           delta->cleanup()
 *       kbps->sample()
 *       kbps->get_xxx_kbps().
 * 3. kbps used as IKbpsDelta, to provides delta bytes:
 *      SrsKbps* kbps = ...;
 *      kbps->set_io(in, out);
 *      IKbpsDelta* delta = (IKbpsDelta*)kbps;
 *      delta->resample();
 *      printf("delta is %d/%d", delta->get_send_bytes_delta(), delta->get_recv_bytes_delta());
 *      delta->cleanup();
 *   the server never know how many bytes already send/recv, for the connection maybe closed.
 */
class SrsKbps : public virtual ISrsProtocolStatistic, public virtual IKbpsDelta
{
private:
    SrsKbpsSlice is;
    SrsKbpsSlice os;
public:
    SrsKbps();
    virtual ~SrsKbps();
public:
    /**
    * set io to start new session.
    * set the underlayer reader/writer,
    * if the io destroied, for instance, the forwarder reconnect,
    * user must set the io of SrsKbps to NULL to continue to use the kbps object.
    * @param in the input stream statistic. can be NULL.
    * @param out the output stream statistic. can be NULL.
    * @remark if in/out is NULL, use the cached data for kbps.
    */
    virtual void set_io(ISrsProtocolStatistic* in, ISrsProtocolStatistic* out);
public:
    /**
    * get total kbps, duration is from the startup of io.
    * @remark, use sample() to update data.
    */
    virtual int get_send_kbps();
    virtual int get_recv_kbps();
    // 30s
    virtual int get_send_kbps_30s();
    virtual int get_recv_kbps_30s();
    // 5m
    virtual int get_send_kbps_5m();
    virtual int get_recv_kbps_5m();
public:
    /**
    * get the total send/recv bytes, from the startup of the oldest io.
    * @remark, use sample() to update data.
    */
    virtual int64_t get_send_bytes();
    virtual int64_t get_recv_bytes();
public:
    /**
    * resample to get the delta.
    */
    virtual void resample();
    /**
    * get the delta of send/recv bytes.
    */
    virtual int64_t get_send_bytes_delta();
    virtual int64_t get_recv_bytes_delta();
    /**
    * cleanup the delta.
    */
    virtual void cleanup();
public:
    /**
    * add delta to kbps clac mechenism.
    * we donot know the total bytes, but know the delta, for instance,
    * for rtmp server to calc total bytes and kbps.
    * @remark user must invoke sample() to calc result after invoke this method.
    * @param delta, assert should never be NULL.
    */
    virtual void add_delta(IKbpsDelta* delta);
    /**
    * resample all samples, ignore if in/out is NULL.
    * used for user to calc the kbps, to sample new kbps value.
    * @remark if user, for instance, the rtmp server to calc the total bytes,
    *       use the add_delta() is better solutions.
    */
    virtual void sample();
};

#endif


text:
export function exists(arr: any[], ite: Function): boolean {
    let flag: boolean = false
    for (let item of arr) {
        if (!!ite(item)) {
            flag = true
            break
        }
    }
    return flag
}

export function timeout(promise: Promise<any>, time: number = 0): Promise<any> {
    return new Promise((res, rej) => {
        promise.then(res)
        setTimeout(() => {
            rej(new Error(`timed out after ${time} msec`))
        }, time)
    })
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Asymptotic Localization, Moser-Calogero Systems and Super Symmetric Yang-Mills Theory</AwardTitle>
    <AwardEffectiveDate>05/01/2001</AwardEffectiveDate>
    <AwardExpirationDate>08/31/2002</AwardExpirationDate>
    <AwardAmount>23448</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      03040200
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Mathematical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Christopher W. Stark</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>09/28/2001</MinAmdLetterDate>
    <MaxAmdLetterDate>09/28/2001</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0196550</AwardID>
    <Investigator>
      <FirstName>Kirill</FirstName>
      <LastName>Vaninsky</LastName>
      <EmailAddress>vaninsky@math.msu.edu</EmailAddress>
      <StartDate>08/24/1999</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Henry</FirstName>
      <LastName>McKean</LastName>
      <EmailAddress>mckean@cims.nyu.edu</EmailAddress>
      <StartDate>10/10/2000</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Michigan State University</Name>
      <CityName>East Lansing</CityName>
      <ZipCode>488242600</ZipCode>
      <PhoneNumber>5173555040</PhoneNumber>
      <StreetAddress>Office of Sponsored Programs</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Michigan</StateName>
      <StateCode>MI</StateCode>
    </Institution>
    <FoaInformation>
      0000099
      <Name>Other Applications NEC</Name>
    </FoaInformation>
  </Award>
</rootTag>


text:
package org.apache.fineract.accounting.closure.exception;

import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException;
import org.joda.time.LocalDate;

/**
 * A {@link RuntimeException} thrown when a GL Closure for a given date and
 * Office combination is already present
 */
public class GLClosureDuplicateException extends AbstractPlatformDomainRuleException {

    public GLClosureDuplicateException(final Long officeId, final LocalDate closureDate) {
        super("error.msg.glclosure.glcode.duplicate", "An accounting closure for branch with Id " + officeId
                + " already exists for the date " + closureDate, officeId, closureDate);
    }

}


text:
namespace __sanitizer {

class LibIgnore {
 public:
  explicit LibIgnore(LinkerInitialized);

  // Must be called during initialization.
  void AddIgnoredLibrary(const char *name_templ);
  void IgnoreNoninstrumentedModules(bool enable) {
    track_instrumented_libs_ = enable;
  }

  // Must be called after a new dynamic library is loaded.
  void OnLibraryLoaded(const char *name);

  // Must be called after a dynamic library is unloaded.
  void OnLibraryUnloaded();

  // Checks whether the provided PC belongs to one of the ignored libraries or
  // the PC should be ignored because it belongs to an non-instrumented module
  // (when ignore_noninstrumented_modules=1). Also returns true via
  // "pc_in_ignored_lib" if the PC is in an ignored library, false otherwise.
  bool IsIgnored(uptr pc, bool *pc_in_ignored_lib) const;

  // Checks whether the provided PC belongs to an instrumented module.
  bool IsPcInstrumented(uptr pc) const;

 private:
  struct Lib {
    char *templ;
    char *name;
    char *real_name;  // target of symlink
    bool loaded;
  };

  struct LibCodeRange {
    uptr begin;
    uptr end;
  };

  inline bool IsInRange(uptr pc, const LibCodeRange &range) const {
    return (pc >= range.begin && pc < range.end);
  }

  static const uptr kMaxIgnoredRanges = 128;
  static const uptr kMaxInstrumentedRanges = 1024;
  static const uptr kMaxLibs = 1024;

  // Hot part:
  atomic_uintptr_t ignored_ranges_count_;
  LibCodeRange ignored_code_ranges_[kMaxIgnoredRanges];

  atomic_uintptr_t instrumented_ranges_count_;
  LibCodeRange instrumented_code_ranges_[kMaxInstrumentedRanges];

  // Cold part:
  BlockingMutex mutex_;
  uptr count_;
  Lib libs_[kMaxLibs];
  bool track_instrumented_libs_;

  // Disallow copying of LibIgnore objects.
  LibIgnore(const LibIgnore&);  // not implemented
  void operator = (const LibIgnore&);  // not implemented
};

inline bool LibIgnore::IsIgnored(uptr pc, bool *pc_in_ignored_lib) const {
  const uptr n = atomic_load(&ignored_ranges_count_, memory_order_acquire);
  for (uptr i = 0; i < n; i++) {
    if (IsInRange(pc, ignored_code_ranges_[i])) {
      *pc_in_ignored_lib = true;
      return true;
    }
  }
  *pc_in_ignored_lib = false;
  if (track_instrumented_libs_ && !IsPcInstrumented(pc))
    return true;
  return false;
}

inline bool LibIgnore::IsPcInstrumented(uptr pc) const {
  const uptr n = atomic_load(&instrumented_ranges_count_, memory_order_acquire);
  for (uptr i = 0; i < n; i++) {
    if (IsInRange(pc, instrumented_code_ranges_[i]))
      return true;
  }
  return false;
}

}  // namespace __sanitizer

#endif  // SANITIZER_LIBIGNORE_H


text:
using namespace llvm;

void GIMatchDagPredicate::print(raw_ostream &OS) const {
  OS << "<<";
  printDescription(OS);
  OS << ">>:$" << Name;
}

void GIMatchDagPredicate::printDescription(raw_ostream &OS) const { OS << ""; }

GIMatchDagOpcodePredicate::GIMatchDagOpcodePredicate(
    GIMatchDagContext &Ctx, StringRef Name, const CodeGenInstruction &Instr)
    : GIMatchDagPredicate(GIMatchDagPredicateKind_Opcode, Name,
                          Ctx.makeMIPredicateOperandList()),
      Instr(Instr) {}

void GIMatchDagOpcodePredicate::printDescription(raw_ostream &OS) const {
  OS << "$mi.getOpcode() == " << Instr.TheDef->getName();
}

GIMatchDagOneOfOpcodesPredicate::GIMatchDagOneOfOpcodesPredicate(
    GIMatchDagContext &Ctx, StringRef Name)
    : GIMatchDagPredicate(GIMatchDagPredicateKind_OneOfOpcodes, Name,
                          Ctx.makeMIPredicateOperandList()) {}

void GIMatchDagOneOfOpcodesPredicate::printDescription(raw_ostream &OS) const {
  OS << "$mi.getOpcode() == oneof(";
  StringRef Separator = "";
  for (const CodeGenInstruction *Instr : Instrs) {
    OS << Separator << Instr->TheDef->getName();
    Separator = ",";
  }
  OS << ")";
}

GIMatchDagSameMOPredicate::GIMatchDagSameMOPredicate(GIMatchDagContext &Ctx,
                                                     StringRef Name)
    : GIMatchDagPredicate(GIMatchDagPredicateKind_SameMO, Name,
                          Ctx.makeTwoMOPredicateOperandList()) {}

void GIMatchDagSameMOPredicate::printDescription(raw_ostream &OS) const {
  OS << "$mi0 == $mi1";
}

raw_ostream &llvm::operator<<(raw_ostream &OS, const GIMatchDagPredicate &N) {
  N.print(OS);
  return OS;
}

raw_ostream &llvm::operator<<(raw_ostream &OS,
                              const GIMatchDagOpcodePredicate &N) {
  N.print(OS);
  return OS;
}


text:
'use strict';

/**
* Module dependencies.
*/
var passport = require('passport');

module.exports = function(app) {
// User Routes
var users = require('../../app/controllers/users');

// User Routes
app.get('/signin', users.signin);
app.get('/signup', users.signup);
app.get('/signout', users.signout);
app.get('/users/me', users.me);

// Setting up the users api
app.post('/users', users.create);

// Setting the local strategy route
app.post('/users/session', passport.authenticate('local', {
    failureRedirect: '/signin',
    failureFlash: true
}), users.session);

// Setting the facebook oauth routes
app.get('/auth/facebook', passport.authenticate('facebook', {
    scope: ['email', 'user_about_me'],
    failureRedirect: '/signin'
}), users.signin);

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    failureRedirect: '/signin'
}), users.authCallback);

// Setting the twitter oauth routes
app.get('/auth/twitter', passport.authenticate('twitter', {
    failureRedirect: '/signin'
}), users.signin);

app.get('/auth/twitter/callback', passport.authenticate('twitter', {
    failureRedirect: '/signin'
}), users.authCallback);

// Setting the google oauth routes
app.get('/auth/google', passport.authenticate('google', {
    failureRedirect: '/signin',
    scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email'
    ]
}), users.signin);

app.get('/auth/google/callback', passport.authenticate('google', {
    failureRedirect: '/signin'
}), users.authCallback);

// Finish with setting up the userId param
app.param('userId', users.user);
};


text:
MTQ_QML_REGISTER_PLUGIN(PaintField)

//Constructor
PaintField::PaintField(QQuickItem *)
{
	setHeight(600);
	setWidth(600);
	setStrokeHue(0);
	setBackgroundBrightness(255);
}

void PaintField::paint(QPainter *painter)
{
	painter->setRenderHint(QPainter::Antialiasing);
	QRect rect(4, 4, width() - 8, height() - 8);
	painter->fillRect(rect, m_bgColor);

	for (int strokeI = 0; strokeI < m_strokes.size(); strokeI++)
	{
		painter->setPen(QPen(QBrush(m_strokeColors.at(strokeI)),4));
		if (m_strokes.at(strokeI).size() == 1)
			painter->drawPoint(m_strokes.at(strokeI).at(0));
		else if (m_strokes.at(strokeI).size() > 1) {
			for (int i = 0; i < m_strokes.at(strokeI).size() - 1; i++) {
				painter->drawLine(m_strokes.at(strokeI).at(i),
								  m_strokes.at(strokeI).at(i+1));
			}
		}
	}
}

qreal PaintField::strokeHue() const
{
	return m_strokeHue;
}

void PaintField::setStrokeHue(const qreal hue)
{
	m_strokeHue = hue;
}

int PaintField::backgroundBrightness() const
{
	return m_backgroundBrightness;
}

void PaintField::setBackgroundBrightness(const int brightness)
{
	m_backgroundBrightness = brightness;
	m_bgColor = QColor().fromHsv(1, 0, brightness);
	update();
}

void PaintField::processContactDown(mtq::ContactEvent *event)
{
	m_strokes.push_back(QVector<QPointF>());
	m_strokeColors.push_back(QColor().fromHsvF(m_strokeHue, 1, 1));
	QPointF center = event->mappedCenter();
	m_strokes.last().push_back(center);
	update();
}

void PaintField::processContactMove(mtq::ContactEvent *event)
{
	QPointF center = event->mappedCenter();
	m_strokes.last().push_back(center);
	update();
}

void PaintField::processContactUp(mtq::ContactEvent *event)
{
	update();
}


text:
title: Controllers in ember-flexberry applications
sidebar: flexberry-ember-2_sidebar
keywords: Flexberry Ember
toc: true
permalink: en/ef2_controller.html
lang: en
autotranslated: true
hash: 8f3aa56bf889a99daa88f766c0bdf4c9f0361f96a147110a38fa1dd11d7c6ab2
summary: Presents basic information about the structure of controllers in ember-flexberry applications.
---

## Description

Controllers in Ember applications are inherit from base class [Ember.Controller](http://emberjs.com/api/classes/Ember.Controller.html).

Technology implemented in the base controller:

* [list of forms](ef2_forms.html),
* [forms for editing and creation](ef2_edit-form.html).

Typical for the technology controller location, see [this article](ef2_router.html).

## Controllers for list forms
Controller for [list form](ef2_forms.html) is as follows. It derives from a certain technology controller `list-form`.

```javascript
import ListFormController from 'ember-flexberry/controllers/list-form';

var EmployeesController = ListFormController; // Can be defined in a separate variable.
export default EmployeesController;
```

## Controllers for forms to edit and create
Controller [edit form](ef2_edit-form.html) is as follows. It derives from a certain technology controller `edit-form`.

```javascript
import EditFormController from 'ember-flexberry/controllers/edit-form';

export default EditFormController; // You can not define in a separate variable.
```

Separate base controller for [form](ef2_edit-form.html) is not implemented. In General, the controller, the controller overrides the edit form:

```javascript
import EmployeeController from '../employee';

var EmployeeNewController = EmployeeController;
export default EmployeeNewController;
```

## App controller
The controller application is located in file `application.js` in the folder `components`.

In this controller it is possible to define the site menu (see example below), configure the processing common to all forms of settings (e.g., in order to [hide the menu bar on forms for the parameter](ef2_show-ember-form-in-frame.html)).

```javascript
import Ember from 'ember';

export default Ember.Controller.extend({
  sitemap: {
    nodes: [{
      link: 'index',
      title: 'Home',
      children: null
    }, {
      link: null,
      title: 'Objects',
      children: [{
        link: 'employees',
        title: 'Employees',
        children: null
      }, {
        link: 'orders',
        title: 'Orders',
        children: null
      }]
    }]
  }
});
```


text:
@interface QBArrowRefreshControl : QBRefreshControl

@property (nonatomic, strong) NSDate *lastUpdate;

@end


text:
module Data.Bechdel.Util where

-- Replace newlines with spaces.
unnewline :: String -> String
unnewline = map nlToSpace
    where nlToSpace :: Char -> Char
          nlToSpace '\n' = ' '
          nlToSpace c = c


text:
<?php

namespace Magento\Catalog\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\Data\ProductLinkInterface;
use Magento\Catalog\Api\ProductLinkRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Eav\Api\AttributeSetRepositoryInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Phrase;
use Magento\Framework\UrlInterface;
use Magento\Ui\Component\DynamicRows;
use Magento\Ui\Component\Form\Element\DataType\Number;
use Magento\Ui\Component\Form\Element\DataType\Text;
use Magento\Ui\Component\Form\Element\Input;
use Magento\Ui\Component\Form\Field;
use Magento\Ui\Component\Form\Fieldset;
use Magento\Ui\Component\Modal;
use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Catalog\Model\Product\Attribute\Source\Status;

/**
 * Class Related
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Related extends AbstractModifier
{
    const DATA_SCOPE = '';
    const DATA_SCOPE_RELATED = 'related';
    const DATA_SCOPE_UPSELL = 'upsell';
    const DATA_SCOPE_CROSSSELL = 'crosssell';
    const GROUP_RELATED = 'related';

    /**
     * @var string
     */
    private static $previousGroup = 'search-engine-optimization';

    /**
     * @var int
     */
    private static $sortOrder = 90;

    /**
     * @var LocatorInterface
     */
    protected $locator;

    /**
     * @var UrlInterface
     */
    protected $urlBuilder;

    /**
     * @var ProductLinkRepositoryInterface
     */
    protected $productLinkRepository;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var ImageHelper
     */
    protected $imageHelper;

    /**
     * @var Status
     */
    protected $status;

    /**
     * @var AttributeSetRepositoryInterface
     */
    protected $attributeSetRepository;

    /**
     * @var string
     */
    protected $scopeName;

    /**
     * @var string
     */
    protected $scopePrefix;

    /**
     * @var \Magento\Catalog\Ui\Component\Listing\Columns\Price
     */
    private $priceModifier;

    /**
     * @param LocatorInterface $locator
     * @param UrlInterface $urlBuilder
     * @param ProductLinkRepositoryInterface $productLinkRepository
     * @param ProductRepositoryInterface $productRepository
     * @param ImageHelper $imageHelper
     * @param Status $status
     * @param AttributeSetRepositoryInterface $attributeSetRepository
     * @param string $scopeName
     * @param string $scopePrefix
     */
    public function __construct(
        LocatorInterface $locator,
        UrlInterface $urlBuilder,
        ProductLinkRepositoryInterface $productLinkRepository,
        ProductRepositoryInterface $productRepository,
        ImageHelper $imageHelper,
        Status $status,
        AttributeSetRepositoryInterface $attributeSetRepository,
        $scopeName = '',
        $scopePrefix = ''
    ) {
        $this->locator = $locator;
        $this->urlBuilder = $urlBuilder;
        $this->productLinkRepository = $productLinkRepository;
        $this->productRepository = $productRepository;
        $this->imageHelper = $imageHelper;
        $this->status = $status;
        $this->attributeSetRepository = $attributeSetRepository;
        $this->scopeName = $scopeName;
        $this->scopePrefix = $scopePrefix;
    }

    /**
     * {@inheritdoc}
     */
    public function modifyMeta(array $meta)
    {
        $meta = array_replace_recursive(
            $meta,
            [
                static::GROUP_RELATED => [
                    'children' => [
                        $this->scopePrefix . static::DATA_SCOPE_RELATED => $this->getRelatedFieldset(),
                        $this->scopePrefix . static::DATA_SCOPE_UPSELL => $this->getUpSellFieldset(),
                        $this->scopePrefix . static::DATA_SCOPE_CROSSSELL => $this->getCrossSellFieldset(),
                    ],
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'label' => __('Related Products, Up-Sells, and Cross-Sells'),
                                'collapsible' => true,
                                'componentType' => Fieldset::NAME,
                                'dataScope' => static::DATA_SCOPE,
                                'sortOrder' =>
                                    $this->getNextGroupSortOrder(
                                        $meta,
                                        self::$previousGroup,
                                        self::$sortOrder
                                    ),
                            ],
                        ],

                    ],
                ],
            ]
        );

        return $meta;
    }

    /**
     * {@inheritdoc}
     */
    public function modifyData(array $data)
    {
        /** @var \Magento\Catalog\Model\Product $product */
        $product = $this->locator->getProduct();
        $productId = $product->getId();

        if (!$productId) {
            return $data;
        }

        $priceModifier = $this->getPriceModifier();
        /**
         * Set field name for modifier
         */
        $priceModifier->setData('name', 'price');

        foreach ($this->getDataScopes() as $dataScope) {
            $data[$productId]['links'][$dataScope] = [];
            foreach ($this->productLinkRepository->getList($product) as $linkItem) {
                if ($linkItem->getLinkType() !== $dataScope) {
                    continue;
                }

                /** @var \Magento\Catalog\Model\Product $linkedProduct */
                $linkedProduct = $this->productRepository->get(
                    $linkItem->getLinkedProductSku(),
                    false,
                    $this->locator->getStore()->getId()
                );
                $data[$productId]['links'][$dataScope][] = $this->fillData($linkedProduct, $linkItem);
            }
            if (!empty($data[$productId]['links'][$dataScope])) {
                $dataMap = $priceModifier->prepareDataSource([
                    'data' => [
                        'items' => $data[$productId]['links'][$dataScope]
                    ]
                ]);
                $data[$productId]['links'][$dataScope] = $dataMap['data']['items'];
            }
        }

        $data[$productId][self::DATA_SOURCE_DEFAULT]['current_product_id'] = $productId;
        $data[$productId][self::DATA_SOURCE_DEFAULT]['current_store_id'] = $this->locator->getStore()->getId();

        return $data;
    }

    /**
     * Get price modifier
     *
     * @return \Magento\Catalog\Ui\Component\Listing\Columns\Price
     * @deprecated
     */
    private function getPriceModifier()
    {
        if (!$this->priceModifier) {
            $this->priceModifier = ObjectManager::getInstance()->get(
                \Magento\Catalog\Ui\Component\Listing\Columns\Price::class
            );
        }
        return $this->priceModifier;
    }

    /**
     * Prepare data column
     *
     * @param ProductInterface $linkedProduct
     * @param ProductLinkInterface $linkItem
     * @return array
     */
    protected function fillData(ProductInterface $linkedProduct, ProductLinkInterface $linkItem)
    {
        return [
            'id' => $linkedProduct->getId(),
            'thumbnail' => $this->imageHelper->init($linkedProduct, 'product_listing_thumbnail')->getUrl(),
            'name' => $linkedProduct->getName(),
            'status' => $this->status->getOptionText($linkedProduct->getStatus()),
            'attribute_set' => $this->attributeSetRepository
                ->get($linkedProduct->getAttributeSetId())
                ->getAttributeSetName(),
            'sku' => $linkItem->getLinkedProductSku(),
            'price' => $linkedProduct->getPrice(),
            'position' => $linkItem->getPosition(),
        ];
    }

    /**
     * Retrieve all data scopes
     *
     * @return array
     */
    protected function getDataScopes()
    {
        return [
            static::DATA_SCOPE_RELATED,
            static::DATA_SCOPE_CROSSSELL,
            static::DATA_SCOPE_UPSELL,
        ];
    }

    /**
     * Prepares config for the Related products fieldset
     *
     * @return array
     */
    protected function getRelatedFieldset()
    {
        $content = __(
            'Related products are shown to customers in addition to the item the customer is looking at.'
        );

        return [
            'children' => [
                'button_set' => $this->getButtonSet(
                    $content,
                    __('Add Related Products'),
                    $this->scopePrefix . static::DATA_SCOPE_RELATED
                ),
                'modal' => $this->getGenericModal(
                    __('Add Related Products'),
                    $this->scopePrefix . static::DATA_SCOPE_RELATED
                ),
                static::DATA_SCOPE_RELATED => $this->getGrid($this->scopePrefix . static::DATA_SCOPE_RELATED),
            ],
            'arguments' => [
                'data' => [
                    'config' => [
                        'additionalClasses' => 'admin__fieldset-section',
                        'label' => __('Related Products'),
                        'collapsible' => false,
                        'componentType' => Fieldset::NAME,
                        'dataScope' => '',
                        'sortOrder' => 10,
                    ],
                ],
            ]
        ];
    }

    /**
     * Prepares config for the Up-Sell products fieldset
     *
     * @return array
     */
    protected function getUpSellFieldset()
    {
        $content = __(
            'An up-sell item is offered to the customer as a pricier or higher-quality' .
            ' alternative to the product the customer is looking at.'
        );

        return [
            'children' => [
                'button_set' => $this->getButtonSet(
                    $content,
                    __('Add Up-Sell Products'),
                    $this->scopePrefix . static::DATA_SCOPE_UPSELL
                ),
                'modal' => $this->getGenericModal(
                    __('Add Up-Sell Products'),
                    $this->scopePrefix . static::DATA_SCOPE_UPSELL
                ),
                static::DATA_SCOPE_UPSELL => $this->getGrid($this->scopePrefix . static::DATA_SCOPE_UPSELL),
            ],
            'arguments' => [
                'data' => [
                    'config' => [
                        'additionalClasses' => 'admin__fieldset-section',
                        'label' => __('Up-Sell Products'),
                        'collapsible' => false,
                        'componentType' => Fieldset::NAME,
                        'dataScope' => '',
                        'sortOrder' => 20,
                    ],
                ],
            ]
        ];
    }

    /**
     * Prepares config for the Cross-Sell products fieldset
     *
     * @return array
     */
    protected function getCrossSellFieldset()
    {
        $content = __(
            'These "impulse-buy" products appear next to the shopping cart' .
            ' as cross-sells to the items already in the shopping cart.'
        );

        return [
            'children' => [
                'button_set' => $this->getButtonSet(
                    $content,
                    __('Add Cross-Sell Products'),
                    $this->scopePrefix . static::DATA_SCOPE_CROSSSELL
                ),
                'modal' => $this->getGenericModal(
                    __('Add Cross-Sell Products'),
                    $this->scopePrefix . static::DATA_SCOPE_CROSSSELL
                ),
                static::DATA_SCOPE_CROSSSELL => $this->getGrid($this->scopePrefix . static::DATA_SCOPE_CROSSSELL),
            ],
            'arguments' => [
                'data' => [
                    'config' => [
                        'additionalClasses' => 'admin__fieldset-section',
                        'label' => __('Cross-Sell Products'),
                        'collapsible' => false,
                        'componentType' => Fieldset::NAME,
                        'dataScope' => '',
                        'sortOrder' => 30,
                    ],
                ],
            ]
        ];
    }

    /**
     * Retrieve button set
     *
     * @param Phrase $content
     * @param Phrase $buttonTitle
     * @param string $scope
     * @return array
     */
    protected function getButtonSet(Phrase $content, Phrase $buttonTitle, $scope)
    {
        $modalTarget = $this->scopeName . '.' . static::GROUP_RELATED . '.' . $scope . '.modal';

        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'formElement' => 'container',
                        'componentType' => 'container',
                        'label' => false,
                        'content' => $content,
                        'template' => 'ui/form/components/complex',
                    ],
                ],
            ],
            'children' => [
                'button_' . $scope => [
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'formElement' => 'container',
                                'componentType' => 'container',
                                'component' => 'Magento_Ui/js/form/components/button',
                                'actions' => [
                                    [
                                        'targetName' => $modalTarget,
                                        'actionName' => 'toggleModal',
                                    ],
                                    [
                                        'targetName' => $modalTarget . '.' . $scope . '_product_listing',
                                        'actionName' => 'render',
                                    ]
                                ],
                                'title' => $buttonTitle,
                                'provider' => null,
                            ],
                        ],
                    ],

                ],
            ],
        ];
    }

    /**
     * Prepares config for modal slide-out panel
     *
     * @param Phrase $title
     * @param string $scope
     * @return array
     */
    protected function getGenericModal(Phrase $title, $scope)
    {
        $listingTarget = $scope . '_product_listing';

        $modal = [
            'arguments' => [
                'data' => [
                    'config' => [
                        'componentType' => Modal::NAME,
                        'dataScope' => '',
                        'options' => [
                            'title' => $title,
                            'buttons' => [
                                [
                                    'text' => __('Cancel'),
                                    'actions' => [
                                        'closeModal'
                                    ]
                                ],
                                [
                                    'text' => __('Add Selected Products'),
                                    'class' => 'action-primary',
                                    'actions' => [
                                        [
                                            'targetName' => 'index = ' . $listingTarget,
                                            'actionName' => 'save'
                                        ],
                                        'closeModal'
                                    ]
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'children' => [
                $listingTarget => [
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'autoRender' => false,
                                'componentType' => 'insertListing',
                                'dataScope' => $listingTarget,
                                'externalProvider' => $listingTarget . '.' . $listingTarget . '_data_source',
                                'selectionsProvider' => $listingTarget . '.' . $listingTarget . '.product_columns.ids',
                                'ns' => $listingTarget,
                                'render_url' => $this->urlBuilder->getUrl('mui/index/render'),
                                'realTimeLink' => true,
                                'dataLinks' => [
                                    'imports' => false,
                                    'exports' => true
                                ],
                                'behaviourType' => 'simple',
                                'externalFilterMode' => true,
                                'imports' => [
                                    'productId' => '${ $.provider }:data.product.current_product_id',
                                    'storeId' => '${ $.provider }:data.product.current_store_id',
                                ],
                                'exports' => [
                                    'productId' => '${ $.externalProvider }:params.current_product_id',
                                    'storeId' => '${ $.externalProvider }:params.current_store_id',
                                ]
                            ],
                        ],
                    ],
                ],
            ],
        ];

        return $modal;
    }

    /**
     * Retrieve grid
     *
     * @param string $scope
     * @return array
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function getGrid($scope)
    {
        $dataProvider = $scope . '_product_listing';

        return [
            'arguments' => [
                'data' => [
                    'config' => [
                        'additionalClasses' => 'admin__field-wide',
                        'componentType' => DynamicRows::NAME,
                        'label' => null,
                        'columnsHeader' => false,
                        'columnsHeaderAfterRender' => true,
                        'renderDefaultRecord' => false,
                        'template' => 'ui/dynamic-rows/templates/grid',
                        'component' => 'Magento_Ui/js/dynamic-rows/dynamic-rows-grid',
                        'addButton' => false,
                        'recordTemplate' => 'record',
                        'dataScope' => 'data.links',
                        'deleteButtonLabel' => __('Remove'),
                        'dataProvider' => $dataProvider,
                        'map' => [
                            'id' => 'entity_id',
                            'name' => 'name',
                            'status' => 'status_text',
                            'attribute_set' => 'attribute_set_text',
                            'sku' => 'sku',
                            'price' => 'price',
                            'thumbnail' => 'thumbnail_src',
                        ],
                        'links' => [
                            'insertData' => '${ $.provider }:${ $.dataProvider }'
                        ],
                        'sortOrder' => 2,
                    ],
                ],
            ],
            'children' => [
                'record' => [
                    'arguments' => [
                        'data' => [
                            'config' => [
                                'componentType' => 'container',
                                'isTemplate' => true,
                                'is_collection' => true,
                                'component' => 'Magento_Ui/js/dynamic-rows/record',
                                'dataScope' => '',
                            ],
                        ],
                    ],
                    'children' => $this->fillMeta(),
                ],
            ],
        ];
    }

    /**
     * Retrieve meta column
     *
     * @return array
     */
    protected function fillMeta()
    {
        return [
            'id' => $this->getTextColumn('id', false, __('ID'), 0),
            'thumbnail' => [
                'arguments' => [
                    'data' => [
                        'config' => [
                            'componentType' => Field::NAME,
                            'formElement' => Input::NAME,
                            'elementTmpl' => 'ui/dynamic-rows/cells/thumbnail',
                            'dataType' => Text::NAME,
                            'dataScope' => 'thumbnail',
                            'fit' => true,
                            'label' => __('Thumbnail'),
                            'sortOrder' => 10,
                        ],
                    ],
                ],
            ],
            'name' => $this->getTextColumn('name', false, __('Name'), 20),
            'status' => $this->getTextColumn('status', true, __('Status'), 30),
            'attribute_set' => $this->getTextColumn('attribute_set', false, __('Attribute Set'), 40),
            'sku' => $this->getTextColumn('sku', true, __('SKU'), 50),
            'price' => $this->getTextColumn('price', true, __('Price'), 60),
            'actionDelete' => [
                'arguments' => [
                    'data' => [
                        'config' => [
                            'additionalClasses' => 'data-grid-actions-cell',
                            'componentType' => 'actionDelete',
                            'dataType' => Text::NAME,
                            'label' => __('Actions'),
                            'sortOrder' => 70,
                            'fit' => true,
                        ],
                    ],
                ],
            ],
            'position' => [
                'arguments' => [
                    'data' => [
                        'config' => [
                            'dataType' => Number::NAME,
                            'formElement' => Input::NAME,
                            'componentType' => Field::NAME,
                            'dataScope' => 'position',
                            'sortOrder' => 80,
                            'visible' => false,
                        ],
                    ],
                ],
            ],
        ];
    }

    /**
     * Retrieve text column structure
     *
     * @param string $dataScope
     * @param bool $fit
     * @param Phrase $label
     * @param int $sortOrder
     * @return array
     */
    protected function getTextColumn($dataScope, $fit, Phrase $label, $sortOrder)
    {
        $column = [
            'arguments' => [
                'data' => [
                    'config' => [
                        'componentType' => Field::NAME,
                        'formElement' => Input::NAME,
                        'elementTmpl' => 'ui/dynamic-rows/cells/text',
                        'component' => 'Magento_Ui/js/form/element/text',
                        'dataType' => Text::NAME,
                        'dataScope' => $dataScope,
                        'fit' => $fit,
                        'label' => $label,
                        'sortOrder' => $sortOrder,
                    ],
                ],
            ],
        ];

        return $column;
    }
}


text:
frontend-bootstrap
==================

Bootstrap application to start a new Front-End project using Bower and GruntJS

## Set-up project

### Bower

- Install/upgrade Bower's last version:
	sudo npm install -g bower
	sudo npm update -g bower

- Check Bower version:
	bower -version

- Initialize Bower project
	bower init

### GruntJS

- Initialize NPM project
	npm init

- Install GruntJS dependency
	npm install grunt --save-dev

- Create GruntJS file
	Gruntfile.js

### Installing npm dependencies

- Install JSHint (to validate JS code)
	npm install grunt-contrib-jshint --save

- Install LessCss
	npm install grunt-contrib-less --save

- Install RequireJS
	npm install grunt-contrib-requirejs --save

- Install Connect Server
	npm install grunt-connect --save-dev

- Install Watch Plugin to compile CSS every time a LESS file changes
	npm install grunt-contrib-watch --save-dev

### Installing Bower dependencies

- Install RequireJS
	bower install requirejs --save

- Install JQuery
	bower install jquery --save

- Install UnderscoreJS
	bower install underscore --save


text:
require 'rails/generators/base'
require 'securerandom'

module Devise
  module Generators
    MissingORMError = Class.new(Thor::Error)

    class InstallGenerator < Rails::Generators::Base
      source_root File.expand_path("../../templates", __FILE__)

      desc "Creates a Devise initializer and copy locale files to your application."
      class_option :orm

      def copy_initializer
        unless options[:orm]
          raise MissingORMError, <<-ERROR.strip_heredoc
          An ORM must be set to install Devise in your application.

          Be sure to have an ORM like Active Record or Mongoid loaded in your
          app or configure your own at `config/application.rb`.

            config.generators do |g|
              g.orm :your_orm_gem
            end
          ERROR
        end

        template "devise.rb", "config/initializers/devise.rb"
      end

      def copy_locale
        copy_file "../../../config/locales/en.yml", "config/locales/devise.en.yml"
      end

      def show_readme
        readme "README" if behavior == :invoke
      end

      def rails_4?
        Rails::VERSION::MAJOR == 4
      end
    end
  end
end


text:
/*
 * PoC: API for Oskari 2.0
 *
 */
define([
    "lodash",
    "src/oskari/oskari",
    "src/oskari/base/module",
    "src/framework/oskariui/module"
], function(_,Oskari, platform) {
    Oskari.VERSION = "2.1.0"; // Overwrite

    var cs = Oskari.clazz;

    /* Simplified Application API for Oskari 2.0 */
    var App = Oskari.cls(undefined, function() {
        this.instances = {};
        this.startupSeq = [];
        this.config = Oskari.appConfig;
    }).methods({
        setConfiguration: function(c) {
            Oskari.setConfiguration(c);
            return this;
        },
        setStartupSequence: function(startup) {
            this.startupSeq = startup;
            return this;
        },
        success: function(s) {
            if (this.result)
                s(this.result);
            else
                this.successFunc = s;
            return this;
        },
        _startApplication: function(callback) {
            // start app
            var me = this,
                result = {},

                // start modules in the given startupSequence order
                startupSequence = me.startupSeq,
                startupSequenceLength = startupSequence.length,
                modules = [];

            var startModules = function(moduleArray, callback) {
                if (moduleArray.length === 0) {
                    if (callback) {
                        callback();
                    }
                    return me;
                }
                var moduleItem = moduleArray.shift(),
                    moduleName = moduleItem.bundlename,
                    instance = null,
                    instancename = moduleItem.bundleinstancename;

                require([moduleName], function(module) {

                    instance = module.start(instancename);
                    name = instance.getName();

                    // store handle for observability while testing and debugging
                    me.instances[name] = instance;

                    // recursively start all modules
                    startModules(moduleArray, callback);
                });
            };
            startModules(startupSequence, callback);
        },
        start: function() {
            var me = this;
            var app = Oskari.app;
            me._startApplication(function(result) {
                if (me.successFunc)
                    me.successFunc(me);
                else
                    me.result = result;

            });
            return this;
        },
        stopApplication: function() {
            // nop atm
            return this;
        },
        getModuleInstances: function() {
            return this.instances;
        }
    });

    /* Generic shortcuts */

    Oskari.Application = App;

    var defaultIdentifier = 0;
    var ConfigurableModule = Oskari.cls('Oskari.Module', function() {
        console.log("CREATED CONFIGURABLE MODULE as BASE for MODULES");
    }, {
        extend: function(props) {
            // Bundles are structured to modules, however the refactoring is done gradually.
            // TODO: Change Oskari.bundleCls to Oskari.moduleClass
            var moduleClass = Oskari.bundleCls(props.identifier);

            moduleClass.category(props);
            moduleClass.category({
                create: function() {
                    console.log("CREATING MODULE INSTANCE ", this.extension, this.identifier, this.locale, this.configuration);
                    var instance =
                        this.extension.create(this.identifier || '_' + (++defaultIdentifier), this.locale);

                    var configProps = this.configuration || {};

                    for (ip in configProps) {
                        if (configProps.hasOwnProperty(ip)) {
                            instance.conf[ip] = configProps[ip];
                        }
                    }

                    console.log("- INSTANCE", instance, "post conf");
                    return instance;
                }

            });

            console.log("DECLARED MODULE CLASS", moduleClass);
            return moduleClass;
        }

    });

    Oskari.Module = ConfigurableModule.create();

    /* Event, Request support Classes */

    /* Oskari.Event */
    /* example:
     *   var evtCls = Oskari.Event.extend({ name: 'MyEvent' });
     *   var evt = evtCls.create({ 'prop': 'value' });
     *   Oskari.getSandbox().notifyAll(evt);
     */
    var ExtendableEvent =
     Oskari.cls('Oskari.Event', function() {
        console.log("CREATED EXTENDABLE EVENT as BASE for EVENTS");
    }, {
	extend : function(props) {
	   return Oskari.cls(props.name ? 'Oskari.event._.'+props.name: undefined,function(instanceProps) {
	        for (ip in instanceProps) {
	       	    if (instanceProps.hasOwnProperty(ip)) {
        		this[ip] = instanceProps[ip];
	            }
        	}
	      },{
              getName : function() {
                return this.name;
              }
           },{
             protocol : ['Oskari.mapframework.event.Event']
           }).category(props);
	}
    });

    Oskari.Event = ExtendableEvent.create();

    /* Oskari.Request */
    /* example:
     *   var reqCls = Oskari.Request.extend({ name: 'MyRequest'});
     *   var req = reqcls.create( { 'prop': 'value' });
     *   Oskari.getSandbox().request("MainMapModule", req);
     *
     */
    var ExtendableRequest =
     Oskari.cls('Oskari.Request', function() {
        console.log("CREATED EXTENDABLE REQUEST as BASE for REQUESTS");
    }, {
	extend : function(props) {
          return Oskari.cls(props.name ? 'Oskari.request._.'+props.name: undefined,function(instanceProps) {
            for (ip in instanceProps) {
              if (instanceProps.hasOwnProperty(ip)) {
                 this[ip] = instanceProps[ip];
              }
            }
         },{
           getName : function() {
                return this.name;
           }
         },{
           protocol : ['Oskari.mapframework.request.Request']
         }).category(props);
       }
     });

    Oskari.Request = ExtendableRequest.create();

    /* Object Generic class */
    /* example:
     *    // instantiate
     *    var obj = Oskari.Object.create({ 'prop' : 'value' });
     *
     *    // extend
     *    var objCls = Oskari.Object.extend( {
     *        funk: function() { return "obj extended "+this.prop; }
     *   });
     *    // and instantiate
     *   var enhancedObj = objCls.create({ 'prop' : 'new value' });
     *   enhancedObj.funk();
     */
    Oskari.Object = Oskari.cls('Oskari.Object',function(instanceProps) {
        for (ip in instanceProps) {
            if (instanceProps.hasOwnProperty(ip)) {
                 this[ip] = instanceProps[ip];
            }
        }
    });

    return Oskari;

});


text:
namespace {

// Invokes RecreateLayer() on all the children of |to_clone|, adding the newly
// cloned children to |parent|.
//
// WARNING: It is assumed that |parent| is ultimately owned by a LayerTreeOwner.
void CloneChildren(ui::Layer* to_clone,
                   ui::Layer* parent,
                   wm::LayerDelegateFactory* factory) {
  typedef std::vector<ui::Layer*> Layers;
  // Make a copy of the children since RecreateLayer() mutates it.
  Layers children(to_clone->children());
  for (Layers::const_iterator i = children.begin(); i != children.end(); ++i) {
    ui::LayerOwner* owner = (*i)->owner();
    ui::Layer* old_layer = owner ? owner->RecreateLayer().release() : NULL;
    if (old_layer) {
      if (factory && owner->layer()->delegate())
        old_layer->set_delegate(
            factory->CreateDelegate(owner->layer()->delegate()));
      parent->Add(old_layer);
      // RecreateLayer() moves the existing children to the new layer. Create a
      // copy of those.
      CloneChildren(owner->layer(), old_layer, factory);
    }
  }
}

}  // namespace

namespace wm {

void ActivateWindow(aura::Window* window) {
  DCHECK(window);
  DCHECK(window->GetRootWindow());
  aura::client::GetActivationClient(window->GetRootWindow())->ActivateWindow(
      window);
}

void DeactivateWindow(aura::Window* window) {
  DCHECK(window);
  DCHECK(window->GetRootWindow());
  aura::client::GetActivationClient(window->GetRootWindow())->DeactivateWindow(
      window);
}

bool IsActiveWindow(aura::Window* window) {
  DCHECK(window);
  if (!window->GetRootWindow())
    return false;
  aura::client::ActivationClient* client =
      aura::client::GetActivationClient(window->GetRootWindow());
  return client && client->GetActiveWindow() == window;
}

bool CanActivateWindow(aura::Window* window) {
  DCHECK(window);
  if (!window->GetRootWindow())
    return false;
  aura::client::ActivationClient* client =
      aura::client::GetActivationClient(window->GetRootWindow());
  return client && client->CanActivateWindow(window);
}

aura::Window* GetActivatableWindow(aura::Window* window) {
  aura::client::ActivationClient* client =
      aura::client::GetActivationClient(window->GetRootWindow());
  return client ? client->GetActivatableWindow(window) : NULL;
}

aura::Window* GetToplevelWindow(aura::Window* window) {
  aura::client::ActivationClient* client =
      aura::client::GetActivationClient(window->GetRootWindow());
  return client ? client->GetToplevelWindow(window) : NULL;
}

std::unique_ptr<ui::LayerTreeOwner> RecreateLayers(
    ui::LayerOwner* root,
    LayerDelegateFactory* factory) {
  std::unique_ptr<ui::LayerTreeOwner> old_layer(
      new ui::LayerTreeOwner(root->RecreateLayer().release()));
  if (old_layer->root()) {
    if (factory) {
      old_layer->root()->set_delegate(
          factory->CreateDelegate(root->layer()->delegate()));
    }
    CloneChildren(root->layer(), old_layer->root(), factory);
  }
  return old_layer;
}

aura::Window* GetTransientParent(aura::Window* window) {
  return const_cast<aura::Window*>(GetTransientParent(
                                 const_cast<const aura::Window*>(window)));
}

const aura::Window* GetTransientParent(const aura::Window* window) {
  const TransientWindowManager* manager = TransientWindowManager::Get(window);
  return manager ? manager->transient_parent() : NULL;
}

const std::vector<aura::Window*>& GetTransientChildren(
    const aura::Window* window) {
  const TransientWindowManager* manager = TransientWindowManager::Get(window);
  if (manager)
    return manager->transient_children();

  static std::vector<aura::Window*>* shared = new std::vector<aura::Window*>;
  return *shared;
}

void AddTransientChild(aura::Window* parent, aura::Window* child) {
  TransientWindowManager::Get(parent)->AddTransientChild(child);
}

void RemoveTransientChild(aura::Window* parent, aura::Window* child) {
  TransientWindowManager::Get(parent)->RemoveTransientChild(child);
}

bool HasTransientAncestor(const aura::Window* window,
                          const aura::Window* ancestor) {
  const aura::Window* transient_parent = GetTransientParent(window);
  if (transient_parent == ancestor)
    return true;
  return transient_parent ?
      HasTransientAncestor(transient_parent, ancestor) : false;
}

}  // namespace wm


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>A. Bloch Photography</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

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

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

    <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700" rel="stylesheet" type="text/css">

            <button type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" class="navbar-toggle">Toggle navigation</button>A.B.P.

About Amanda

Connect & Contact

FAQ

Blog

About

A Little About Me & My Photography.

What is A. Bloch Photography?

Hello! I am Amanda and thanks so much for visiting my site.  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Meet Amanda

A few fun facts about me; I have lived in Alaska, California, and Michigan; I love traveling and experiencing new things; I have the most amazing friends a girl could ask for; I enjoy hikes  with my husband and our golden retriever, Milly; and if I had it my way Hogwarts and the Shire would not be pretend!

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

Here is a Little Taste of My Life (via Instagram).

Connect & Contact

Lorem ipsum dolor sit amet consectetur.

              <form id="contactForm" name="sentMessage" novalidate="">

                      <input id="name" type="text" placeholder="Your Name *" required="" data-validation-required-message="Please enter your name." class="form-control">

                      <input id="email" type="email" placeholder="Your Email *" required="" data-validation-required-message="Please enter your email address." class="form-control">

                      <input id="date" type="text" placeholder="Wedding Date (if applicable)" class="form-control">

                      <textarea id="message" placeholder="Your Message *" required="" data-validation-required-message="Please enter a message." class="form-control"></textarea>

                    <button type="submit" class="btn btn-xl">Send Message</button>

              </form>

F.A.Q

Let Me Answer Some of Your Questions :)

How are travel costs calculated?

Travel Cost Calculator

                      <form class="inputs">

Please enter the locations's name or address

                          <input type="text" name="destination" placeholder="ex. The Georgia Aquarium or 123 Main Street" class="form-control">
                            <button type="submit" name="calculate" class="btn btn-default">Go!</button>

                      </form>

                        <form class="parameters input-group input-group-lg">
                          Origin Address
                            <input type="text" name="origin" class="form-control">

                          Travel Allowance (miles)
                            <input type="number" name="allowance" min="0" max="150" class="form-control">

                          Mileage Rate ($/mile)
                            <input type="number" name="rate" step="any" min="0" max="1" class="form-control">

                        </form>

                            Origin
                            Amanda's House

                            Destination Address

                            Round Trip Distance (miles)

                            Travel Allowance (miles):

                            Miles Over Travel Allowance:

                            Mileage Rate ($/mile)

                            Additional Cost:

                            Great News! This location is covered by your travel allowance.  No additional travel charges apply.

                            This location likley requires an overnight stay.  Please contact Amanda to work out the details

Copyright © A. Bloch Photography 2014


text:
int steviloVeder;
int zahtevanaKolicina;
int *velikostiVeder;

struct vedro
{
	unsigned short trenutnoStanje;
};

struct stanje
{
	struct vedro *tabela;
};

struct kolekcijaStanj
{
	struct stanje *stanja;
	int steviloStanj;
	int moznaStanja;
};

struct array
{
	int velikost;
	struct stanje* array;
	int maxSize;
};

struct hashTable
{
	struct array *bucket;
	int velikostTabele;
	int steviloElementov;
};

struct hashTable vsaStanja;

void inicializirajTabeloPrivate(struct hashTable *hashTable, int velikost) {
	hashTable->velikostTabele = velikost;
	hashTable->steviloElementov = 0;
	hashTable->bucket = malloc(hashTable->velikostTabele * (sizeof(struct array)));
	int i;
	for(i = 0; i < hashTable->velikostTabele; i++) {
		hashTable->bucket[i].velikost = 0;
		hashTable->bucket[i].maxSize = 10;
	}
}

int komparator(struct stanje prvo, struct stanje drugo){
	int i;
	for(i = 0; i < steviloVeder; i++){
		if(prvo.tabela[i].trenutnoStanje != drugo.tabela[i].trenutnoStanje)
			return 0;
	}
	return 1;
}

unsigned int hasher(struct stanje stanje) {

    unsigned int hash = 0;
    int i;
    for (i = 0 ; i < steviloVeder ; i++)
    {
        hash = ((hash<<5)+hash) + stanje.tabela[i].trenutnoStanje;
    }
    return hash;
}

int vsebujeElement(struct array list, struct stanje element){
	//printf("Enter vsebuje element");
	//printf("%d\n", list.velikost);
	int i;
	for(i = 0; i < list.velikost; i++) {
		if(komparator(list.array[i], element) == 1) {
	//printf("exit vsebuje element");
			return 1;
		}
	}
	//printf("exit vsebuje element");
	return 0;
}

void dodajElement(struct array *list, struct stanje element){
	if(list->velikost == 0){
		list->array = (struct stanje*)malloc(list->maxSize*sizeof(struct stanje));
	}
	else{
		if(list->velikost == list->maxSize) {
			list->maxSize *= 2;
			list->array = (struct stanje*)realloc(list->array, list->maxSize*sizeof(struct stanje));
		}
	}
	list->array[list->velikost++] = element;
	//printf("Exit dodaj element\n");
}

int vsebuje(struct stanje element, struct hashTable *hashTable) {
	//printf("Enter vsebuje");
	unsigned int hash = hasher(element)%hashTable->velikostTabele;

	//printf("%d\n", hash);
	struct array podArray = hashTable->bucket[hash];
	int val = vsebujeElement(podArray, element);
	//printf("Exit vsebuje");
	return val;
}

void vstavi(struct stanje element, struct hashTable *hashTable) {

	unsigned int hash = hasher(element)%hashTable->velikostTabele;
	struct array *podArray = &(hashTable->bucket[hash]);
	dodajElement(podArray, element);
	hashTable->steviloElementov++;
}

void napolniVedro(struct vedro *vedro, int i) {
	vedro->trenutnoStanje = velikostiVeder[i];
}

int jePolno(struct vedro *vedro, int i) {
	return vedro->trenutnoStanje == velikostiVeder[i];
}

int stanjeVedra(struct vedro *vedro) {
	return vedro->trenutnoStanje;
}

void zprazniVedro(struct vedro *vedro) {
	vedro->trenutnoStanje = 0;
}

int lahkoPrelijem(struct vedro *prvo, struct vedro *drugo, int indeksPrvo, int indeksDrugo) {
	if(prvo->trenutnoStanje == 0 || drugo->trenutnoStanje == velikostiVeder[indeksDrugo]) {
		return 0;
	}
	else {
		return prvo->trenutnoStanje >= velikostiVeder[indeksDrugo]-drugo->trenutnoStanje || velikostiVeder[indeksDrugo]-drugo->trenutnoStanje >= prvo->trenutnoStanje;
	}

}

void prelij(struct vedro *prvo, struct vedro *drugo, int indeksPrvo, int indeksDrugo) {
	if(prvo->trenutnoStanje >= velikostiVeder[indeksDrugo]-drugo->trenutnoStanje) {
		prvo->trenutnoStanje -= velikostiVeder[indeksDrugo]-drugo->trenutnoStanje;
		drugo->trenutnoStanje = velikostiVeder[indeksDrugo];
	}
	else {
		drugo->trenutnoStanje += prvo->trenutnoStanje;
		prvo->trenutnoStanje = 0;
	}
}

int jeKonec(struct stanje stanje){
	int i;
	for(i = 0; i < steviloVeder; i++) {
		if(stanje.tabela[i].trenutnoStanje == zahtevanaKolicina) {
			return 1;
		}
	}
	return 0;
}

int jeKonecPrograma(struct kolekcijaStanj kolekcija) {
	int i;
	for(i = 0; i < kolekcija.steviloStanj; i++) {
		if(jeKonec(kolekcija.stanja[i])) {
			return 1;
		}
	}
	return 0;
}

void izpisiStanje(struct stanje stanje){
    int i;
    printf("[");
    for(i=0; i<steviloVeder; i++) {
        printf("%d ", stanje.tabela[i].trenutnoStanje);
    }
    printf("]\n");
}

void izpisiKolekcijo(struct kolekcijaStanj *kolekcija) {
	int i;
	for(i = 0; i < kolekcija->steviloStanj; i++) {
		izpisiStanje(kolekcija->stanja[i]);
	}
	printf("\n");
}

int primerjajStanji(struct stanje *ena, struct stanje *dva) {
	int i;
	for(i = 0; i < steviloVeder; i++) {
		if(ena->tabela[i].trenutnoStanje != dva->tabela[i].trenutnoStanje) {
			return 0;
		}
	}
	return 1;
}

int zeObstajaStanje(struct kolekcijaStanj *kolekcijaStanj, struct stanje *trenutno) {
	int i;
	for(i = 0; i < kolekcijaStanj->steviloStanj; i++) {
		if(primerjajStanji(&kolekcijaStanj->stanja[i], trenutno) == 1) {
			return 1;
		}
	}
	return 0;
}

struct vedro *kopirajTabelo(struct vedro *tabela) {
	int i;
	struct vedro *novaTabela = malloc(steviloVeder*sizeof(struct vedro));
	for(i = 0; i < steviloVeder; i++) {
		novaTabela[i] = tabela[i];
	}
	return novaTabela;
}

int dodajNaKolekcijo(struct kolekcijaStanj *kolekcija, struct stanje dodaj) {
	if(jeKonec(dodaj)) {
		kolekcija->stanja[kolekcija->steviloStanj++] = dodaj;
		return 1;
	}
	if(!vsebuje(dodaj, &vsaStanja)) {
		kolekcija->stanja[kolekcija->steviloStanj++] = dodaj;
		if(kolekcija->steviloStanj == kolekcija->moznaStanja) {
			kolekcija->moznaStanja*=2;
			struct stanje *novaStanja = realloc(kolekcija->stanja, kolekcija->moznaStanja*sizeof(struct stanje));
			if(novaStanja == NULL) {
				printf("ERROR RELOCATING");
				exit(0);
			}
			kolekcija->stanja = novaStanja;
		}
		vstavi(dodaj, &vsaStanja);
	}
	return 0;
}

int generirajStanja(struct kolekcijaStanj *kolekcija, struct vedro *tabela){
	int i;
	int x;

	for(i = 0; i < steviloVeder; i++) {
		struct vedro trenutno = tabela[i];
		// NAPOLNIMO VSA VEDRA
		if(!jePolno(&trenutno, i)) {
			struct vedro *novaTabela = kopirajTabelo(tabela);
			napolniVedro(&novaTabela[i], i);
			struct stanje stanje;
			stanje.tabela = novaTabela;
			int a = dodajNaKolekcijo(kolekcija, stanje);
			if(a) {
				return 1;
			}

		}
		// IZPRAZNIMO VSA VEDRA
		if(trenutno.trenutnoStanje != 0) {
			struct vedro *novaTabela = kopirajTabelo(tabela);
			zprazniVedro(&novaTabela[i]);
			struct stanje stanje;
			stanje.tabela = novaTabela;
			int a = dodajNaKolekcijo(kolekcija, stanje);
			if(a) {
				return 1;
			}

		}
		// PRELIJEMO VSA VEDRA
		for(x = 0; x < steviloVeder; x++) {
			struct vedro novo = tabela[x];
			if(i == x) {
				continue;
			}
			if(lahkoPrelijem(&trenutno,&novo, i , x)) {
				struct stanje stanje;
				struct vedro *novaTabela = kopirajTabelo(tabela);
				prelij(&novaTabela[i], &novaTabela[x], i, x);
				stanje.tabela = novaTabela;
				int a = dodajNaKolekcijo(kolekcija, stanje);
				if(a) {
					return 1;
				}
			}
		}

	}
	return 0;
}

int main() {
	//setbuf(stdout, NULL);

	// PREBRAN VHOD
	scanf("%d", &steviloVeder);
	int i;
	struct stanje stanje;
	velikostiVeder = malloc(steviloVeder*sizeof(int));
	stanje.tabela = malloc(steviloVeder*sizeof(struct vedro));
	for(i = 0; i < steviloVeder; i++) {
		scanf("%d", &velikostiVeder[i]);
		stanje.tabela[i].trenutnoStanje = 0;
	}
	scanf("%d", &zahtevanaKolicina);
	// PREBRAN VHOD
	//printf("STEVILO VEDER: %d\n", steviloVeder);
	//printf("ZELJENA KOLICINA: %d\n", zahtevanaKolicina);

	// INICIALIZACIJA STANJ
	struct kolekcijaStanj kolekcijaStanj;
	struct kolekcijaStanj stara;
	inicializirajTabeloPrivate(&vsaStanja, 100000);
	scanf("%d", &zahtevanaKolicina);
	kolekcijaStanj.moznaStanja = 1000;
	stara.moznaStanja = 1000;
	kolekcijaStanj.stanja = malloc(kolekcijaStanj.moznaStanja*sizeof(struct stanje));
	stara.stanja = malloc(stara.moznaStanja*sizeof(struct stanje));
	stara.steviloStanj = 1;
	stara.stanja[0] = stanje;
	kolekcijaStanj.steviloStanj = 0;
	// INICIALIZACIJA STANJ

	int steviloKorakov = 0;

	// DOKLER SE PROGRAM NE ZAKLJUČI
	while(!jeKonecPrograma(stara)) {

		steviloKorakov++;
		// for zanka skoz vsako stanje za generiranje stanj
		for(i = 0; i < stara.steviloStanj; i++) {
			stanje = stara.stanja[i];
			int a = generirajStanja(&kolekcijaStanj, stanje.tabela);
			if(a) {
				break;
			}
		}
		// stara se bo uporabla v naslednji iteraciji, kolekcijaStanj gre na nič za nova stanja
		struct kolekcijaStanj temp = stara;
		stara = kolekcijaStanj;
		kolekcijaStanj = temp;
		kolekcijaStanj.steviloStanj = 0;

		//izpisiKolekcijo(&stara);
		//printf("ITEARCIJA, STEVILO STANJ %d %d\n", steviloKorakov, vsaStanja.steviloElementov);
	}
	// DOKLER SE PROGRAM NE ZAKLJUČI
	printf("%d\n", steviloKorakov);

	return 0;
}


text:
require File.dirname(__FILE__) + '/test_helper'

# make sure the worlds not fallen from beneith us.
class ResqueTest < Test::Unit::TestCase

  def test_resque_version
    major, minor, patch = Resque::Version.split('.')
    assert_equal 1, major.to_i, 'major version does not match'
    assert_operator minor.to_i, :>=, 8, 'minor version is too low'
  end

  def test_resque_plugin_lint
    assert_nothing_raised do
      Resque::Plugin.lint(Resque::Plugins::ParallelLimit)
    end
  end

end


text:
from flask_securest.authentication_providers.abstract_authentication_provider\
    import AbstractAuthenticationProvider
from flask_securest.models import User

class AuthorizeUser1(AbstractAuthenticationProvider):

    def __init__(self, dummy_param):
        self._dummy_param = dummy_param

    def authenticate(self, auth_info, userstore):
        if not self._dummy_param:
            return ValueError('dummy_param is missing or empty')

        if userstore:
            raise ValueError("userstore specified, but I don't want it")

        if auth_info.user_id != 'user1':
            raise Exception('invalid username, only user1 is valid')

        return User('mockuser1', 'mockpass1', 'mockuser1@mock.com', [],
                    active=True)


text:
from sklearn.cluster import Birch as sk_Birch
from .clustering import Clustering

class Birch(Clustering):
    """docstring for Birch."""
    def __init__(self, data, threshold = 0.5, branching_factor = 50,
                 n_clusters = 3, compute_labels = True, copy = True):
        super(Birch, self).__init__()
        self.data = data
        self.threshold = threshold
        self.branching_factor = branching_factor
        self.n_clusters = n_clusters
        self.compute_labels = compute_labels
        self.copy = copy

    def execute(self):
        """Constroi o modelo de clusterizacao."""
        self.model = sk_Birch(threshold = self.threshold,
                              branching_factor = self.branching_factor,
                              n_clusters = self.n_clusters,
                              compute_labels = self.compute_labels,
                              copy = self.copy).fit(self.data)

        self.clusters = super().make_clusters(self.data, self.model.labels_)

    @property
    def labels_(self):
        """Retorna os labels dos elementos do dataset."""
        return self.model.labels_

    @property
    def clusters_(self):
        """Retorna um dicionaro onde os indices dos grupos sao as chaves."""
        return self.clusters

    @property
    def model_(self):
        """Retorna o modelo de agrupamento."""
        return self.model_


text:
.class public final Landroid/net/Downloads$ById;
.super Landroid/net/Downloads$DownloadBase;
.source "Downloads.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/Downloads;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "ById"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 344
    invoke-direct {p0}, Landroid/net/Downloads$DownloadBase;-><init>()V

    return-void
.end method

.method public static deleteDownload(Landroid/content/Context;J)V
    .locals 4
    .parameter "context"
    .parameter "downloadId"

    .prologue
    const/4 v3, 0x0

    .line 374
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 376
    .local v0, cr:Landroid/content/ContentResolver;
    const/4 v2, 0x0

    .line 378
    .local v2, mimeType:Ljava/lang/String;
    invoke-static {p1, p2}, Landroid/net/Downloads$ById;->getDownloadUri(J)Landroid/net/Uri;

    move-result-object v1

    .line 380
    .local v1, downloadUri:Landroid/net/Uri;
    invoke-virtual {v0, v1, v3, v3}, Landroid/content/ContentResolver;->delete(Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I

    .line 381
    return-void
.end method

.method private static getDownloadUri(J)Landroid/net/Uri;
    .locals 2
    .parameter "downloadId"

    .prologue
    .line 415
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    sget-object v1, Landroid/provider/Downloads$Impl;->CONTENT_URI:Landroid/net/Uri;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, "/"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p0, p1}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static getMimeTypeForId(Landroid/content/Context;J)Ljava/lang/String;
    .locals 8
    .parameter "context"
    .parameter "downloadId"

    .prologue
    .line 350
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 352
    .local v0, cr:Landroid/content/ContentResolver;
    const/4 v7, 0x0

    .line 353
    .local v7, mimeType:Ljava/lang/String;
    const/4 v6, 0x0

    .line 356
    .local v6, downloadCursor:Landroid/database/Cursor;
    :try_start_0
    invoke-static {p1, p2}, Landroid/net/Downloads$ById;->getDownloadUri(J)Landroid/net/Uri;

    move-result-object v1

    .line 358
    .local v1, downloadUri:Landroid/net/Uri;
    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/String;

    const/4 v3, 0x0

    const-string/jumbo v4, "mimetype"

    aput-object v4, v2, v3

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 361
    invoke-interface {v6}, Landroid/database/Cursor;->moveToNext()Z

    move-result v2

    if-eqz v2, :cond_0

    .line 362
    const/4 v2, 0x0

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v7

    .line 365
    :cond_0
    if-eqz v6, :cond_1

    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    .line 367
    :cond_1
    return-object v7

    .line 365
    .end local v1           #downloadUri:Landroid/net/Uri;
    :catchall_0
    move-exception v2

    if-eqz v6, :cond_2

    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_2
    throw v2
.end method

.method public static final getStatus(Landroid/content/Context;J)Landroid/net/Downloads$StatusInfo;
    .locals 15
    .parameter "context"
    .parameter "downloadId"

    .prologue
    .line 425
    const/4 v12, 0x0

    .line 426
    .local v12, result:Landroid/net/Downloads$StatusInfo;
    const/4 v9, 0x0

    .line 427
    .local v9, hasFailedDownload:Z
    const-wide/16 v7, 0x0

    .line 429
    .local v7, failedDownloadModificationTime:J
    invoke-static/range {p1 .. p2}, Landroid/net/Downloads$ById;->getDownloadUri(J)Landroid/net/Uri;

    move-result-object v1

    .line 431
    .local v1, downloadUri:Landroid/net/Uri;
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 433
    .local v0, cr:Landroid/content/ContentResolver;
    invoke-static {}, Landroid/net/Downloads;->access$000()[Ljava/lang/String;

    move-result-object v2

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 436
    .local v6, c:Landroid/database/Cursor;
    if-eqz v6, :cond_0

    :try_start_0
    invoke-interface {v6}, Landroid/database/Cursor;->moveToNext()Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v2

    if-nez v2, :cond_2

    .line 459
    :cond_0
    if-eqz v6, :cond_1

    .line 460
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_1
    move-object v13, v12

    .line 463
    .end local v12           #result:Landroid/net/Downloads$StatusInfo;
    .local v13, result:Landroid/net/Downloads$StatusInfo;
    :goto_0
    return-object v13

    .line 440
    .end local v13           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v12       #result:Landroid/net/Downloads$StatusInfo;
    :cond_2
    if-nez v12, :cond_3

    .line 441
    :try_start_1
    new-instance v13, Landroid/net/Downloads$StatusInfo;

    invoke-direct {v13}, Landroid/net/Downloads$StatusInfo;-><init>()V

    .end local v12           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v13       #result:Landroid/net/Downloads$StatusInfo;
    move-object v12, v13

    .line 443
    .end local v13           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v12       #result:Landroid/net/Downloads$StatusInfo;
    :cond_3
    const-wide/16 v2, 0x0

    #calls: Landroid/net/Downloads;->getStatusOfDownload(Landroid/database/Cursor;J)I
    invoke-static {v6, v2, v3}, Landroid/net/Downloads;->access$100(Landroid/database/Cursor;J)I

    move-result v14

    .line 444
    .local v14, status:I
    const/4 v2, 0x3

    if-eq v14, v2, :cond_4

    const/4 v2, 0x4

    if-ne v14, v2, :cond_7

    .line 446
    :cond_4
    const/4 v2, 0x4

    if-ne v14, v2, :cond_6

    const/4 v2, 0x1

    :goto_1
    iput-boolean v2, v12, Landroid/net/Downloads$StatusInfo;->completed:Z

    .line 447
    const/4 v2, 0x3

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v2

    iput-object v2, v12, Landroid/net/Downloads$StatusInfo;->filename:Ljava/lang/String;

    .line 448
    const/4 v2, 0x0

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v2

    iput-wide v2, v12, Landroid/net/Downloads$StatusInfo;->id:J

    .line 449
    const/4 v2, 0x2

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getInt(I)I

    move-result v2

    iput v2, v12, Landroid/net/Downloads$StatusInfo;->statusCode:I

    .line 450
    const/4 v2, 0x5

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v2

    iput-wide v2, v12, Landroid/net/Downloads$StatusInfo;->bytesSoFar:J
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    .line 459
    if-eqz v6, :cond_5

    .line 460
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_5
    move-object v13, v12

    .end local v12           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v13       #result:Landroid/net/Downloads$StatusInfo;
    goto :goto_0

    .line 446
    .end local v13           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v12       #result:Landroid/net/Downloads$StatusInfo;
    :cond_6
    const/4 v2, 0x0

    goto :goto_1

    .line 454
    :cond_7
    const/4 v2, 0x4

    :try_start_2
    invoke-interface {v6, v2}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v10

    .line 456
    .local v10, modTime:J
    const/4 v2, 0x2

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getInt(I)I

    move-result v2

    iput v2, v12, Landroid/net/Downloads$StatusInfo;->statusCode:I

    .line 457
    const/4 v2, 0x5

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v2

    iput-wide v2, v12, Landroid/net/Downloads$StatusInfo;->bytesSoFar:J
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    .line 459
    if-eqz v6, :cond_8

    .line 460
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_8
    move-object v13, v12

    .line 463
    .end local v12           #result:Landroid/net/Downloads$StatusInfo;
    .restart local v13       #result:Landroid/net/Downloads$StatusInfo;
    goto :goto_0

    .line 459
    .end local v10           #modTime:J
    .end local v13           #result:Landroid/net/Downloads$StatusInfo;
    .end local v14           #status:I
    .restart local v12       #result:Landroid/net/Downloads$StatusInfo;
    :catchall_0
    move-exception v2

    if-eqz v6, :cond_9

    .line 460
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_9
    throw v2
.end method

.method public static openDownload(Landroid/content/Context;JLjava/lang/String;)Landroid/os/ParcelFileDescriptor;
    .locals 4
    .parameter "context"
    .parameter "downloadId"
    .parameter "mode"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/FileNotFoundException;
        }
    .end annotation

    .prologue
    .line 390
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 392
    .local v0, cr:Landroid/content/ContentResolver;
    const/4 v2, 0x0

    .line 394
    .local v2, mimeType:Ljava/lang/String;
    invoke-static {p1, p2}, Landroid/net/Downloads$ById;->getDownloadUri(J)Landroid/net/Uri;

    move-result-object v1

    .line 396
    .local v1, downloadUri:Landroid/net/Uri;
    invoke-virtual {v0, v1, p3}, Landroid/content/ContentResolver;->openFileDescriptor(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;

    move-result-object v3

    return-object v3
.end method

.method public static openDownloadStream(Landroid/content/Context;J)Ljava/io/InputStream;
    .locals 4
    .parameter "context"
    .parameter "downloadId"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/FileNotFoundException;,
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 405
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 407
    .local v0, cr:Landroid/content/ContentResolver;
    const/4 v2, 0x0

    .line 409
    .local v2, mimeType:Ljava/lang/String;
    invoke-static {p1, p2}, Landroid/net/Downloads$ById;->getDownloadUri(J)Landroid/net/Uri;

    move-result-object v1

    .line 411
    .local v1, downloadUri:Landroid/net/Uri;
    invoke-virtual {v0, v1}, Landroid/content/ContentResolver;->openInputStream(Landroid/net/Uri;)Ljava/io/InputStream;

    move-result-object v3

    return-object v3
.end method


text:
module IceCube

  module Validations::DayOfMonth

    include Validations::Lock

    def day_of_month(*days)
      days.each do |day|
        validations_for(:day_of_month) << Validation.new(day)
      end
      clobber_base_validations(:day, :wday)
      self
    end

    class Validation

      include Validations::Lock

      StringBuilder.register_formatter(:day_of_month) do |entries|
        str = "on the #{StringBuilder.sentence(entries)} "
        str << (entries.size == 1 ? 'day of the month' : 'days of the month')
        str
      end

      attr_reader :day
      alias :value :day

      def initialize(day)
        @day = day
      end

      def build_s(builder)
        builder.piece(:day_of_month) << StringBuilder.nice_number(day)
      end

      def build_hash(builder)
        builder.validations_array(:day_of_month) << day
      end

      def build_ical(builder)
        builder['BYMONTHDAY'] << day
      end

      def type
        :day
      end

    end

  end

end


text:
#include "ZRpcInterface.h"

ZRpcInterface::ZRpcInterface(CmdResult *CmdResult, LcmInterface *LcmInterface)
{
    Z_Payload = 0;
    Z_Payload_SetBaudrate = 0;
    cmdResult_ = CmdResult;
    lcmInterface_ = LcmInterface;

    Z_IndataBuffer = new LockLessQueue(10);
}

ZRpcInterface::~ZRpcInterface()
{
    delete Z_IndataBuffer;
    delete[] Z_Payload;
    delete[] Z_Payload_SetBaudrate;
}

ErrorCode_e ZRpcInterface::Do_CEH_Callback(CommandData_t *CmdData_p)
{
    ErrorCode_e Status = E_GENERAL_FATAL_ERROR;

    Status = DoneRPC_Z_ReadImpl(*CmdData_p);

    return Status;
}

ErrorCode_e ZRpcInterface::DoRPC_Z_VersionRequest()
{
    ErrorCode_e Result = E_SUCCESS;

    if (Z_Payload != 0) {
        delete [] Z_Payload;
        Z_Payload = 0;
    }

    Z_Payload = new uint8[2];
    Z_Payload[0] = 0x01;
    Z_Payload[1] = 0x3F;

    Result = lcmInterface_->CommunicationSend(Z_Payload);

    return Result;
}

ErrorCode_e ZRpcInterface::DoRPC_Z_SetBaudrate(int Baudrate)
{
    ErrorCode_e Result = E_SUCCESS;
    char Rate;

    switch (Baudrate) {
    case 9600:
        Rate = '0';
        break;

    case 19200:
        Rate = '1';
        break;

    case 38400:
        Rate = '2';
        break;

    case 57600:
        Rate = '3';
        break;

    case 115200:
        Rate = '4';
        break;

    case 230400:
        Rate = '5';
        break;

    case 460800:
        Rate = '6';
        break;

    case 921600:
        Rate = '7';
        break;

    case 1625000:
        Rate = '8';
        break;

    default :
        return E_INVALID_INPUT_PARAMETERS;
    }

    if (Z_Payload != 0) {
        delete [] Z_Payload;
        Z_Payload = 0;
    }

    Z_Payload = new uint8[2];

    Z_Payload[0] = 0x01;
    Z_Payload[1] = 'S';

    Result = lcmInterface_->CommunicationSend(Z_Payload);

    Z_Payload_SetBaudrate = new uint8[2];
    Z_Payload_SetBaudrate[0] = 0x01;
    Z_Payload_SetBaudrate[1] = Rate;

    Result = lcmInterface_->CommunicationSend(Z_Payload_SetBaudrate);

    return Result;
}

ErrorCode_e ZRpcInterface::DoRPC_Z_Exit_Z_Protocol()
{
    ErrorCode_e Result = E_SUCCESS;

    if (Z_Payload != 0) {
        delete [] Z_Payload;
        Z_Payload = 0;
    }

    Z_Payload = new uint8[2];
    Z_Payload[0] = 0x01;
    Z_Payload[1] = 'Q';

    Result = lcmInterface_->CommunicationSend(Z_Payload);

    return Result;
}

ErrorCode_e ZRpcInterface::DoneRPC_Z_ReadImpl(CommandData_t CmdData)
{
    unsigned char Data_p = *CmdData.Payload.Data_p;
    bool Full = false;

    Z_IndataBuffer->Push(Data_p, &Full);

    if (Full == true) {
        return E_GENERAL_FATAL_ERROR;
    }

    return E_SUCCESS;
}


text:
package org.jkiss.dbeaver.model.impl.auth;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.auth.*;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Session context implementation
 */
public class SessionContextImpl implements SMSessionContext {
    private static final Log log = Log.getLog(SessionContextImpl.class);

    private final SMSessionContext parentContext;
    private final List<SMSession> sessions = new ArrayList<>();

    public SessionContextImpl(SMSessionContext parentContext) {
        this.parentContext = parentContext;
    }

    @Nullable
    @Override
    public SMSession getSpaceSession(@NotNull DBRProgressMonitor monitor, @NotNull SMAuthSpace space, boolean open) throws DBException {
        for (SMSession session : sessions) {
            if (CommonUtils.equalObjects(session.getSessionSpace(), space)) {
                return session;
            }
        }
        //log.debug(">> Session not found in context " + this + " for space " + space);
        SMSession session = parentContext == null ? null : parentContext.getSpaceSession(monitor, space, false);
        if (session == null && open) {
            SMSessionProviderService sessionProviderService = DBWorkbench.getService(SMSessionProviderService.class);
            if (sessionProviderService != null) {
                try {
                    // Session will be added in this context by itself (if needed)
                    session = sessionProviderService.acquireSession(monitor, this, space);
                    if (session != null) {
                        addSession(session);
                    }
                } catch (Exception e) {
                    throw new DBException("Error acquiring session", e);
                }
            }
        }
        return session;
    }

    @Override
    public SMAuthToken[] getSavedTokens() {
        return new SMAuthToken[0];
    }

    public void addSession(@NotNull SMSession session) {
        if (!sessions.contains(session)) {
            sessions.add(session);
            //log.debug(">> Session added to context " + this + ", space=" + session.getSessionSpace() + ": " + session, new Exception());
        } else {
            log.debug("Session '" + session + "' was added twice");
        }
    }

    @Override
    public boolean removeSession(@NotNull SMSession session) {
        if (sessions.remove(session)) {
            //log.debug(">> Session removed from context " + this + ", space=" + session.getSessionSpace()  + ": " + session, new Exception());
            return true;
        } else {
            log.debug("Session '" + session + "' was removed twice");
            return false;
        }
    }

    public void close() {
        this.sessions.clear();
    }

}


text:
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace BehaviorsTestApplication.Views.Pages;

public class ChangePropertyActionView : UserControl
{
    public ChangePropertyActionView()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }
}


text:
require 'puppet/util/feature'

Puppet.features.add(:crx_packmgr_api_client, libs: %w[crx_packmgr_api_client])


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/compliantcontacts.iml" filepath="$PROJECT_DIR$/compliantcontacts.iml" />
    </modules>
  </component>
</project>


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright Bruno Lalande 2008, 2009
// Copyright Barend Gehrels 2007-2009, Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_EXTENSIONS_NSPHERE_GEOMETRIES_CONCEPTS_NSPHERE_CONCEPT_HPP
#define BOOST_GEOMETRY_EXTENSIONS_NSPHERE_GEOMETRIES_CONCEPTS_NSPHERE_CONCEPT_HPP

#include <boost/concept_check.hpp>

#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/extensions/nsphere/core/radius.hpp>

namespace boost { namespace geometry { namespace concept {

/*!
    \brief Checks Nsphere concept (const version)
    \ingroup concepts
    \details The ConstNsphere concept check the same as the Nsphere concept,
    but does not check write access.
*/
template <typename Geometry>
class ConstNsphere
{
    typedef typename point_type<Geometry>::type point_type;
    typedef typename radius_type<Geometry>::type radius_type;

    template <size_t Dimension, size_t DimensionCount>
    struct dimension_checker
    {
        static void apply()
        {
            typedef typename coordinate_type<Geometry>::type coordinate_type;
            const Geometry* s = 0;
            coordinate_type coord(geometry::get<Dimension>(*s));
            boost::ignore_unused_variable_warning(coord);
            dimension_checker<Dimension + 1, DimensionCount>::apply();
        }
    };

    template <size_t DimensionCount>
    struct dimension_checker<DimensionCount, DimensionCount>
    {
        static void apply() {}
    };

public :

    BOOST_CONCEPT_USAGE(ConstNsphere)
    {
        static const size_t n = dimension<Geometry>::value;
        dimension_checker<0, n>::apply();
        dimension_checker<0, n>::apply();

        // Check radius access
        Geometry const* s = 0;
        radius_type coord(geometry::get_radius<0>(*s));
        boost::ignore_unused_variable_warning(coord);
    }
};

/*!
    \brief Checks nsphere concept
    \ingroup concepts
*/
template <typename Geometry>
class Nsphere
{
    BOOST_CONCEPT_ASSERT( (concept::ConstNsphere<Geometry>) );

    typedef typename point_type<Geometry>::type point_type;
    typedef typename radius_type<Geometry>::type radius_type;

    template <size_t Dimension, size_t DimensionCount>
    struct dimension_checker
    {
        static void apply()
        {
            Geometry* s;
            geometry::set<Dimension>(*s, geometry::get<Dimension>(*s));
            dimension_checker<Dimension + 1, DimensionCount>::apply();
        }
    };

    template <size_t DimensionCount>
    struct dimension_checker<DimensionCount, DimensionCount>
    {
        static void apply() {}
    };

public :

    BOOST_CONCEPT_USAGE(Nsphere)
    {
        static const size_t n = dimension<Geometry>::type::value;
        dimension_checker<0, n>::apply();
        dimension_checker<0, n>::apply();

        // Check radius access
        Geometry* s = 0;
        set_radius<0>(*s, get_radius<0>(*s));
    }
};

}}} // namespace boost::geometry::concept

#endif // BOOST_GEOMETRY_EXTENSIONS_NSPHERE_GEOMETRIES_CONCEPTS_NSPHERE_CONCEPT_HPP