text:
.. _tutorial-multi-master:

=====================
Multi Master Tutorial
=====================

As of Salt 0.16.0, the ability to connect minions to multiple masters has been
made available. The multi-master system allows for redundancy of Salt
masters and facilitates multiple points of communication out to minions. When
using a multi-master setup, all masters are running hot, and any active master
can be used to send commands out to the minions.

.. note::
    If you need failover capabilities with multiple masters, there is also a
    MultiMaster-PKI setup available, that uses a different topology
    `MultiMaster-PKI with Failover Tutorial <https://docs.saltproject.io/en/latest/topics/tutorials/multimaster_pki.html>`_

In 0.16.0, the masters do not share any information, keys need to be accepted
on both masters, and shared files need to be shared manually or use tools like
the git fileserver backend to ensure that the :conf_master:`file_roots` are
kept consistent.

Beginning with Salt 2016.11.0, the :ref:`Pluggable Minion Data Cache <pluggable-data-cache>`
was introduced. The minion data cache contains the Salt Mine data, minion grains, and minion
pillar information cached on the Salt Master. By default, Salt uses the ``localfs`` cache
module, but other external data stores can be used instead.

Using a pluggable minion cache modules allows for the data stored on a Salt Master about
Salt Minions to be replicated on other Salt Masters the Minion is connected to. Please see
the :ref:`Minion Data Cache <cache>` documentation for more information and configuration
examples.

Summary of Steps
----------------

1. Create a redundant master server
2. Copy primary master key to redundant master
3. Start redundant master
4. Configure minions to connect to redundant master
5. Restart minions
6. Accept keys on redundant master

Prepping a Redundant Master
---------------------------

The first task is to prepare the redundant master. If the redundant master is
already running, stop it. There is only one requirement when preparing a
redundant master, which is that masters share the same private key. When the
first master was created, the master's identifying key pair was generated and
placed in the master's ``pki_dir``. The default location of the master's key
pair is ``/etc/salt/pki/master/``. Take the private key, ``master.pem``, and
copy it to the same location on the redundant master. Do the same for the
master's public key, ``master.pub``. Assuming that no minions have yet been
connected to the new redundant master, it is safe to delete any existing key
in this location and replace it.

.. note::
    There is no logical limit to the number of redundant masters that can be
    used.

Once the new key is in place, the redundant master can be safely started.

Configure Minions
-----------------

Since minions need to be master-aware, the new master needs to be added to the
minion configurations. Simply update the minion configurations to list all
connected masters:

.. code-block:: yaml

    master:
      - saltmaster1.example.com
      - saltmaster2.example.com

Now the minion can be safely restarted.

.. note::

    If the ipc_mode for the minion is set to TCP (default in Windows), then
    each minion in the multi-minion setup (one per master) needs its own
    tcp_pub_port and tcp_pull_port.

    If these settings are left as the default 4510/4511, each minion object
    will receive a port 2 higher than the previous. Thus the first minion will
    get 4510/4511, the second will get 4512/4513, and so on. If these port
    decisions are unacceptable, you must configure tcp_pub_port and
    tcp_pull_port with lists of ports for each master. The length of these
    lists should match the number of masters, and there should not be overlap
    in the lists.

Now the minions will check into the original master and also check into the new
redundant master. Both masters are first-class and have rights to the minions.

.. note::

    Minions can automatically detect failed masters and attempt to reconnect
    to them quickly. To enable this functionality, set
    `master_alive_interval` in the minion config and specify a number of
    seconds to poll the masters for connection status.

    If this option is not set, minions will still reconnect to failed masters
    but the first command sent after a master comes back up may be lost while
    the minion authenticates.

Sharing Files Between Masters
-----------------------------

Salt does not automatically share files between multiple masters. A number of
files should be shared or sharing of these files should be strongly considered.

Minion Keys
```````````

Minion keys can be accepted the normal way using :strong:`salt-key` on both
masters.  Keys accepted, deleted, or rejected on one master will NOT be
automatically managed on redundant masters; this needs to be taken care of by
running salt-key on both masters or sharing the
``/etc/salt/pki/master/{minions,minions_pre,minions_rejected}`` directories
between masters.

.. note::

    While sharing the :strong:`/etc/salt/pki/master` directory will work, it is
    strongly discouraged, since allowing access to the :strong:`master.pem` key
    outside of Salt creates a *SERIOUS* security risk.

File_Roots
``````````

The :conf_master:`file_roots` contents should be kept consistent between
masters. Otherwise state runs will not always be consistent on minions since
instructions managed by one master will not agree with other masters.

The recommended way to sync these is to use a fileserver backend like gitfs or
to keep these files on shared storage.

.. important::
   If using gitfs/git_pillar with the cachedir shared between masters using
   `GlusterFS`_, nfs, or another network filesystem, and the masters are
   running Salt 2015.5.9 or later, it is strongly recommended not to turn off
   :conf_master:`gitfs_global_lock`/:conf_master:`git_pillar_global_lock` as
   doing so will cause lock files to be removed if they were created by a
   different master.

.. _GlusterFS: http://www.gluster.org/

Pillar_Roots
````````````

Pillar roots should be given the same considerations as
:conf_master:`file_roots`.

Master Configurations
`````````````````````

While reasons may exist to maintain separate master configurations, it is wise
to remember that each master maintains independent control over minions.
Therefore, access controls should be in sync between masters unless a valid
reason otherwise exists to keep them inconsistent.

These access control options include but are not limited to:

- external_auth
- publisher_acl
- peer
- peer_run


text:
using System;
using ObjCRuntime;

[assembly: LinkWith ("FBSDKCoreKit.a", LinkTarget.Simulator | LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Arm64 | LinkTarget.Simulator64, SmartLink = true, ForceLoad = true)]

redpajama_set_name: RedPajamaGithub


text:
package org.broadinstitute.hellbender.tools.funcotator.filtrationRules;

import java.util.Map;

/**
 * A rule to match against the Funcotations from a variant within a {@link FuncotationFilter}.
 */
interface FuncotationFiltrationRule {

    /**
     * Check if a set of Funcotations matches this rule.
     */
    boolean checkRule(final Map<String, String> funcotations);
}


text: console.log("code for initialization, e.g. angular modules and bootstrap");


text:
import template from './profile.route.html';

export function profileRoutes($stateProvider) {
    'ngInject';

    $stateProvider
        .state('app.profile', {
            url: '/',
            template,
            resolve: {
                posts: resolvePosts,
                followers: resolveFollowers
            }
        });

    function resolvePosts() {
        'ngInject';
        return [];
    }

    function resolveFollowers() {
        'ngInject';
        return [];
    }
}


text:
inline int coda_str_empty(const char *str)
{
    return !str || !*str;
}


text:
// S60 inlcudes
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <barsread.h>
#include <stringloader.h>
#include <eiklabel.h>
#include <eikenv.h>
#include <gdi.h>
#include <eikseced.h>
#include <akncontext.h>
#include <akntitle.h>
#include <eikbtgpc.h>

// project includes
#include <wayfinder8_s60v5.rsg>
#include "wayfinder.hrh"
#include "WayFinderConstants.h"
#include "WayFinderAppUi.h"
#include "WFTextUtil.h"
#include "GuiProt/GuiProtMess.h"
#include "GuiProt/GuiParameterEnums.h"

#include "MyAccountView.h"
#include "MyAccountContainer.h"

using namespace isab;

/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CMyAccountView::CMyAccountView(CWayFinderAppUi* aUi) :
   CViewBase(aUi)
{
   iMyAccountContainer = NULL;

}

/**
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CMyAccountView::~CMyAccountView()
{
   delete iMyAccountContainer;
   iMyAccountContainer = NULL;

   iPassword.Close();
   iUsername.Close();
}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CMyAccountViewView
 */
CMyAccountView* CMyAccountView::NewL(CWayFinderAppUi* aUi,
                                         isab::Log* aLog)
	{
	CMyAccountView* self = CMyAccountView::NewLC(aUi,aLog);
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CMyAccountViewView
 */
CMyAccountView* CMyAccountView::NewLC(CWayFinderAppUi* aUi, isab::Log* /*aLog*/)
	{
	CMyAccountView* self = new ( ELeave ) CMyAccountView(aUi);
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}

/**
 * Second-phase constructor for view.
 * Initialize contents from resource.
 */
void
CMyAccountView::ConstructL()
{
   BaseConstructL(R_MY_ACCOUNT_VIEW);

   iPassword.Create(KBuf64Length);
   iUsername.Create(KBuf64Length);
}

/**
 * @return The UID for this view
 */
TUid
CMyAccountView::Id() const
{
   return KMyAccountViewId;
}

/**
 * Handle a command for this My Account view
 * The user can select either Update or Cancel
 * @param aCommand command id to be handled
 */
void
CMyAccountView::HandleCommandL(TInt aCommand)
{
   switch (aCommand) {
   case EAknSoftkeyCancel:
      // user has selected Cancel
      iWayfinderAppUi->pop();
      break;
   case EAknSoftkeyOk:
      // user has selected update, so check if password has changed
      iMyAccountContainer->GetPassword(iPassword);
      if (iPassword.Length()) {
         char* tmp_str = WFTextUtil::newTDesDupL(iPassword);
         GeneralParameterMess* gen_mess;
         gen_mess = new (ELeave) GeneralParameterMess(
               GuiProtEnums::paramWebPassword, tmp_str);

         iWayfinderAppUi->SendMessageL(gen_mess);
         gen_mess->deleteMembers();
         delete gen_mess;
      }
      // user has selected update
      iWayfinderAppUi->pop();
      break;
   default:
      {
         CAknView::HandleCommandL(aCommand);
         break;
      }
   }
}

/**
 * Handles user actions during activation of the view,
 * such as initializing the content.
 */
void CMyAccountView::DoActivateL(const TVwsViewId& /*aPrevViewId*/,
                            TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
{
   SetupStatusPaneL();
   HBufC* titleText = StringLoader::LoadLC(R_S60_MY_ACCOUNT_TXT);
   iWayfinderAppUi->setTitleText(titleText->Des());
   CleanupStack::PopAndDestroy(titleText);

   if (iMyAccountContainer == NULL) {
      iMyAccountContainer = CreateContainerL();
      iMyAccountContainer->SetMopParent(this);
      AppUi()->AddToStackL(*this, iMyAccountContainer);

      CEikButtonGroupContainer* buttonGroupContainer=CEikButtonGroupContainer::Current();
      buttonGroupContainer->MakeCommandVisible(EAknSoftkeyOk,EFalse);

   }

}

/*
 * Called when de-activating view
 */
void
CMyAccountView::DoDeactivate()
{
   CleanupStatusPane();

   if (iMyAccountContainer != NULL) {
      AppUi()->RemoveFromViewStack(*this, iMyAccountContainer);
      delete iMyAccountContainer;
      iMyAccountContainer = NULL;
   }

}

/**
 * Handle status pane size change for this view (override)
 */
void
CMyAccountView::HandleStatusPaneSizeChange()
{
   CAknView::HandleStatusPaneSizeChange();

   // this may fail, but we're not able to propagate exceptions here
   TVwsViewId view;
   AppUi()->GetActiveViewId(view);
   if (view.iViewUid == Id()) {
      TInt result;
      TRAP( result, SetupStatusPaneL() );
   }

}

void
CMyAccountView::SetupStatusPaneL()
{
   // reset the context pane
   TUid contextPaneUid = TUid::Uid(EEikStatusPaneUidContext);
   CEikStatusPaneBase::TPaneCapabilities subPaneContext =
         StatusPane()->PaneCapabilities(contextPaneUid);
   if (subPaneContext.IsPresent() && subPaneContext.IsAppOwned()) {
      CAknContextPane* context =
            static_cast<CAknContextPane*> (StatusPane()->ControlL(
                  contextPaneUid));
      context->SetPictureToDefaultL();
   }
}

void
CMyAccountView::CleanupStatusPane()
{
}

/**
 * Creates the top-level container for the view.  You may modify this method's
 * contents and the CMyAccountView::NewL() signature as needed to initialize the
 * container, but the signature for this method is fixed.
 * @return new initialized instance of CMyAccountView
 */
CMyAccountContainer*
CMyAccountView::CreateContainerL()
{
   return CMyAccountContainer::NewL(ClientRect(), NULL, this, iUsername);
}

void
CMyAccountView::SetUserName(const char* aUser)
{
   // copy the char* username and password into RBuf
   TInt i = 0;
   iUsername.Zero();
   while (aUser[i]) {
      iUsername.Append(aUser[i]);
      i++;
   }
}


text:
namespace Spready.Commands
{
    /// <summary>
    /// Contract for all commands.
    /// </summary>
    public interface ICommand
    {
        /// <summary>
        /// Run the command.
        /// </summary>
        /// <param name="options">Command options depend upon the command.</param>
        /// <returns>Process result code.</returns>
        int Run(object options);
    }
}


text: Javascript library that "extends" regexes to work with twitch emotes


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text, Badge } from 'native-base';

import styles from './styles';

const {
  replaceAt,
} = actions;

class NHListIcon extends Component {

  static propTypes = {
    replaceAt: React.PropTypes.func,
    navigation: React.PropTypes.shape({
      key: React.PropTypes.string,
    }),
  }

  replaceAt(route) {
    this.props.replaceAt('listIcon', { key: route }, this.props.navigation.key);
  }

  render() {
    return (
      <Container style={styles.container}>
        <Header>
          <Button transparent onPress={() => this.replaceAt('list')}>
            <Icon name="ios-arrow-back" />
          </Button>

          <Title>List Icon</Title>
        </Header>

        <Content>
          <List>
            <ListItem iconLeft>
              <Icon name="ios-plane" style={{ color: '#0A69FE' }} />
              <Text>Airplane Mode</Text>
              <Text note>Off</Text>
            </ListItem>
            <ListItem iconLeft>
              <Icon name="ios-wifi" style={{ color: '#0A69FE' }} />
              <Text>Wi-Fi</Text>
              <Text note>GeekyAnts</Text>
            </ListItem>
            <ListItem iconLeft>
              <Icon name="ios-bluetooth" style={{ color: '#0A69FE' }} />
              <Text>Bluetooth</Text>
              <Text note>Off</Text>
            </ListItem>
            <ListItem iconLeft>
              <Icon name="ios-settings-outline" style={{ color: '#0A69FE' }} />
              <Text>Software Update</Text>
              <Badge style={{ backgroundColor: '#8C97B5' }}>2</Badge>
            </ListItem>
            <ListItem iconLeft>
              <Icon name="ios-mail-outline" style={{ color: '#0A69FE' }} />
              <Text>Mail</Text>
              <Badge>12</Badge>
            </ListItem>
          </List>
        </Content>
      </Container>
    );
  }
}

function bindAction(dispatch) {
  return {
    replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
});

export default connect(mapStateToProps, bindAction)(NHListIcon);


text:
require 'optparse'

class Railsprof::CLI
  def self.start
    logger = Railsprof::Logger.new(STDOUT)
    logger.level = Logger::INFO
    options = {}

    opt_parser = OptionParser.new do |opts|
      opts.banner = 'Usage: railsprof [options] /path'

      opts.on('-h', '--help', 'Show this message') do
        puts opts.help
        exit
      end

      opts.on('--version', 'Show version') do
        puts "Version #{Railsprof::VERSION}"
        exit
      end

      opts.on('-v', '--verbose',
              'Run verbosely') do
        logger.level = options[:log_level] = Logger::DEBUG
      end

      opts.on('-e', '--environment ENV',
              'Environment (defaults to RAILS_ENV)') do |env|
        ENV['RAILS_ENV'] = env
      end

      opts.on('-q', '--query-param KEY=VAL',
              'Add query paramter (-q key=val {key: "val"}') do |q|
        options[:params] ||= {}
        key, val = q.split('=', 2)
        options[:params][key] = val
      end

      # TODO add session support
      # opts.on('-s', '--session KEY=VAL',
      #         'Session info (-s user=3 --> {user: 3})') do |s|
      #   options[:session] ||= {}
      #   key, val = s.split('=', 2)

      #   # parse session value in ruby if possible
      #   options[:session][key.to_sym] =
      #     begin
      #       eval val
      #     rescue NameError
      #       val
      #     end

      #   logger.debug "Added to session: {#{key.to_sym.inspect} => #{val.inspect}}"
      # end

      # TODO add cookie support
      # opts.on('-c', '--cookie KEY=VAL',
      #         'Add cookie (-c remember=all --> {:remember => "all"})') do |s|
      #   options[:cookies] ||= {}
      #   key, val = s.split('=', 2)

      #   options[:cookies][key.to_sym] = val

      #   logger.debug "Added to cookiejar: {#{key.to_sym.inspect} => #{val.inspect}}"
      # end

      # TODO add host support
      # opts.on('--host HOST',
      #         'Host for request (--host www.blah.com)') do |h|
      #   options[:host] = h
      # end

      # TODO add port support
      # opts.on('--port PORT',
      #         Integer,
      #         'Port for request (--port 3000)') do |p|
      #   options[:port] = p
      # end

      opts.on('-w', '--warmups N', Integer,
              'Number of warmup runs on stack, default ' +
              Railsprof::DEFAULT_OPTIONS[:warmups].to_s) do |w|
        options[:warmups] = w
      end

      opts.on('-n', '--num-runs N', Integer,
              'Number of runs in profiling mode, default ' +
              Railsprof::DEFAULT_OPTIONS[:runs].to_s) do |r|
        options[:runs] = r
      end

      opts.on('-t', '--threshold N', Float,
              'Threshold for file output in millis, default: ' +
              Railsprof::DEFAULT_OPTIONS[:threshold].to_s) do |t|
        options[:threshold] = t
      end

      opts.on('-d', '--directory DIR',
              'Local paths to profile, default: ' +
              Railsprof::DEFAULT_OPTIONS[:app_paths].join(', ')) do |d|
        options[:app_dirs] ||= []
        options[:app_dirs] << d
      end

      opts.on('-g', '--gem GEM',
              'Gems to profile, default: ' +
              Railsprof::DEFAULT_OPTIONS[:gems].join(', ')) do |d|
        options[:gems] ||= []
        options[:gems] << d
      end

      # for capturing args before '--'
      # opts.on do |h|
      #   puts "head: #{h.inspect}"
      # end

      # # for capturing args after '--'
      # opts.on_tail do |t|
      #   puts "tail: #{t.inspect}"
      # end

      opts.on_tail("-h", "--help", "Show this message") do
        puts opts
        exit
      end
    end

    args = opt_parser.parse!

    if args.empty?
      puts opt_parser.help
      exit
    end

    Railsprof::Profiler.new(args, options).profile!
  end
end


text:
@interface FLStatusBarViewController : FLViewController {
@private
    NSMutableArray* _stack;
}
- (void) setStatusView:(SDKView*) view
              animated:(BOOL) animated
              completion:(void (^)()) completion;

- (void) pushStatusView:(SDKView*) view
               animated:(BOOL) animated
               completion:(void (^)()) completion;

- (void) popStatusViewAnimated:(BOOL) animated
                    completion:(void (^)()) completion;

- (void) removeAllStatusViewsAnimated:(BOOL) animated
                           completion:(void (^)()) completion;
@end
#endif


text:
current_dir = File.dirname(__FILE__)
log_level                :info
log_location             STDOUT
node_name                "adeetikaushal"
client_key               "#{current_dir}/adeetikaushal.pem"
validation_client_name   "adeetiorg-validator"
validation_key           "#{current_dir}/adeetiorg-validator.pem"
chef_server_url          "https://api.opscode.com/organizations/adeetiorg"
cache_type               'BasicFile'
cache_options( :path => "#{ENV['HOME']}/.chef/checksums" )
cookbook_path            ["#{current_dir}/../cookbooks"]


text:
package com.amazonaws.services.devicefarm.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Represents a device pool compatibility result.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DevicePoolCompatibilityResult implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The device (phone or tablet) that you wish to return information about.
     *

     */
    private Device device;
    /**
     *

     * Whether the result was compatible with the device pool.
     *

     */
    private Boolean compatible;
    /**
     *

     * Information about the compatibility.
     *

     */
    private java.util.List<IncompatibilityMessage> incompatibilityMessages;

    /**
     *

     * The device (phone or tablet) that you wish to return information about.
     *

     *
     * @param device
     *        The device (phone or tablet) that you wish to return information about.
     */

    public void setDevice(Device device) {
        this.device = device;
    }

    /**
     *

     * The device (phone or tablet) that you wish to return information about.
     *

     *
     * @return The device (phone or tablet) that you wish to return information about.
     */

    public Device getDevice() {
        return this.device;
    }

    /**
     *

     * The device (phone or tablet) that you wish to return information about.
     *

     *
     * @param device
     *        The device (phone or tablet) that you wish to return information about.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DevicePoolCompatibilityResult withDevice(Device device) {
        setDevice(device);
        return this;
    }

    /**
     *

     * Whether the result was compatible with the device pool.
     *

     *
     * @param compatible
     *        Whether the result was compatible with the device pool.
     */

    public void setCompatible(Boolean compatible) {
        this.compatible = compatible;
    }

    /**
     *

     * Whether the result was compatible with the device pool.
     *

     *
     * @return Whether the result was compatible with the device pool.
     */

    public Boolean getCompatible() {
        return this.compatible;
    }

    /**
     *

     * Whether the result was compatible with the device pool.
     *

     *
     * @param compatible
     *        Whether the result was compatible with the device pool.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DevicePoolCompatibilityResult withCompatible(Boolean compatible) {
        setCompatible(compatible);
        return this;
    }

    /**
     *

     * Whether the result was compatible with the device pool.
     *

     *
     * @return Whether the result was compatible with the device pool.
     */

    public Boolean isCompatible() {
        return this.compatible;
    }

    /**
     *

     * Information about the compatibility.
     *

     *
     * @return Information about the compatibility.
     */

    public java.util.List<IncompatibilityMessage> getIncompatibilityMessages() {
        return incompatibilityMessages;
    }

    /**
     *

     * Information about the compatibility.
     *

     *
     * @param incompatibilityMessages
     *        Information about the compatibility.
     */

    public void setIncompatibilityMessages(java.util.Collection<IncompatibilityMessage> incompatibilityMessages) {
        if (incompatibilityMessages == null) {
            this.incompatibilityMessages = null;
            return;
        }

        this.incompatibilityMessages = new java.util.ArrayList<IncompatibilityMessage>(incompatibilityMessages);
    }

    /**
     *

     * Information about the compatibility.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setIncompatibilityMessages(java.util.Collection)} or
     * {@link #withIncompatibilityMessages(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param incompatibilityMessages
     *        Information about the compatibility.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DevicePoolCompatibilityResult withIncompatibilityMessages(IncompatibilityMessage... incompatibilityMessages) {
        if (this.incompatibilityMessages == null) {
            setIncompatibilityMessages(new java.util.ArrayList<IncompatibilityMessage>(incompatibilityMessages.length));
        }
        for (IncompatibilityMessage ele : incompatibilityMessages) {
            this.incompatibilityMessages.add(ele);
        }
        return this;
    }

    /**
     *

     * Information about the compatibility.
     *

     *
     * @param incompatibilityMessages
     *        Information about the compatibility.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DevicePoolCompatibilityResult withIncompatibilityMessages(java.util.Collection<IncompatibilityMessage> incompatibilityMessages) {
        setIncompatibilityMessages(incompatibilityMessages);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDevice() != null)
            sb.append("Device: ").append(getDevice()).append(",");
        if (getCompatible() != null)
            sb.append("Compatible: ").append(getCompatible()).append(",");
        if (getIncompatibilityMessages() != null)
            sb.append("IncompatibilityMessages: ").append(getIncompatibilityMessages());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DevicePoolCompatibilityResult == false)
            return false;
        DevicePoolCompatibilityResult other = (DevicePoolCompatibilityResult) obj;
        if (other.getDevice() == null ^ this.getDevice() == null)
            return false;
        if (other.getDevice() != null && other.getDevice().equals(this.getDevice()) == false)
            return false;
        if (other.getCompatible() == null ^ this.getCompatible() == null)
            return false;
        if (other.getCompatible() != null && other.getCompatible().equals(this.getCompatible()) == false)
            return false;
        if (other.getIncompatibilityMessages() == null ^ this.getIncompatibilityMessages() == null)
            return false;
        if (other.getIncompatibilityMessages() != null && other.getIncompatibilityMessages().equals(this.getIncompatibilityMessages()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDevice() == null) ? 0 : getDevice().hashCode());
        hashCode = prime * hashCode + ((getCompatible() == null) ? 0 : getCompatible().hashCode());
        hashCode = prime * hashCode + ((getIncompatibilityMessages() == null) ? 0 : getIncompatibilityMessages().hashCode());
        return hashCode;
    }

    @Override
    public DevicePoolCompatibilityResult clone() {
        try {
            return (DevicePoolCompatibilityResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.devicefarm.model.transform.DevicePoolCompatibilityResultMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
using namespace cv;
using namespace std;

static void help()
{
    cout <<
            "\nThis program demonstrates Laplace point/edge detection using OpenCV function Laplacian()\n"
            "It captures from the camera of your choice: 0, 1, ... default 0\n"
            "Call:\n"
            "./laplace -c=<camera #, default 0> -p=<index of the frame to be decoded/captured next>\n" << endl;
}

enum {GAUSSIAN, BLUR, MEDIAN};

int sigma = 3;
int smoothType = GAUSSIAN;

int main( int argc, char** argv )
{
    VideoCapture cap;
    cv::CommandLineParser parser(argc, argv, "{help h | | }{ c | 0 | }{ p | | }");
    if ( parser.has("help") )
    {
        help();
        return 0;
    }
    if( parser.get<string>("c").size() == 1 && isdigit(parser.get<string>("c")[0]) )
        cap.open(parser.get<int>("c"));
    else
        cap.open(parser.get<string>("c"));
    if( cap.isOpened() )
        cout << "Video " << parser.get<string>("c") <<
            ": width=" << cap.get(CAP_PROP_FRAME_WIDTH) <<
            ", height=" << cap.get(CAP_PROP_FRAME_HEIGHT) <<
            ", nframes=" << cap.get(CAP_PROP_FRAME_COUNT) << endl;
    if( parser.has("p") )
    {
        int pos = parser.get<int>("p");
        if (!parser.check())
        {
            parser.printErrors();
            return -1;
        }
        cout << "seeking to frame #" << pos << endl;
        cap.set(CAP_PROP_POS_FRAMES, pos);
    }

    if( !cap.isOpened() )
    {
        cout << "Could not initialize capturing...\n";
        return -1;
    }

    namedWindow( "Laplacian", 0 );
    createTrackbar( "Sigma", "Laplacian", &sigma, 15, 0 );

    Mat smoothed, laplace, result;

    for(;;)
    {
        Mat frame;
        cap >> frame;
        if( frame.empty() )
            break;

        int ksize = (sigma*5)|1;
        if(smoothType == GAUSSIAN)
            GaussianBlur(frame, smoothed, Size(ksize, ksize), sigma, sigma);
        else if(smoothType == BLUR)
            blur(frame, smoothed, Size(ksize, ksize));
        else
            medianBlur(frame, smoothed, ksize);

        Laplacian(smoothed, laplace, CV_16S, 5);
        convertScaleAbs(laplace, result, (sigma+1)*0.25);
        imshow("Laplacian", result);

        int c = waitKey(30);
        if( c == ' ' )
            smoothType = smoothType == GAUSSIAN ? BLUR : smoothType == BLUR ? MEDIAN : GAUSSIAN;
        if( c == 'q' || c == 'Q' || (c & 255) == 27 )
            break;
    }

    return 0;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="/lib/qunit.css">


text:
.class Lcom/zte/fingerprint/service/FPCServiceImpl$2;
.super Ljava/lang/Object;
.source "FPCServiceImpl.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/zte/fingerprint/service/FPCServiceImpl;->unregisterCallback(Lcom/android/fingerprints/keyguard/IFingerprintUnlockCallback;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/zte/fingerprint/service/FPCServiceImpl;

# direct methods
.method constructor <init>(Lcom/zte/fingerprint/service/FPCServiceImpl;)V
    .locals 0
    .param p1, "this$0"    # Lcom/zte/fingerprint/service/FPCServiceImpl;

    .prologue
    .line 78
    iput-object p1, p0, Lcom/zte/fingerprint/service/FPCServiceImpl$2;->this$0:Lcom/zte/fingerprint/service/FPCServiceImpl;

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

    return-void
.end method

# virtual methods
.method public run()V
    .locals 1

    .prologue
    .line 81
    iget-object v0, p0, Lcom/zte/fingerprint/service/FPCServiceImpl$2;->this$0:Lcom/zte/fingerprint/service/FPCServiceImpl;

    invoke-virtual {v0}, Lcom/zte/fingerprint/service/FPCServiceImpl;->releaseFingerprint()V

    .line 82
    return-void
.end method


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 394 (1923)

#### Original name
Graphis agminalis Nyl.

### Remarks
null


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" href="apple-touch-icon.png">

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans|Oswald|PT+Sans" rel="stylesheet">
    <link rel="stylesheet" href="css/main.css">

10/12/2017

CDMX

Videoconferencia

La mejor conferencia de
                    <spam>diseño web</spam>

                Conferencia
                Calendario
                Invitados
                Reservaciones

Registro de usuarios

    <form class="registro" id="registro" action="index.html" method="post">

          Nombre:
          <input type="text" name="nombre" id="nombre" value="tu nombre">

          Apellido:
          <input type="text" name="apellido" id="apellido" value="tu apellido">

          Email:
          <input type="email" name="email" id="email" value="tu email">

Elege nuestros paquetes

Pase por día (Viernes)

$30

Bocadillos Gratis

Todas las conferencias

Todos los talleres

                  Boletos deseados:
                  <input type="number" min="0" id="pase_di" size="3" placeholder="0">

Todos los días

$50

Bocadillos Gratis

Todas las conferencias

Todos los talleres

                  Boletos deseados:
                  <input type="number" min="0" id="pase_completo" size="3" placeholder="0">

Pase por 2 días (Viernes y Sábado)

$45

Bocadillos Gratis

Todas las conferencias

Todos los talleres

                  Boletos deseados:
                  <input type="number" min="0" id="pase_dosdias" size="3" placeholder="0">

Elige tus talleres

Viernes

Talleres:

                               <input type="checkbox" name="registro[]" id="taller_01" value="taller_01"><time>10:00</time> Responsive Web Design
                               <input type="checkbox" name="registro[]" id="taller_02" value="taller_02"><time>12:00</time> Flexbox
                               <input type="checkbox" name="registro[]" id="taller_03" value="taller_03"><time>14:00</time> HTML5 y CSS3
                               <input type="checkbox" name="registro[]" id="taller_04" value="taller_04"><time>17:00</time> Drupal
                               <input type="checkbox" name="registro[]" id="taller_05" value="taller_05"><time>19:00</time> WordPress

Conferencias:

                               <input type="checkbox" name="registro[]" id="conf_01" value="conf_01"><time>10:00</time> Como ser Freelancer
                               <input type="checkbox" name="registro[]" id="conf_02" value="conf_02"><time>17:00</time> Tecnologías del Futuro
                               <input type="checkbox" name="registro[]" id="conf_03" value="conf_03"><time>19:00</time> Seguridad en la Web

Seminarios:

                               <input type="checkbox" name="registro[]" id="sem_01" value="sem_01"><time>10:00</time> Diseño UI y UX para móviles

Sábado

Talleres:

                             <input type="checkbox" name="registro[]" id="taller_06" value="taller_06"><time>10:00</time> AngularJS
                             <input type="checkbox" name="registro[]" id="taller_07" value="taller_07"><time>12:00</time> PHP y MySQL
                             <input type="checkbox" name="registro[]" id="taller_08" value="taller_08"><time>14:00</time> JavaScript Avanzado
                             <input type="checkbox" name="registro[]" id="taller_09" value="taller_09"><time>17:00</time> SEO en Google
                             <input type="checkbox" name="registro[]" id="taller_10" value="taller_10"><time>19:00</time> De Photoshop a HTML5 y CSS3
                             <input type="checkbox" name="registro[]" id="taller_11" value="taller_11"><time>21:00</time> PHP Medio y Avanzado

Conferencias:

                             <input type="checkbox" name="registro[]" id="conf_04" value="conf_04"><time>10:00</time> Como crear una tienda online que venda millones en pocos días
                             <input type="checkbox" name="registro[]" id="conf_05" value="conf_05"><time>17:00</time> Los mejores lugares para encontrar trabajo
                             <input type="checkbox" name="registro[]" id="conf_06" value="conf_06"><time>19:00</time> Pasos para crear un negocio rentable

Seminarios:

                             <input type="checkbox" name="registro[]" id="sem_02" value="sem_02"><time>10:00</time> Aprende a Programar en una mañana
                             <input type="checkbox" name="registro[]" id="sem_03" value="sem_03"><time>17:00</time> Diseño UI y UX para móviles

Domingo

Talleres:

                             <input type="checkbox" name="registro[]" id="taller_12" value="taller_12"><time>10:00</time> Laravel
                             <input type="checkbox" name="registro[]" id="taller_13" value="taller_13"><time>12:00</time> Crea tu propia API
                             <input type="checkbox" name="registro[]" id="taller_14" value="taller_14"><time>14:00</time> JavaScript y jQuery
                             <input type="checkbox" name="registro[]" id="taller_15" value="taller_15"><time>17:00</time> Creando Plantillas para WordPress
                             <input type="checkbox" name="registro[]" id="taller_16" value="taller_16"><time>19:00</time> Tiendas Virtuales en Magento

Conferencias:

                             <input type="checkbox" name="registro[]" id="conf_07" value="conf_07"><time>10:00</time> Como hacer Marketing en línea
                             <input type="checkbox" name="registro[]" id="conf_08" value="conf_08"><time>17:00</time> ¿Con que lenguaje debo empezar?
                             <input type="checkbox" name="registro[]" id="conf_09" value="conf_09"><time>19:00</time> Frameworks y librerias Open Source

Seminarios:

                             <input type="checkbox" name="registro[]" id="sem_04" value="sem_04"><time>14:00</time> Creando una App en Android en una tarde
                             <input type="checkbox" name="registro[]" id="sem_05" value="sem_05"><time>17:00</time> Creando una App en iOS en una tarde

Pago y extras

                 Camisa del evento $10 (promocion 7% dto.)
                 <input type="number" min="0" name="" value="" id="camisa_evento" size="3" placeholder="0">

                 Paquete de 10 eriquetas $2 (HTMl5 CSS3 Javascript)
                 <input type="number" min="0" name="" value="" id="etiquetas" size="3" placeholder="0">

                 Seleccione un regalo
                 <select id="regalo" required class="" name="">
                   <option value="">- Seleccione un regalo</option>
                   <option value="ETI">Etiquetas</option>
                   <option value="PUL">Pulsera</option>
                   <option value="Plumas">Plumas</option>
                 </select>
                 <input type="button" name="Calcular" value="Calcular" id="calcular" class="button">

Resumen

total:

                    <input type="submit" name="" value="Pagar" class="button">

    </form>

Sobre GDLWEBCAMP

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Últimos Tweets

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Redes Sociales

Todos los derechos reservados GDLWEBCAMP


text:
+++
Title = "Edson Celio"
Twitter = "tuxpilgrim"
linkedin = "https://www.linkedin.com/in/edsoncelio/"
website = "https://edsoncelio.github.io/"
image = "edson-celio.jpg"
type = "speaker"
linktitle = "edson-celio"

+++

Atualmente programador de sistemas [embarcados] na Grendene S/A e graduando em Engenharia da Computação pela UFC. Também envolvido em projeto de Governança da Internet, já sendo bolsista do CGIbr, ISOC e LACNIC. Entusiasta da cultura DevOps e busca difundir cada vez mais a cultura no ambiente de trabalho e no mercado de tecnologia local.


text:
using Microsoft.Azure.Management.Security;
using Microsoft.Azure.Management.Security.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using SecurityCenter.Tests.Helpers;
using System.Net;
using Xunit;

namespace Microsoft.Azure.Management.SecurityCenter.Tests.SecureScores
{
    public class SecureScoreControlTests : TestBase
    {
        #region Test setup
        private static readonly string AscLocation = "centralus";
        private static TestEnvironment TestEnvironment { get; set; }
        #endregion

        private static SecurityCenterClient GetSecurityCenterClient(MockContext context)
        {
            if (TestEnvironment == null && HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                TestEnvironment = TestEnvironmentFactory.GetTestEnvironment();
            }

            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK, IsPassThrough = true };

            var securityCenterClient = HttpMockServer.Mode == HttpRecorderMode.Record
                ? context.GetServiceClient<SecurityCenterClient>(TestEnvironment, handlers: handler)
                : context.GetServiceClient<SecurityCenterClient>(handlers: handler);

            securityCenterClient.AscLocation = AscLocation;

            return securityCenterClient;
        }

        #region Tests
        [Fact]
        public void SecureScoreControls_ListAll()
        {
            using (var context = MockContext.Start(GetType()))
            {
                var securityCenterClient = GetSecurityCenterClient(context);
                var ret = securityCenterClient.SecureScoreControls.List(expand: "definitions");
                ValidateSecureScoreControlsList(ret, false);
            }
        }

        [Fact]
        public void SecureScoreControls_ListAllWithDefinitions()
        {
            using (var context = MockContext.Start(GetType()))
            {
                var securityCenterClient = GetSecurityCenterClient(context);
                var ret = securityCenterClient.SecureScoreControls.List(expand: "definition");
                ValidateSecureScoreControlsList(ret, true);
            }
        }

        [Fact]
        public void SecureScores_Get()
        {
            using (var context = MockContext.Start(GetType()))
            {
                var securityCenterClient = GetSecurityCenterClient(context);
                var ret = securityCenterClient.SecureScoreControls.ListBySecureScore("ascScore");
                ValidateSecureScoreControlsList(ret, false);
            }
        }

        [Fact]
        public void SecureScores_Get_Unknown()
        {
            using (var context = MockContext.Start(GetType()))
            {
                var securityCenterClient = GetSecurityCenterClient(context);
                var a = securityCenterClient.SecureScoreControls.ListBySecureScore("unknown");
                Assert.Empty(a);
            }
        }
        #endregion

        #region Validations
        private static void ValidateSecureScoreControlsList(IPage<SecureScoreControlDetails> ret, bool expectedMetadata)
        {
            Assert.True(ret.IsAny(), "Got empty list");
            foreach (var item in ret)
            {
                ValidateSecureScoreControlItem(item, expectedMetadata);
            }
        }

        private static void ValidateSecureScoreControlItem(SecureScoreControlDetails item, bool expectedMetadata)
        {
            Assert.NotNull(item);
            Assert.NotNull(item.DisplayName);
            Assert.NotNull(item.Id);
            Assert.NotNull(item.Type);
            Assert.NotNull(item.Current);
            Assert.NotNull(item.Max);
            Assert.NotNull(item.Weight);
            Assert.NotNull(item.Percentage);
            Assert.Equal(expectedMetadata, item.Definition != null);
            Assert.True(item.Max >= 0);
            Assert.Equal("Microsoft.Security/secureScores/secureScoreControls", item.Type);
            Assert.True(item.Current >= 0.00 && item.Current <= item.Max);
            Assert.True(item.Weight >= 0);
            Assert.True(item.Percentage >= 0.00 && item.Percentage <= 1.00);
        }
        #endregion
    }
}


text:
package postgres

import (
	"database/sql"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/dairycart/dairycart/storage/v1/database/postgres/migrations"

	"github.com/mattes/migrate"
	_ "github.com/mattes/migrate/database/postgres"
	"github.com/mattes/migrate/source/go-bindata"
	"github.com/spf13/viper"
)

const (
	maxConnectionAttempts = 5

	migrateExampleDataKey = "migrate_example_data"
	databaseConnectionKey = "connection_details"
)

func loadMigrationData(dbURL string, loadExampleData bool) (*migrate.Migrate, error) {
	s := bindata.Resource(migrations.AssetNames(), func(name string) ([]byte, error) {
		if strings.Contains(name, "example_data") && loadExampleData {
			return migrations.Asset(name)
		} else if strings.Contains(name, "example_data") && !loadExampleData {
			return nil, nil
		}
		return migrations.Asset(name)
	})

	d, err := bindata.WithInstance(s)
	if err != nil {
		return nil, err
	}

	return migrate.NewWithSourceInstance("go-bindata", d, dbURL)
}

func prepareForMigration(db *sql.DB, dbURL string, loadExampleData bool) (*migrate.Migrate, error) {
	err := databaseIsAvailable(db)
	if err != nil {
		return nil, err
	}

	return loadMigrationData(dbURL, loadExampleData)
}

func databaseIsAvailable(db *sql.DB) error {
	numberOfUnsuccessfulAttempts := 0
	databaseIsNotMigrated := true
	for databaseIsNotMigrated {
		err := db.Ping()
		if err != nil {
			log.Printf("ping failed, waiting half a second for the database")
			time.Sleep(1 * time.Second)
			numberOfUnsuccessfulAttempts++
			if numberOfUnsuccessfulAttempts == maxConnectionAttempts {
				return fmt.Errorf("failed to connect to the database: %v\n", err)
			}
		} else {
			break
		}
	}
	return nil
}

func (pg *postgres) Migrate(db *sql.DB, cfg *viper.Viper) error {
	dbURL := cfg.GetString(databaseConnectionKey)
	loadExampleData := cfg.GetBool(migrateExampleDataKey)

	m, err := prepareForMigration(db, dbURL, loadExampleData)
	if err != nil {
		return err
	}

	err = m.Up()
	if err == migrate.ErrNoChange {
		return nil
	}
	return err
}

func (pg *postgres) Downgrade(db *sql.DB, cfg *viper.Viper) error {
	dbURL := cfg.GetString(databaseConnectionKey)
	loadExampleData := cfg.GetBool(migrateExampleDataKey)

	m, err := prepareForMigration(db, dbURL, loadExampleData)
	if err != nil {
		return err
	}

	err = m.Down()
	if err == migrate.ErrNoChange {
		return nil
	}
	return err
}


text:
import Control.Monad
import qualified Data.Vector as V
import Data.Char
import Data.Bits

-- isPowerOfTwo n = if popCount n == 1 && testBit (complement n) 0 then 1 else 0
isPowerOfTwo n = 0

strength v
    | V.length v == 0 = 0
    | V.head v == '0' = 0
    | otherwise = fullStrength
        where
        -- TODO: no need to fold, just convert int to string
            fullStrength = V.foldl' (\acc c -> acc * 10 + digitToInt c) 0 v

countPowers v (i, j) = strength s
    where
        s = V.slice i (j - i + 1) v

-- TODO: use the fact that max strength is the slice number itself

twotwo s = [countPowers v (i, j) | i <- [0..len - 1], j <- [i..len - 1], 4 * (j - i + 1) < 800]
    where
        v = V.fromList s
        len = length v

main :: IO ()
main = do
    n <- readLn :: IO Int
    testCases <- replicateM n getLine
    -- print testCases
    let ans = map twotwo testCases
    -- print ans
    mapM_ (print . sum) ans


text:
<?php

/**
 * @file
 * Contains \Drupal\ckeditor\CKEditorPluginContextualInterface.
 */

namespace Drupal\ckeditor;

use Drupal\editor\Plugin\Core\Entity\Editor;

/**
 * Defines an interface for contextually enabled CKEditor plugins.
 *
 * Contextually enabled CKEditor plugins can be enabled via an explicit setting,
 * or enable themselves based on the configuration of another setting, such as
 * enabling based on a particular button being present in the toolbar.
 *
 * If a contextually enabled CKEditor plugin must also be configurable (e.g. in
 * the case where it must be enabled based on an explicit setting), then one
 * must also implement the CKEditorPluginConfigurableInterface interface.
 *
 * @see CKEditorPluginConfigurableInterface
 */
interface CKEditorPluginContextualInterface extends CKEditorPluginInterface {

  /**
   * Checks if this plugin should be enabled based on the editor configuration.
   *
   * The editor's settings can be found in $editor->settings.
   *
   * @param \Drupal\editor\Plugin\Core\Entity\Editor $editor
   *   A configured text editor object.
   *
   * @return bool
   */
  public function isEnabled(Editor $editor);

}


text:
package com.cezarykluczynski.stapi.etl.series.creation.configuration;

import com.cezarykluczynski.stapi.etl.configuration.job.service.StepCompletenessDecider;
import com.cezarykluczynski.stapi.etl.series.creation.processor.SeriesReader;
import com.cezarykluczynski.stapi.etl.util.SortingUtil;
import com.cezarykluczynski.stapi.etl.util.constant.CategoryTitle;
import com.cezarykluczynski.stapi.etl.util.constant.JobName;
import com.cezarykluczynski.stapi.etl.util.constant.StepName;
import com.cezarykluczynski.stapi.sources.mediawiki.api.CategoryApi;
import com.cezarykluczynski.stapi.sources.mediawiki.api.enums.MediaWikiSource;
import com.cezarykluczynski.stapi.sources.mediawiki.dto.PageHeader;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.inject.Inject;
import java.util.List;

@Configuration
public class SeriesCreationConfiguration {

	@Inject
	private CategoryApi categoryApi;

	@Inject
	private StepCompletenessDecider stepCompletenessDecider;

	@Bean
	@DependsOn("batchDatabaseInitializer")
	public SeriesReader seriesReader() {
		List<PageHeader> pageHeaderList = Lists.newArrayList();

		if (!stepCompletenessDecider.isStepComplete(JobName.JOB_CREATE, StepName.CREATE_SERIES)) {
			pageHeaderList.addAll(categoryApi.getPages(CategoryTitle.STAR_TREK_SERIES, MediaWikiSource.MEMORY_ALPHA_EN));
		}

		return new SeriesReader(SortingUtil.sortedUnique(pageHeaderList));
	}

}


text:
describe RuboCop::Cop::Style::BracesAroundHashParameters, :config do
  subject(:cop) { described_class.new(config) }

  shared_examples 'general non-offenses' do
    after { expect(cop.offenses).to be_empty }

    it 'accepts one non-hash parameter' do
      inspect_source('where(2)')
    end

    it 'accepts multiple non-hash parameters' do
      inspect_source('where(1, "2")')
    end

    it 'accepts one empty hash parameter' do
      inspect_source('where({})')
    end

    it 'accepts one empty hash parameter with whitespace' do
      inspect_source(['where(  {     ',
                      " }\t   )  "])
    end
  end

  shared_examples 'no_braces and context_dependent non-offenses' do
    after { expect(cop.offenses).to be_empty }

    it 'accepts one hash parameter without braces' do
      inspect_source('where(x: "y")')
    end

    it 'accepts one hash parameter without braces and with multiple keys' do
      inspect_source('where(x: "y", foo: "bar")')
    end

    it 'accepts one hash parameter without braces and with one hash value' do
      inspect_source('where(x: { "y" => "z" })')
    end

    it 'accepts property assignment with braces' do
      inspect_source('x.z = { y: "z" }')
    end

    it 'accepts operator with a hash parameter with braces' do
      inspect_source('x.z - { y: "z" }')
    end
  end

  shared_examples 'no_braces and context_dependent offenses' do
    let(:msg) { 'Redundant curly braces around a hash parameter.' }

    it 'registers an offense for one non-hash parameter followed by a hash ' \
       'parameter with braces' do
      inspect_source('where(1, { y: 2 })')
      expect(cop.messages).to eq([msg])
      expect(cop.highlights).to eq(['{ y: 2 }'])
    end

    it 'registers an offense for one object method hash parameter with ' \
       'braces' do
      inspect_source('x.func({ y: "z" })')
      expect(cop.messages).to eq([msg])
      expect(cop.highlights).to eq(['{ y: "z" }'])
    end

    it 'registers an offense for one hash parameter with braces' do
      inspect_source('where({ x: 1 })')
      expect(cop.messages).to eq([msg])
      expect(cop.highlights).to eq(['{ x: 1 }'])
    end

    it 'registers an offense for one hash parameter with braces and ' \
       'whitespace' do
      inspect_source("where(  \n { x: 1 }   )")
      expect(cop.messages).to eq([msg])
      expect(cop.highlights).to eq(['{ x: 1 }'])
    end

    it 'registers an offense for one hash parameter with braces and multiple ' \
       'keys' do
      inspect_source('where({ x: 1, foo: "bar" })')
      expect(cop.messages).to eq([msg])
      expect(cop.highlights).to eq(['{ x: 1, foo: "bar" }'])
    end
  end

  shared_examples 'no_braces and context_dependent auto-corrections' do
    it 'corrects one non-hash parameter followed by a hash parameter with ' \
       'braces' do
      corrected = autocorrect_source(['where(1, { y: 2 })'])
      expect(corrected).to eq('where(1, y: 2)')
    end

    it 'corrects one object method hash parameter with braces' do
      corrected = autocorrect_source(['x.func({ y: "z" })'])
      expect(corrected).to eq('x.func(y: "z")')
    end

    it 'corrects one hash parameter with braces' do
      corrected = autocorrect_source(['where({ x: 1 })'])
      expect(corrected).to eq('where(x: 1)')
    end

    it 'corrects one hash parameter with braces and whitespace' do
      corrected = autocorrect_source(['where(  ',
                                      ' { x: 1 }   )'])
      expect(corrected).to eq(['where(  ',
                               ' x: 1   )'].join("\n"))
    end

    it 'corrects one hash parameter with braces and multiple keys' do
      corrected = autocorrect_source(['where({ x: 1, foo: "bar" })'])
      expect(corrected).to eq('where(x: 1, foo: "bar")')
    end

    it 'corrects one hash parameter with braces and extra leading whitespace' do
      corrected = autocorrect_source(['where({   x: 1, y: 2 })'])
      expect(corrected).to eq('where(x: 1, y: 2)')
    end

    it 'corrects one hash parameter with braces and extra trailing ' \
       'whitespace' do
      corrected = autocorrect_source(['where({ x: 1, y: 2   })'])
      expect(corrected).to eq('where(x: 1, y: 2)')
    end

    it 'corrects one hash parameter with braces and a trailing comma' do
      corrected = autocorrect_source(['where({ x: 1, y: 2, })'])
      expect(corrected).to eq('where(x: 1, y: 2)')
    end

    it 'corrects one hash parameter with braces and trailing comma and ' \
       'whitespace' do
      corrected = autocorrect_source(['where({ x: 1, y: 2,   })'])
      expect(corrected).to eq('where(x: 1, y: 2)')
    end

    it 'corrects one hash parameter with braces without adding extra space' do
      corrected = autocorrect_source('get :i, { q: { x: 1 } }')
      expect(corrected).to eq('get :i, q: { x: 1 }')
    end

    context 'with a comment following the last key-value pair' do
      it 'corrects and leaves line breaks' do
        src = <<-RUBY.strip_indent
          r = opts.merge({
            p1: opts[:a],
            p2: (opts[:b] || opts[:c]) # a comment
          })
        RUBY
        corrected = autocorrect_source(src)
        expect(corrected).to eq(<<-RUBY.strip_indent)
          r = opts.merge(
            p1: opts[:a],
            p2: (opts[:b] || opts[:c]) # a comment
          )
        RUBY
      end
    end

    context 'in a method call without parentheses' do
      it 'corrects a hash parameter with trailing comma' do
        src = 'get :i, { x: 1, }'
        corrected = autocorrect_source(src)
        expect(corrected).to eq('get :i, x: 1')
      end
    end
  end

  context 'when EnforcedStyle is no_braces' do
    let(:cop_config) { { 'EnforcedStyle' => 'no_braces' } }

    context 'for correct code' do
      include_examples 'general non-offenses'
      include_examples 'no_braces and context_dependent non-offenses'
    end

    context 'for incorrect code' do
      include_examples 'no_braces and context_dependent offenses'

      after do
        expect(cop.messages)
          .to eq(['Redundant curly braces around a hash parameter.'])
      end

      it 'registers an offense for two hash parameters with braces' do
        expect_offense(<<-RUBY.strip_indent)
          where({ x: 1 }, { y: 2 })
                          ^^^^^^^^ Redundant curly braces around a hash parameter.
        RUBY
      end
    end

    describe '#autocorrect' do
      include_examples 'no_braces and context_dependent auto-corrections'

      it 'corrects one hash parameter with braces' do
        corrected = autocorrect_source(['where(1, { x: 1 })'])
        expect(corrected).to eq('where(1, x: 1)')
      end

      it 'corrects two hash parameters with braces' do
        corrected = autocorrect_source(['where(1, { x: 1 }, { y: 2 })'])
        expect(corrected).to eq('where(1, { x: 1 }, y: 2)')
      end
    end
  end

  context 'when EnforcedStyle is context_dependent' do
    let(:cop_config) { { 'EnforcedStyle' => 'context_dependent' } }

    context 'for correct code' do
      include_examples 'general non-offenses'
      include_examples 'no_braces and context_dependent non-offenses'

      it 'accepts two hash parameters with braces' do
        expect_no_offenses('where({ x: 1 }, { y: 2 })')
      end
    end

    context 'for incorrect code' do
      include_examples 'no_braces and context_dependent offenses'

      it 'registers an offense for one hash parameter with braces and one ' \
         'without' do
        inspect_source('where({ x: 1 }, y: 2)')
        expect(cop.messages)
          .to eq(['Missing curly braces around a hash parameter.'])
        expect(cop.highlights).to eq(['y: 2'])
      end
    end

    describe '#autocorrect' do
      include_examples 'no_braces and context_dependent auto-corrections'

      it 'corrects one hash parameter with braces and one without' do
        corrected = autocorrect_source(['where(1, { x: 1 }, y: 2)'])
        expect(corrected).to eq('where(1, { x: 1 }, {y: 2})')
      end

      it 'corrects one hash parameter with braces' do
        corrected = autocorrect_source(['where(1, { x: 1 })'])
        expect(corrected).to eq('where(1, x: 1)')
      end
    end
  end

  context 'when EnforcedStyle is braces' do
    let(:cop_config) { { 'EnforcedStyle' => 'braces' } }

    context 'for correct code' do
      include_examples 'general non-offenses'

      after { expect(cop.offenses).to be_empty }

      it 'accepts one hash parameter with braces' do
        expect_no_offenses('where({ x: 1 })')
      end

      it 'accepts multiple hash parameters with braces' do
        expect_no_offenses('where({ x: 1 }, { y: 2 })')
      end

      it 'accepts one hash parameter with braces and whitespace' do
        expect_no_offenses(<<-RUBY.strip_indent)
          where( 	    {  x: 1
            }   )
        RUBY
      end
    end

    context 'for incorrect code' do
      after do
        expect(cop.messages)
          .to eq(['Missing curly braces around a hash parameter.'])
      end

      it 'registers an offense for one hash parameter without braces' do
        expect_offense(<<-RUBY.strip_indent)
          where(x: "y")
                ^^^^^^ Missing curly braces around a hash parameter.
        RUBY
      end

      it 'registers an offense for one hash parameter with multiple keys and ' \
         'without braces' do
        inspect_source('where(x: "y", foo: "bar")')
        expect(cop.highlights).to eq(['x: "y", foo: "bar"'])
      end

      it 'registers an offense for one hash parameter without braces with ' \
         'one hash value' do
        inspect_source('where(x: { "y" => "z" })')
        expect(cop.highlights).to eq(['x: { "y" => "z" }'])
      end
    end

    describe '#autocorrect' do
      it 'corrects one hash parameter without braces' do
        corrected = autocorrect_source(['where(x: "y")'])
        expect(corrected).to eq('where({x: "y"})')
      end

      it 'corrects one hash parameter with multiple keys and without braces' do
        corrected = autocorrect_source(['where(x: "y", foo: "bar")'])
        expect(corrected).to eq('where({x: "y", foo: "bar"})')
      end

      it 'corrects one hash parameter without braces with one hash value' do
        corrected = autocorrect_source(['where(x: { "y" => "z" })'])
        expect(corrected).to eq('where({x: { "y" => "z" }})')
      end
    end
  end
end


text:
<?php declare(strict_types = 1);

namespace DrdPlus\Tables\Partials\Exceptions;

class RequiredRowNotFound extends RequiredDataNotFound
{

}


text:
<?php

use Symfony\Component\HttpFoundation\Request;

require __DIR__.'/../vendor/autoload.php';
if (PHP_VERSION_ID < 70000) {
    include_once __DIR__.'/../var/bootstrap.php.cache';
}

$kernel = new AppKernel('prod', false);
if (PHP_VERSION_ID < 70000) {
    $kernel->loadClassCache();
}
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
Request::setTrustedProxies([$request->server->get('REMOTE_ADDR')]);
Request::setTrustedHeaderName(Request::HEADER_FORWARDED, null);
Request::setTrustedHeaderName(Request::HEADER_X_FORWARDED_HOST, null);
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);


text:
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP

#include <realm/column.hpp>
#include <realm/timestamp.hpp>

namespace realm {

// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple {
public:
    TimestampColumn(bool nullable, Allocator& alloc, ref_type ref, size_t col_ndx = npos);

    static ref_type create(Allocator& alloc, size_t size, bool nullable);
    static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept;

    /// Get the number of entries in this column. This operation is relatively
    /// slow.
    size_t size() const noexcept override;
    /// Whether or not this column is nullable.
    bool is_nullable() const noexcept override;
    /// Whether or not the value at \a row_ndx is NULL. If the column is not
    /// nullable, always returns false.
    bool is_null(size_t row_ndx) const noexcept override;
    /// Sets the value at \a row_ndx to be NULL.
    /// \throw LogicError Thrown if this column is not nullable.
    void set_null(size_t row_ndx) override;
    void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
    void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
                    bool broken_reciprocal_backlinks) override;
    void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) override;
    void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
    void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
    void destroy() noexcept override;

    bool has_search_index() const noexcept final
    {
        return bool(m_search_index);
    }
    StringIndex* get_search_index() noexcept final
    {
        return m_search_index.get();
    }
    StringIndex* get_search_index() const noexcept final
    {
        return m_search_index.get();
    }
    void destroy_search_index() noexcept override;
    void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
                              bool allow_duplicate_values) final;
    void populate_search_index();
    StringIndex* create_search_index() override;
    bool supports_search_index() const noexcept final
    {
        return true;
    }

    StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
    ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
    void update_from_parent(size_t old_baseline) noexcept override;
    void set_ndx_in_parent(size_t ndx) noexcept override;
    void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;

    void verify() const override;
    void to_dot(std::ostream&, StringData title = StringData()) const override;
    void do_dump_node_structure(std::ostream&, int level) const override;
    void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;

    void add(const Timestamp& ts = Timestamp{});
    Timestamp get(size_t row_ndx) const noexcept;
    void set(size_t row_ndx, const Timestamp& ts);
    bool compare(const TimestampColumn& c) const noexcept;
    int compare_values(size_t row1, size_t row2) const noexcept override;

    Timestamp maximum(size_t* result_index) const;
    Timestamp minimum(size_t* result_index) const;
    size_t count(Timestamp) const;
    void erase(size_t row_ndx, bool is_last);

    template <class Condition>
    size_t find(Timestamp value, size_t begin, size_t end) const noexcept
    {
        // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match
        // check nanoseconds, etc. Lots of possibilities. Below code is naive and slow but works.

        Condition cond;
        for (size_t t = begin; t < end; t++) {
            Timestamp ts = get(t);
            if (cond(ts, value, ts.is_null(), value.is_null()))
                return t;
        }
        return npos;
    }

    typedef Timestamp value_type;

private:
    std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
    std::unique_ptr<BpTree<int64_t>> m_nanoseconds;

    std::unique_ptr<StringIndex> m_search_index;
    bool m_nullable;

    template <class BT>
    class CreateHandler;

    template <class Condition>
    Timestamp minmax(size_t* result_index) const noexcept
    {
        // Condition is realm::Greater for maximum and realm::Less for minimum.

        if (size() == 0) {
            if (result_index)
                *result_index = npos;
            return Timestamp{};
        }

        Timestamp best = get(0);
        size_t best_index = 0;

        for (size_t i = 1; i < size(); ++i) {
            Timestamp candidate = get(i);
            if (Condition()(candidate, best, candidate.is_null(), best.is_null())) {
                best = candidate;
                best_index = i;
            }
        }
        if (result_index)
            *result_index = best_index;
        return best;
    }
};

} // namespace realm

#endif // REALM_COLUMN_TIMESTAMP_HPP


text:
package com.triangleleft.flashcards.service.vocabular;

import com.google.auto.value.AutoValue;
import com.triangleleft.service.vocabular.VocabularyWordTranslationModel;

@AutoValue
public abstract class VocabularWordTranslationDao implements VocabularyWordTranslationModel {

    public static final Factory<VocabularWordTranslationDao> FACTORY =
            new Factory<>(AutoValue_VocabularWordTranslationDao::new);

}


text:
package org.dynmap.markers.impl;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.dynmap.ConfigurationNode;
import org.dynmap.markers.MarkerIcon;

class MarkerIconImpl implements MarkerIcon {
    private String iconid;
    private String label;
    private boolean is_builtin;
    private MarkerSize size = MarkerSize.MARKER_16x16;

    MarkerIconImpl(String id) {
        iconid = id;
        label = id;
        is_builtin = false;
    }

    MarkerIconImpl(String id, String lbl, boolean is_builtin) {
        iconid = id;
        if(lbl != null)
            label = lbl;
        else
            label = id;
        this.is_builtin = is_builtin;
    }

    void cleanup() {

    }

    @Override
    public String getMarkerIconID() {
        return iconid;
    }

    @Override
    public String getMarkerIconLabel() {
        return label;
    }

    @Override
    public void setMarkerIconLabel(String lbl) {
        if(lbl == null) lbl = iconid;
        if(label.equals(lbl) == false) {
            label = lbl;
            MarkerAPIImpl.saveMarkers();
        }
    }

    @Override
    public void setMarkerIconImage(InputStream in) {
        if(MarkerAPIImpl.api.loadMarkerIconStream(this.iconid, in))
            MarkerAPIImpl.api.publishMarkerIcon(this);
    }

    @Override
    public void deleteIcon() {
        MarkerAPIImpl.removeIcon(this);
    }

    @Override
    public boolean isBuiltIn() {
        return is_builtin;
    }

    /**
     * Get configuration node to be saved
     * @return node
     */
    Map<String, Object> getPersistentData() {
        if(is_builtin)
            return null;

        HashMap<String, Object> node = new HashMap<String, Object>();
        node.put("label", label);

        return node;
    }

    boolean loadPersistentData(ConfigurationNode node) {
        if(is_builtin)
            return false;

        label = node.getString("label", iconid);

        return true;
    }

    @Override
    public MarkerSize getMarkerIconSize() {
        return size;
    }

    void setMarkerIconSize(MarkerSize sz) {
        size = sz;
    }
}


text:
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE.md) [![Haxelib Version](https://img.shields.io/github/tag/openfl/lime.svg?style=flat&label=haxelib)](http://lib.haxe.org/p/lime) [![Build Status](https://img.shields.io/github/workflow/status/openfl/lime/CI/develop)](https://github.com/openfl/lime/actions) [![Community](https://img.shields.io/discourse/posts?color=24afc4&server=https%3A%2F%2Fcommunity.openfl.org&label=community)](https://community.openfl.org/c/lime/19) [![Discord Server](https://img.shields.io/discord/415681294446493696.svg?color=7289da)](https://discordapp.com/invite/tDgq8EE)

Lime
====

Lime is a flexible, lightweight layer for Haxe cross-platform developers.

Lime supports native, Flash and HTML5 targets with unified support for:

 * Windowing
 * Input
 * Events
 * Audio
 * Render contexts
 * Network access
 * Assets

Lime does not include a renderer, but exposes the current context:

 * Cairo
 * Canvas
 * DOM
 * Flash
 * GL

The GL context is based upon the WebGL standard, implemented for both OpenGL and OpenGL ES as needed.

Lime provides a unified audio API, but also provides access to OpenAL for advanced audio on native targets.

License
=======

Lime is free, open-source software under the [MIT license](LICENSE.md).

Installation
============

First install the latest version of [Haxe](http://www.haxe.org/download).

Development Builds
==================

When there are changes, Lime is built nightly. Builds are available for download [here](https://github.com/openfl/lime/actions?query=branch%3Adevelop+is%3Asuccess).

To install a development build, use the "haxelib local" command:

    haxelib local lime-haxelib.zip

Building from Source
====================

Clone the Lime repository, as well as the submodules:

    git clone --recursive https://github.com/openfl/lime

Tell haxelib where your development copy of Lime is installed:

    haxelib dev lime lime

The first time you run the "lime" command, it will attempt to build the Lime standard binary for your desktop platform as the command-line tools. To build these manually, use the following command (using "mac" or "linux" if appropriate):

    haxelib install format
    haxelib install hxp
    lime rebuild windows

You can build additional binaries, or rebuild binaries after making changes, using "lime rebuild":

    lime rebuild windows
    lime rebuild linux -64 -release -clean

You can also rebuild the tools if you make changes to them:

    lime rebuild tools

On a Windows machine, you should have Microsoft Visual Studio C++ (Express is just fine) installed. You will need Xcode on a Mac. To build on a Linux machine, you may need the following packages (or similar):

    sudo apt-get install libgl1-mesa-dev libglu1-mesa-dev g++ g++-multilib gcc-multilib libasound2-dev libx11-dev libxext-dev libxi-dev libxrandr-dev libxinerama-dev

To switch away from a source build, use:

    haxelib dev lime

Sample
======

You can build a sample Lime project with the following commands:

    lime create HelloWorld
    cd HelloWorld
    lime test neko

You can also list other projects that are available using "lime create".

Targets
=======

Lime currently supports the following targets:

    lime test windows
    lime test mac
    lime test linux
    lime test android
    lime test ios
    lime test html5
    lime test flash
    lime test air
    lime test neko
    lime test hl

Desktop builds are currently designed to be built on the same host OS


text:
const gulp = require('gulp'),
    bump = require('gulp-bump'),
    tsc = require('gulp-typescript'),
    webpack = require('webpack'),
    gutil = require('gulp-util');

gulp.task('bump', () => {
    return gulp.src('./package.json')
        .pipe(bump())
        .pipe(gulp.dest('.'));
});

gulp.task('bump:minor', () => {
    return gulp.src('./package.json')
        .pipe(bump({
            type: 'minor'
        })).pipe(gulp.dest('.'));
});

gulp.task('typescript', () => {
    const project = tsc.createProject('./tsconfig.json')
    return gulp.src('./src/**/*.ts')
        .pipe(project())
        .pipe(gulp.dest('lib'));
});

gulp.task('webpack', done => {
    webpack(require('./webpack.config'), (e, s) => {
        if (e) {
            throw new gutil.PluginError('webpack:build', e);
        }
        gutil.log('[webpack:build]', s.toString({
            chunks: false,
            colors: true
        }));
        done();
    });
});

gulp.task('build', ['typescript', 'webpack']);

gulp.task('watch', ['default'], () => {
    gulp.watch('./src/**/*.ts', ['typescript'])
    const compiler = webpack(require('./webpack.config'));
    compiler.watch({}, e => e ? gutil.log(e) : void 0)

});

gulp.task('default', ['build']);


text:
from inspect import getdoc

def document_func_view(serializer_class=None,
                       response_serializer_class=None,
                       filter_backends=None,
                       permission_classes=None,
                       authentication_classes=None,
                       doc_format_args=list(),
                       doc_format_kwargs=dict()):
    """
    Decorator to make functional view documentable via drf-autodocs
    """
    def decorator(func):
        if serializer_class:
            func.cls.serializer_class = func.view_class.serializer_class = serializer_class
        if response_serializer_class:
            func.cls.response_serializer_class = func.view_class.response_serializer_class = response_serializer_class
        if filter_backends:
            func.cls.filter_backends = func.view_class.filter_backends = filter_backends
        if permission_classes:
            func.cls.permission_classes = func.view_class.permission_classes = permission_classes
        if authentication_classes:
            func.cls.authentication_classes = func.view_class.authentication_classes = authentication_classes
        if doc_format_args or doc_format_kwargs:
            func.cls.__doc__ = func.view_class.__doc__ = getdoc(func).format(*doc_format_args, **doc_format_kwargs)
        return func

    return decorator

def format_docstring(*args, **kwargs):
    """
    Decorator for clean docstring formatting
    """
    def decorator(func):
        func.__doc__ = getdoc(func).format(*args, **kwargs)
        return func
    return decorator


text:
#ifndef __XN_STREAM_DEVICE_STREAM_HOLDER_H__
#define __XN_STREAM_DEVICE_STREAM_HOLDER_H__

//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnDeviceModuleHolder.h"
#include "XnDeviceStream.h"
#include <XnHashT.h>
#include <XnFormats/XnCodec.h>

//---------------------------------------------------------------------------
// Types
//---------------------------------------------------------------------------
class XN_DDK_CPP_API XnStreamDeviceStreamHolder : public XnDeviceModuleHolder
{
public:
	XnStreamDeviceStreamHolder(XnDeviceStream* pStream, XnBool bCompressionIsReadOnly);

	virtual XnStatus Init(const XnActualPropertiesHash* pProps);
	virtual XnStatus Free();

	inline XnDeviceStream* GetStream() { return (XnDeviceStream*)GetModule(); }

	inline XnCompressionFormats GetCompression() const { return (XnCompressionFormats)m_Compression.GetValue(); }

	inline XnCodec* GetCodec() const { return m_pCodec; }

protected:
	XnActualIntProperty& CompressionProperty() { return m_Compression; }

private:
	XnStatus ChooseCodec();

	static XnStatus XN_CALLBACK_TYPE CodecPropertyChangedCallback(const XnProperty* pSender, void* pCookie);

	XnActualIntProperty m_Compression;
	XnCodec* m_pCodec;

	typedef XnHashT<XnProperty*, XnValue> XnPropertiesHash;
	XnPropertiesHash m_CodecProperties;
};

#endif //__XN_STREAM_DEVICE_STREAM_HOLDER_H__


text:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <persistence-unit name="transactions-optional">
        <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
        <class>es.currexify.server.model.CurrencyBudgetModel</class>
      	<class>es.currexify.server.model.CurrencyExRateModel</class>
      	<class>es.currexify.server.model.HistoryModel</class>
      	<class>es.currexify.server.model.UsuariosModel</class>
      	<class>es.currexify.server.model.TransactionModel</class>
        <properties>
            <property name="datanucleus.NontransactionalRead" value="true"/>
            <property name="datanucleus.NontransactionalWrite" value="true"/>
            <property name="datanucleus.ConnectionURL" value="appengine"/>
        </properties>
    </persistence-unit>
</persistence>