text:
#ifndef gamgee__individual_field_value__guard
#define gamgee__individual_field_value__guard

#include "individual_field_value_iterator.h"

#include "../missing.h"
#include "../utils/hts_memory.h"
#include "../utils/utils.h"
#include "../utils/variant_field_type.h"

#include "htslib/vcf.h"

#include <memory>

namespace gamgee {

/**
 * @brief A class template to hold the values a format field for a particular sample
 *
 * The role of this class is to perform the pointer manipulations behind the
 * scenes that permit the user to navigate the values of a field in a sample
 * without making any copies and benefiting from data locality (all the data is
 * stored contiguously in memory).
 *
 * A typical use of the IndividualFieldValue can be exemplified by the
 * phred likelihood accessor in Variant:
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * const auto all_pls = record.integer_individual_field("PL");
 * const auto my_pls = all_pls[2] // take the second sample
 * for_each(my_pls.begin(), my_pls.end(), [](const auto pl) { cout << pl << endl; });
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * IndividualFieldValue objects can also be used in for loops like so:
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * for (const auto pl : my_pls)
 *   cout << pl << endl;
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * While the IndividualFieldValue objects are not really intended to be
 * created by the user, they are the returned by the IndividualField iterator for
 * types that don't have a specialized object.  Utilizing them correctly can
 * really simplify your work by leveraging the power of the STL functions.
 *
 * @note all methods are inlined on purpose because they are so simple
 *
 * @tparam TYPE the object type that holds the values for each sample. For
 * example for GQ it's a uint8_t, some types like GT can have specialized classes
 * like Genotype. For all other types it can be the IndividualFieldValue.
 */
template<class VALUE_TYPE>
class IndividualFieldValue {
 public:

  /**
   * @brief creates a new IndividualFieldValue poiinting to the shared byte array inside the variant object
   * @copydetails IndividualField::IndividualField(const std::shared_ptr<bcf1_t>&, bcf_fmt_t*)
   * @param body the the bcf1_t structure to hold a shared pointer to
   * @param format_ptr the format field pointer inside the body
   * @param data_ptr the location in the specific value inside the format_ptr byte array
   */
  IndividualFieldValue(const std::shared_ptr<bcf1_t>& body, const bcf_fmt_t* const format_ptr, uint8_t* const data_ptr) :
    m_body {body},
    m_format_ptr {format_ptr},
    m_data_ptr {data_ptr},
    m_num_bytes {utils::size_for_type(static_cast<utils::VariantFieldType>(format_ptr->type), format_ptr)}
  {}

  /**
   * @brief copying of the IndividualFieldValue object is not allowed.
   * @copydetails IndividualField::IndividualField(const IndividualField&)
   */
  IndividualFieldValue(const IndividualFieldValue& other) = delete;

  /**
   * @brief safely moves the data from one IndividualFieldValue to a new one without making any copies
   * @param other another IndividualFieldValue object
   */
  IndividualFieldValue(IndividualFieldValue&& other) :
    m_body {std::move(other.m_body)},
    m_format_ptr {other.m_format_ptr},
    m_data_ptr {other.m_data_ptr},
    m_num_bytes {other.m_num_bytes}
  {}

  /**
   * @copydoc IndividualField::IndividualFieldValue(const IndividualFieldValue&)
   */
  IndividualFieldValue& operator=(const IndividualFieldValue& other) = delete;

  /**
   * @brief safely moves the data from one IndividualField to the other without making any copies
   * @param other another IndividualFieldValue object
   */
  IndividualFieldValue& operator=(IndividualFieldValue&& other) {
    if (this != &other)
      return *this;
    m_body = std::move(other.m_body);
    m_format_ptr = other.m_format_ptr;
    m_data_ptr = other.m_data_ptr;
    m_num_bytes = other.m_num_bytes;
    return *this;
  }

  /**
   * @brief compares two IndividualFieldValue objects in the following order: memory address, size and values.
   * @param other something to compare to
   * @return true if the objects are the same (memory address-wise), or contain exactly the same values. Value comparison is dictated by TYPE's operator== implementation
   */
  bool operator==(const IndividualFieldValue& other) const {
    if (this == &other)
      return true;
    //Use iterators where possible as they take care of field sizes, bcf_*_vector_end
    auto other_iter = other.begin();
    auto other_end = other.end();
    for(const auto& curr_val : *this)
    {
      if(other_iter == other_end)	//different length, this is longer (more valid values) than other
	return false;
      if(!utils::bcf_check_equal_element(curr_val, *other_iter))
	return false;
      ++other_iter;
    }
    //Check if other still has more valid values
    if(other_iter != other_end)
      return false;
    return true;
  }

  /**
   * @brief compares two IndividualFieldValue objects in the following order: memory address, size and values.
   * @param other something to compare to
   * @return true if the objects are not the same (memory address-wise), or contain different number of values, or the values are not exactly the same. Value comparison is dictated by TYPE's operator== implementation
   */
  bool operator!=(const IndividualFieldValue& other) const {
    return !(*this == other);
  }

  /**
   * @brief random access to the value of a given sample for reading or writing
   * @param index must be between 0 and the number of values per sample for this record
   * @note implementation guarantees this operation to be O(1)
   * @exception std::out_of_range if sample is out of range
   * @return the value in that index
   */
  VALUE_TYPE operator[](const uint32_t index) const {
    utils::check_max_boundary(index, m_format_ptr->n);
    return convert_from_byte_array(index);
  }

  /**
   * @brief create a new begin iterator over the values for this sample
   */
  IndividualFieldValueIterator<VALUE_TYPE> begin() const {
    return IndividualFieldValueIterator<VALUE_TYPE>{m_body, m_data_ptr, m_data_ptr + m_format_ptr->size, m_num_bytes, static_cast<utils::VariantFieldType>(m_format_ptr->type)};
  }

  /**
   * @brief create a new end iterator over the values for this sample
   */
  IndividualFieldValueIterator<VALUE_TYPE> end() const {
    return IndividualFieldValueIterator<VALUE_TYPE>{m_body, m_data_ptr + m_format_ptr->size, m_data_ptr + m_format_ptr->size, m_num_bytes, static_cast<utils::VariantFieldType>(m_format_ptr->type)};
  }

  uint32_t size() const { return m_format_ptr->n; } ///< @brief the number of values in this IndividualFieldValue (values per sample)
  VALUE_TYPE front() const { return operator[](0); }                    ///< @brief convenience function to access the first element
  VALUE_TYPE back() const { return operator[](m_format_ptr->n - 1); }   ///< @brief convenience function to access the last element

  /**
   * @brief returns true if all of the values are missing
   */
  bool missing() const {
    // Important: relies on IndividualFieldValueIterator to skip vector end values, if there are any
    for (const auto& value : *this) {
      // use qualifier to avoid recursion
      if (!gamgee::missing(value))
        return false;
    }
    return true;
  }

 private:
  std::shared_ptr<bcf1_t> m_body;
  const bcf_fmt_t* m_format_ptr;
  uint8_t* m_data_ptr;
  uint8_t m_num_bytes;

  VALUE_TYPE convert_from_byte_array(int index) const;
};

/**
 * @brief specialization of the conversion template for int32_t
 */
template<> inline
int32_t IndividualFieldValue<int32_t>::convert_from_byte_array(int index) const {
  return utils::convert_data_to_integer(m_data_ptr, index, m_num_bytes, static_cast<utils::VariantFieldType>(m_format_ptr->type));
}

/**
 * @brief specialization of the conversion template for floats
 */
template<> inline
float IndividualFieldValue<float>::convert_from_byte_array(int index) const {
  return utils::convert_data_to_float(m_data_ptr, index, m_num_bytes, static_cast<utils::VariantFieldType>(m_format_ptr->type));
}

/**
 * @brief specialization of the conversion template for strings
 */
template<> inline
std::string IndividualFieldValue<std::string>::convert_from_byte_array(int index) const {
  return utils::convert_data_to_string(m_data_ptr, index, m_num_bytes, static_cast<utils::VariantFieldType>(m_format_ptr->type));
}

/**
 * @brief  specialization for operator[] for strings
 * String fields have 1 string (at most), it is wrong to have a non-0 index
 */
template<> inline
std::string IndividualFieldValue<std::string>::operator[](const uint32_t index) const {
  auto is_string_type = utils::is_string_type(m_format_ptr->type);
  auto limit = size();
  auto prefix_msg = "";
  if(is_string_type)
  {
    limit = 1u;
    prefix_msg = "FORMAT fields of type string in VCFs have only 1 element per sample :: ";
  }
  utils::check_max_boundary(index, limit, prefix_msg);
  return convert_from_byte_array(index);
}

}

#endif // gamgee__individual_field_value__guard


text:
title: Remotely Debugging Opera for Android
authors:
- bruce-lawson
- chris-mills
intro: 'Now that Opera for Android is out, you'll sometimes need to debug it, as there are differences in Standards support between Opera and Chrome for Android and Chrome on Android 4+. Here's how to connect Opera for Android to Chromium-based desktop browsers for remote debugging.'
tags:
- android
- opera-presto
- remote-debugging
license: cc-by-3.0
---

## Introduction

Now that Opera for Android is out, you'll sometimes need to debug it, as there are differences in Standards support between Opera and Chrome for Android and Chrome on Android 4+ (`<input type=color>`, `@supports`, etc,).

Here's how to connect Opera for Android to Chromium-based desktop browsers for remote debugging.

## Preparing your desktop

You'll be remotely debugging your phone from your desktop, so let's get the desktop ready.

### Install Android SDK

The first thing you'll need is the [Android SDK — download it][1] and then put the kettle on; it's a 400MB file.

[1]: http://developer.android.com/sdk/index.html#download

Extract the files to a memorable location, such as /Users/_your-user-name_/adt or c:android/adt. If you choose something else, use that in the example steps below.

Windows users may need to [install Device drivers][2]. Linux and Mac users shouldn't need to.

[2]: http://developer.android.com/tools/extras/oem-usb.html

### Install a Chromium-based browser

You'll need a Chromium-based desktop browser. Use Opera 15+, Google Chrome, Chromium, or the Yandex browser.

### Preparing your device

Ensure that you have a USB cable available to connect your Android device to your computer (the USB power cable should be fine) and [Opera for Android][3] installed on it (see the [Opera for Android user guide][4] for installation help, if needed.) Keep the phone disconnected from your computer just for now.

[3]: https://play.google.com/store/apps/details?id=com.opera.browser
[4]: http://www.opera.com/help/mobile

Note that you can't remotely debug Opera Mini from desktop, as the rendering is done on our Mini servers and only displayed on the device. ([Opera Mini FAQs][5])

[5]: http://www.opera.com/help/mini/faq

Next, you need to [enable USB debugging on your device][6]. Check the "USB debugging" checkbox in Developer Options.

[6]: http://developer.android.com/tools/device.html

- On Android 2.3, the option is under Settings > Applications > Development
- On Android 4.0 and newer, it's in Settings > Developer options
- On Android 4.2 and newer, go to Settings > About phone and tap Build number seven times to get a message that says "congratulations! you are now a developer". Returning to the previous screen shows previously-hidden developer options.

On Android 4.2.2 and higher, you'll see a dialog asking whether to accept an RSA key. This is a security mechanism; accept the dialog.

When doing mobile debugging on Android it is also useful to check the "stay awake" option that you'll find in the same place as the "USB debugging" option, so the device stays on while plugged into USB, but this isn't mandatory.

![Android developer options with 'Stay Awake' option checked](stay-awake.png)

Before moving on, connect your phone to your computer via the USB cable. If it was already connected, try disconnecting and reconnecting it, just to make sure the computer recognises the phone properly. You should see a message on the phone along the lines of "USB debugging connected" to indicate that things are proceeding successfully.

## Connect desktop to device

Start Opera for Android, and enable debugging by entering opera:debug in your address bar and checking the "enable" checkbox in the resulting page, as seen below.

![opera:debug page and 'enable' checkbox](opera-debug.png)

Now let's get the debugger started:

In your computer's terminal, navigate to the directory into which you extracted the Android SDK. Once there, navigate to sdk > platform-tools. Inside there you should see an executable called adb, which is an acronym for Android Debugging Bridge.

To start the debugging bridge, Type in the following terminal command:

	adb forward tcp:9222 localabstract:com.opera.browser.devtools

You should see a message output along the lines of the following:

	$ daemon not running. starting it now on port 5037*
	$ daemon started successfully

If you are using Linux or Mac OSX, you will have to add ./ at the start of the terminal command above, to tell terminal to look for adb inside the current directory, and not your Path. To avoid having to do this every time, you could add a path to adb in your actual path. You can do this by placing a line in your ~/.profile or ~/.bash_profile like so:

	export PATH=/Users/your-username/path-to-adk-folder/adt/sdk/platform-tools/:$PATH

You'll then need to restart the Terminal, or open a new tab.

## Debug!

Your device and desktop browser should now be connected and able to send information to each other across the debugging bridge. To begin debugging, go to localhost:9222 in your desktop browser. You'll see a list of inspectable tabs (note that if you open a new tab on the device, you'll need to refresh the Inspectable Tabs page):

![localhost:9222 list of inspectable tabs](inspectable-tabs.png)

If you instead get a message saying that the server sent no data, or similar, you might have typed in the Terminal command incorrectly. Go back to the Terminal, check it, and try again. There is a very small chance that, if it didn't work, the bridge isn't running, but its process still is. If you still have a problem upon retrying the Terminal command, you might have kill the process directly. This can be done by first typing the command `ps -A` to bring up a list of running processes, finding the right process ID (the one with "adb fork-server server" in the CMD column), and then killing it with `kill _your-process-id_`.

Clicking on one of the inspectable tabs brings up the web inspector full-screen, allowing you to debug, change the page, and [all sorts of amazing things][10]:

[10]: https://docs.google.com/presentation/d/1DNljLkRpe9LIDfcqcpHzdLvEOyuVH4d1y9dtAJBr1I8/preview#slide=id.p19

![web inspector showing page, changing a heading](web-inspector.gif)

and the changes are immediately visible on your device:

![changes happen on the device instantly](android-debugging.png)

## What about Opera Dragonfly?

The current version of Opera Dragonfly (which is Presto-based) won't work with Chromium, because the protocols are radically different.

Cover image by [sleepingcatbeads][14].

[14]: http://www.flickr.com/photos/sleepingcatbeads/3872894835/

redpajama_set_name: RedPajamaGithub


text:
namespace Bezysoftware.Navigation.Sample.ViewModels
{
    using Bezysoftware.Navigation.Lookup;
    using Bezysoftware.Navigation.Platform;
    using Bezysoftware.Navigation.Sample.AssemblyResolver;
    using Bezysoftware.Navigation.Sample.Dto;
    using Bezysoftware.Navigation.Sample.Views;
    using Bezysoftware.Navigation.StatePersistence;
    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.Unity;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading.Tasks;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        static ViewModelLocator()
        {
            var unity = new UnityContainer();

            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unity));

            unity
                .RegisterType<INavigationService, NavigationService>(new ContainerControlledLifetimeManager())
                .RegisterType<IViewLocator, ViewLocator>(new ContainerControlledLifetimeManager())
                .RegisterType<IStore, Store>(new ContainerControlledLifetimeManager())
                .RegisterType<IViewModelLocator, ViewModelServiceLocator>(new ContainerControlledLifetimeManager())
                .RegisterType<IPlatformNavigator, PlatformNavigator>(new ContainerControlledLifetimeManager())
                .RegisterType<IApplicationFrameProvider, CurrentWindowFrameProvider>(new ContainerControlledLifetimeManager())
                .RegisterType<IStatePersistor, StatePersistor>(new ContainerControlledLifetimeManager())
                .RegisterType<IAssemblyResolver, ThisAssemblyResolver>(new ContainerControlledLifetimeManager())
                .RegisterInstance(typeof(TaskScheduler), TaskScheduler.Default)
                .RegisterType<INavigationInterceptor, AdaptiveNavigationInterceptor>("Adaptive", new ContainerControlledLifetimeManager())
                .RegisterType<IEnumerable<INavigationInterceptor>, INavigationInterceptor[]>(new ContainerControlledLifetimeManager())
                .RegisterType<MainViewModel>(new ContainerControlledLifetimeManager())
                .RegisterType<SecondViewModel>(new ContainerControlledLifetimeManager())
                .RegisterType<ThirdViewModel>(new ContainerControlledLifetimeManager());

            // manually register association for the main page to speed up application startup
            unity.Resolve<IViewLocator>().RegisterAssociation<MainViewModel, MainPage>();

            ServiceLocator.Current.GetInstance<INavigationService>().Navigated += ViewModelLocator_Navigated;
        }

        private static void ViewModelLocator_Navigated(object sender, NavigationEventArgs e)
        {
            Debug.WriteLine(e.OriginalViewModelType);
        }

        public static void Init()
        { }

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public SecondViewModel Second
        {
            get
            {
                return ServiceLocator.Current.GetInstance<SecondViewModel>();
            }
        }

        public ThirdViewModel Third
        {
            get
            {
                return ServiceLocator.Current.GetInstance<ThirdViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }
}


text:
layout: page
title: "Things to do on a new Rails project"
date:  2017-05-09 12:25:26
---

**Replace byebug with pry**

**Add ruby-version and -gemset files**

**run bin/setup**

**check that rails t works**

**setup foreman**

**disable useless generators**

**switch to uuids (maybe not)**

**write readme**

**Add pronto**

**Add rack-mini-profiler**


text:
var R = require('ramda');

module.exports = IO;

var compose = R.compose;

function IO(fn) {
  if (!(this instanceof IO)) {
    return new IO(fn);
  }
  this.fn = fn;
}

// `f` must return an IO
IO.prototype.chain = function(f) {
  var io = this;
  return new IO(function() {
    return f(io.fn()).fn();
  });
};

IO.prototype.map = function(f) {
  var io = this;
  return new IO(compose(f, io.fn));
};

// `this` IO must wrap a function `f` that takes an IO (`thatIo`) as input
// `f` must return an IO
IO.prototype.ap = function(thatIo) {
  return this.chain(function(f) {
    return thatIo.map(f);
  });
};

IO.runIO = function(io) {
  return io.runIO.apply(io, [].slice.call(arguments, 1));
};

IO.prototype.runIO = function() {
  return this.fn.apply(this, arguments);
};

IO.prototype.of = function(x) {
  return new IO(function() { return x; });
};

IO.of = IO.prototype.of;

// this is really only to accommodate testing ....
IO.prototype.equals = function(that) {
  return this === that ||
    this.fn === that.fn ||
    R.equals(IO.runIO(this), IO.runIO(that));
};

IO.prototype.toString = function() {
  return 'IO(' + R.toString(this.fn) + ')';
};


text:
module Control.Concurrent.STM.TXChan
  ( TXChan()
  , newTXChan
  , newTXChanIO
  , newEmptyTXChan
  , newEmptyTXChanIO
  , writeTXChan
  , readTXChan
  , takeTXChan ) where

import Control.Concurrent.STM

data TXChan a = TXChan (TVar (Maybe a))
  deriving (Eq)

newTXChan :: a -> STM (TXChan a)
newTXChan x = TXChan <$> newTVar (Just x)

newTXChanIO :: a -> IO (TXChan a)
newTXChanIO x = TXChan <$> newTVarIO (Just x)

newEmptyTXChan :: STM (TXChan a)
newEmptyTXChan = TXChan <$> newTVar Nothing

newEmptyTXChanIO :: IO (TXChan a)
newEmptyTXChanIO = TXChan <$> newTVarIO Nothing

writeTXChan :: TXChan a -> a -> STM ()
writeTXChan (TXChan v) a = writeTVar v (Just a)

readTXChan :: TXChan a -> STM (Maybe a)
readTXChan (TXChan v) = readTVar v

takeTXChan :: TXChan a -> STM a
takeTXChan (TXChan v) = do
  val <- readTVar v
  case val of
    Just x -> return x
    Nothing -> retry


text:
package org.vizzini.swingui.game.boardgame.chess.standard;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import org.vizzini.chess.standard.StandardGameInjector;
import org.vizzini.swingui.game.boardgame.chess.ChessPanel;

/**
 * Provides a user interface for standard chess.
 *

 * To get the application name in the Mac menu bar, add this to the run configuration:
 *

 * -Dcom.apple.mrj.application.apple.menu.about.name="Vizzini Chess"
 */
public final class StandardChessUI extends JFrame
{
    /**
     * Application method.
     *
     * @param args Application arguments.
     */
    public static final void main(final String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                final StandardChessUI app = new StandardChessUI();
                app.setVisible(true);
            }
        });
    }

    /**
     * Construct this object.
     */
    public StandardChessUI()
    {
        final ChessPanel appPanel = new ChessPanel(this, new StandardGameInjector());

        setTitle("Vizzini Standard Chess");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(appPanel, BorderLayout.CENTER);
        final Dimension size = new Dimension(1024, 768);
        setPreferredSize(size);
        setSize(size);
        setLocationRelativeTo(null);

        appPanel.start();
    }
}


text:
const Node = require('./node')
const JsEvalNode = require('./js-eval-node')
const Variable = require('./variable')

class Quoted extends JsEvalNode {
  constructor(str, content, escaped, index, currentFileInfo) {
    super()
    this.escaped = escaped == null ? true : escaped
    this.value = content || ''
    this.quote = str.charAt(0)
    this.index = index
    this.currentFileInfo = currentFileInfo
  }

  genCSS(context, output) {
    if (!this.escaped) {
      output.add(this.quote, this.currentFileInfo, this.index)
    }
    output.add(this.value)
    if (!this.escaped) {
      output.add(this.quote)
    }
  }

  containsVariables() {
    return this.value.match(/(`([^`]+)`)|@\{([\w-]+)\}/)
  }

  eval(context) {
    const that = this
    let value = this.value
    const javascriptReplacement = (_, exp) =>
      String(that.evaluateJavaScript(exp, context))
    const interpolationReplacement = (_, name) => {
      const v = new Variable(`@${name}`, that.index, that.currentFileInfo).eval(
        context,
        true
      )
      return v instanceof Quoted ? v.value : v.toCSS()
    }
    function iterativeReplace(value, regexp, replacementFnc) {
      let evaluatedValue = value
      do {
        value = evaluatedValue
        evaluatedValue = value.replace(regexp, replacementFnc)
      } while (value !== evaluatedValue)
      return evaluatedValue
    }
    value = iterativeReplace(value, /`([^`]+)`/g, javascriptReplacement)
    value = iterativeReplace(value, /@\{([\w-]+)\}/g, interpolationReplacement)
    return new Quoted(
      this.quote + value + this.quote,
      value,
      this.escaped,
      this.index,
      this.currentFileInfo
    )
  }

  compare(other) {
    // when comparing quoted strings allow the quote to differ
    if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
      return Node.numericCompare(this.value, other.value)
    } else {
      return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined
    }
  }
}

Quoted.prototype.type = 'Quoted'
module.exports = Quoted


text:
- Helpers module extracted into two seperate gems (turkish_ranges, turkish_regexps). [`a2a6261`](https://github.com/sbagdat/turkish_support/commit/a2a6261)
- Too much refactoring. [`a2a6261`](https://github.com/sbagdat/turkish_support/commit/a2a6261)
- Decided to keep a changelog file (this file).


text:
<?php

namespace OpenClassrooms\Tests\UseCase\BusinessRules\UseCases\Transaction;

use OpenClassrooms\UseCase\Application\Annotations\Transaction;
use OpenClassrooms\UseCase\BusinessRules\Requestors\UseCase;
use OpenClassrooms\UseCase\BusinessRules\Requestors\UseCaseRequest;
use OpenClassrooms\UseCase\BusinessRules\Responders\UseCaseResponse;

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class NestedTransactionUseCaseStub implements UseCase
{

    /**
     * @var UseCase
     */
    private $nestedUseCase;

    /**
     * @Transaction()
     * @return UseCaseResponse
     */
    public function execute(UseCaseRequest $useCaseRequest)
    {
        return $this->nestedUseCase->execute($useCaseRequest);
    }

    public function setNestedUseCase(UseCase $nestedUseCase)
    {
        $this->nestedUseCase = $nestedUseCase;
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Farlowia 1: 104 (1943)

#### Original name
null

### Remarks
null


text:
By Wayne Zhu
Utility created based on HDP/CDH stand-alone sandbox, but can be modified for a muti-node cluster.

github
https://help.github.com/articles/changing-a-remote-s-url/
https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/
To swithc ssh key in ssh-agnet:
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa


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">

  <title>Categorías « Camilo Alvarado</title>
  <meta name="description" content="La Web es maravillosa.">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost/categorias/">
  <link rel="alternate" type="application/rss+xml" title="Camilo Alvarado" href="http://localhost/feed.xml" />
  <link rel="shortcut icon" type="image/png" href="https://scontent-mia1-1.xx.fbcdn.net/v/t1.0-9/15380522_1188555537859132_1972087068581904017_n.jpg?oh=87d5609e54434edaeb3c40e8438c2f9e&oe=58E48147"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link  href="http://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css?family=Dancing+Script" rel="stylesheet">

     Camilo Alvarado

        Acerca

        Categorías

Categorías

CONTRACULTURA

Aug 25 » The Internet's Own Boy, un documental sobre Aaron Swartz, como se levantó por la libertad y la justicia y fue perseguido hasta su muerte

Jul 30 » Un manifiesto de los Nativos Digitales

Jun 03 » EL EMPLEO - THE EMPLOYMENT

TECNOLOGíA

Aug 25 » The Internet's Own Boy, un documental sobre Aaron Swartz, como se levantó por la libertad y la justicia y fue perseguido hasta su muerte

Jul 30 » Un manifiesto de los Nativos Digitales

Camilo Alvarado

Desarrollador Web, entusiasta del Software Libre, interesado en promover las libertades en detrimento de las privaciones y los prejuicios.

Nuevos Posts

The Internet's Own Boy, un documental sobre Aaron Swartz, como se levantó por la libertad y la justicia y fue perseguido hasta su muerte

Un manifiesto de los Nativos Digitales

EL EMPLEO - THE EMPLOYMENT

Creative Commons  2016 Camilo Alvarado


text:
<?php

namespace Sunahip\EntityBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SunahipEntityBundle extends Bundle
{
}


text:
import {get, isEmpty} from 'lodash'
import {BuilderConfig, DashboardDraftQuery} from 'src/types'
import {FUNCTIONS} from 'src/timeMachine/constants/queryBuilder'
import {
  TIME_RANGE_START,
  TIME_RANGE_STOP,
  OPTION_NAME,
  WINDOW_PERIOD,
} from 'src/variables/constants'
import {AGG_WINDOW_AUTO} from 'src/timeMachine/constants/queryBuilder'
import {BuilderTagsType} from '@influxdata/influx'

export function isConfigValid(builderConfig: BuilderConfig): boolean {
  const {buckets, tags} = builderConfig
  const isConfigValid =
    buckets.length >= 1 &&
    tags.length >= 1 &&
    tags.some(({key, values}) => key && values.length > 0)

  return isConfigValid
}

export interface CheckQueryValidity {
  oneQuery: boolean
  builderMode: boolean
  singleAggregateFunc: boolean
  singleField: boolean
}

export const isDraftQueryAlertable = (
  draftQueries: DashboardDraftQuery[]
): CheckQueryValidity => {
  const tags: BuilderTagsType[] = get(
    draftQueries,
    '[0].builderConfig.tags',
    []
  )
  const fieldSelection = tags.find(t => get(t, 'key') === '_field')
  const fieldValues = get(fieldSelection, 'values', [])
  const functions = draftQueries[0].builderConfig.functions
  return {
    oneQuery: draftQueries.length === 1, // one query
    builderMode: draftQueries[0].editMode == 'builder', // built in builder
    singleAggregateFunc: functions.length === 1, // one aggregate function
    singleField: fieldValues.length === 1, // one field selection
  }
}

export const isCheckSaveable = (
  draftQueries: DashboardDraftQuery[]
): boolean => {
  const {
    oneQuery,
    builderMode,
    singleAggregateFunc,
    singleField,
  } = isDraftQueryAlertable(draftQueries)
  return oneQuery && builderMode && singleAggregateFunc && singleField
}

export function buildQuery(builderConfig: BuilderConfig): string {
  const {functions} = builderConfig

  let query: string

  if (functions.length) {
    query = functions.map(f => buildQueryHelper(builderConfig, f)).join('\n\n')
  } else {
    query = buildQueryHelper(builderConfig)
  }

  return query
}

function buildQueryHelper(
  builderConfig: BuilderConfig,
  fn?: BuilderConfig['functions'][0]
): string {
  const [bucket] = builderConfig.buckets
  const tagFilterCall = formatTagFilterCall(builderConfig.tags)
  const {aggregateWindow} = builderConfig
  const fnCall = fn ? formatFunctionCall(fn, aggregateWindow.period) : ''

  const query = `from(bucket: "${bucket}")
  |> range(start: ${OPTION_NAME}.${TIME_RANGE_START}, stop: ${OPTION_NAME}.${TIME_RANGE_STOP})${tagFilterCall}${fnCall}`

  return query
}

export function formatFunctionCall(
  fn: BuilderConfig['functions'][0],
  period: string
) {
  const fnSpec = FUNCTIONS.find(spec => spec.name === fn.name)

  if (!fnSpec) {
    return
  }

  const formattedPeriod = formatPeriod(period)

  return `\n  ${fnSpec.flux(formattedPeriod)}\n  |> yield(name: "${fn.name}")`
}

const formatPeriod = (period: string): string => {
  if (period === AGG_WINDOW_AUTO || !period) {
    return `${OPTION_NAME}.${WINDOW_PERIOD}`
  }

  return period
}

function formatTagFilterCall(tagsSelections: BuilderConfig['tags']) {
  if (!tagsSelections.length) {
    return ''
  }

  const calls = tagsSelections
    .filter(({key, values}) => key && values.length)
    .map(({key, values}) => {
      const fnBody = values.map(value => `r.${key} == "${value}"`).join(' or ')

      return `|> filter(fn: (r) => ${fnBody})`
    })
    .join('\n  ')

  return `\n  ${calls}`
}

export function hasQueryBeenEdited(
  query: string,
  builderConfig: BuilderConfig
): boolean {
  const emptyQueryChanged = !isConfigValid(builderConfig) && !isEmpty(query)
  const existingQueryChanged = query !== buildQuery(builderConfig)

  return emptyQueryChanged || existingQueryChanged
}


text:
<?php
/* setup default time zone */
date_default_timezone_set('UTC');

/* change dir to root */
chdir(dirname(__FILE__) . '/..');

/* change to set debug mode */
// defined('YII_DEBUG') or define('YII_DEBUG',true);

$config =  'console/config/main.php';

require_once('common/lib/Yii/yii.php');
require_once('common/lib/Yii/yiic.php');


text:
var basicNextTick;
if ((typeof process=='object') && (typeof process.nextTick=='function')){
	basicNextTick = process.nextTick;
} else if (typeof setImmediate=='function'){
	basicNextTick = function(fn){
		// not a direct alias for IE10 compatibility
		setImmediate(fn);
	};
} else {
	basicNextTick = function(fn){
		setTimeout(fn, 0);
	};
}
var nextTick = function(fn){
	var cancelled = false;
	var cancel = function(){
		cancelled = true;
	};
	basicNextTick(function(){
		if (!cancelled){
			fn();
		}
	});
	return cancel;
};
module.exports = nextTick;


text:
int resizeManual(std::string input,std::string output, cv::Point size, cv::Point featured1, cv::Point featured2);
int resizeAutomatic(std::string input, std::string output, cv::Point size);
int clip(int n, int lower, int upper);


text:
package com.bydavy.digitalclock;

import android.app.Activity;
import android.os.Bundle;
import com.bydavy.morpher.DigitalClockView;
import com.bydavy.morpher.font.DFont;

import java.text.SimpleDateFormat;

public class SimpleBigClock extends Activity implements SystemClockManager.SystemClockListener {

	public static final String EXTRA_MORPHING_DURATION = "morphing_duration";

	private DigitalClockView mDigitalClockView;
	private SystemClockManager mSystemClockManager;
	private SimpleDateFormat mSimpleDateFormat;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simple_big_clock);

		mDigitalClockView = (DigitalClockView) findViewById(R.id.digitalClock);
		mDigitalClockView.setFont(new DFont(130, 10));

		int morphingDuration = getIntent().getIntExtra(EXTRA_MORPHING_DURATION, DigitalClockView.DEFAULT_MORPHING_DURATION);
		mDigitalClockView.setMorphingDuration(morphingDuration);

		mSimpleDateFormat = new SimpleDateFormat("hh:mm:ss");
		mSystemClockManager = new SystemClockManager(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSystemClockManager.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mSystemClockManager.stop();
	}

	@Override
	public void onTimeChanged(long time) {
		String formattedTime = mSimpleDateFormat.format(time);

		// Useful when a long morphing duration is set otherwise we never see the destination number as it's always morphing
		if (!mDigitalClockView.isMorphingAnimationRunning()) {
			mDigitalClockView.setTime(formattedTime);
		}
	}
}


text:
package gettext

import (
	"testing"
)

func TestFileSystem_os(t *testing.T) {
	fs := OS("./examples/locale")
	tAssert(t, fs.String() == "gettext.localfs(./examples/locale)", fs.String())

	testExamplesLocal(t, fs)
}

func TestFileSystem_zip(t *testing.T) {
	fs := NewFS("./examples/locale.zip", nil)
	tAssert(t, fs.String() == "gettext.zipfs(./examples/locale.zip)", fs.String())

	testExamplesLocal(t, fs)
}

func testExamplesLocal(t *testing.T, fs FileSystem) {
	localeList := fs.LocaleList()
	tAssert(t, len(localeList) == 3, localeList)
	tAssert(t, localeList[0] == "default")
	tAssert(t, localeList[1] == "zh_CN")
	tAssert(t, localeList[2] == "zh_TW")
}


text:
layout: tutorial_v2
title: Zoom levels
---

## Zoom levels

Leaflet works with [latitude](https://en.wikipedia.org/wiki/Latitude), [longitude](https://en.wikipedia.org/wiki/Longitude) and "zoom level".

Lower zoom levels means that the map shows entire continents, while higher zoom
levels means that the map can show details of a city.

To understand how zoom levels work, first we need a basic introduction to geodesy.

## The shape of the earth

Let's have a look at a simple map locked at zoom zero:

	var map = L.map('map', {
		minZoom: 0,
		maxZoom: 0
	});

	var cartodbAttribution = '© OpenStreetMap contributors, © CARTO';

	var positron = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
		attribution: cartodbAttribution
	}).addTo(map);

	map.setView([0, 0], 0);

{% include frame.html url="example-zero.html" %}

Notice that the "whole earth" is just one image, 256 pixels wide and 256 pixels high:

Just to be clear: the earth is not a square. Rather, the earth has an irregular shape that can be approximated to [something similar to a sphere](https://en.wikipedia.org/wiki/Geoid).

So we *assume* that the earth is mostly round. To make it flat, we put an imaginary cylinder around, unroll it, and cut it so it looks square:

This is called a "cylindrical map projection".

This is not the only way of displaying the surface on the earth on a plane. There
are [hundreds of ways](https://en.wikipedia.org/wiki/Map_projection), each of them
with its own advantages and disadvantages. The following 6-minute video is a nice
introduction to the topic:

Things like geodesy, map projections and coordinate systems are hard, *very hard*
(and out of scope for this tutorial). Assuming that the earth is a square is not
always the right thing to do, but most of the time works fine enough, makes things
simpler, and allows Leaflet (and other map libraries) to be fast.

## Powers of two

For now, let's just ***assume*** that the world is a square:

When we represent the world at zoom level **zero**, it's 256 pixels wide and high. When we go into zoom level **one**, it doubles its width and height, and can be represented by four 256-pixel-by-256-pixel images:

At each zoom level, each tile is divided in four, and its size (length of the edge, given by the `tileSize` option) doubles, quadrupling the area. (in other words, the width and height of the world is 256·2zoomlevel pixels):

Zoom 0	Zoom 1	Zoom 2

This goes on and on. Most tile services offer tiles up to zoom level 18, depending on
their coverage. This is enough to see a few city blocks per tile.

## A note about scale

One of the disadvantages of using a cylindrical projection is that the scale is not
constant, and measuring distances or sizes is not reliable, specially at low zoom levels.

In [technical terms](https://en.wikipedia.org/wiki/Map_projection#Projections_by_preservation_of_a_metric_property),
the cylindrical projection that Leaflet uses is conformal (preserves shapes),
but not equidistant (does not preserve distances), and not equal-area
(does not preserve areas, as things near the equator appear smaller than they are).

By adding a `L.Control.Scale` to a map, and panning to the equator and to 60° north,
we can see how the scale factor doubles. The following example uses
[javascript timeouts](https://developer.mozilla.org/docs/Web/API/WindowTimers/setTimeout)
to  do this automatically:

	L.control.scale().addTo(map);

	setInterval(function(){
		map.setView([0, 0]);
		setTimeout(function(){
			map.setView([60, 0]);
		}, 2000);
	}, 4000);

{% include frame.html url="example-scale.html" %}

`L.Control.Scale` shows the scale which applies to the center point of the map.
At high zoom levels, the scale changes very little, and is not noticeable.

## Controlling the zoom

A leaflet map has several ways to control the zoom level shown, but the most obvious
one is [`setZoom()`](/reference.html#map-setzoom). For example, `map.setZoom(0);`
will set the zoom level of `map` to `0`.

This example again uses timeouts to alternate between zoom levels `0` and `1` automatically:

	setInterval(function(){
		map.setZoom(0);
		setTimeout(function(){
			map.setZoom(1);
		}, 2000);
	}, 4000);

{% include frame.html url="example-setzoom.html" %}

Notice how the images shown at zoom levels 0 and one correspond with the images
shown in the previous section!

Other ways of setting the zoom are:

* [`setView(center, zoom)`](/reference.html#map-setview), which also sets the map center
* [`flyTo(center, zoom)`](/reference.html#map-flyto), like `setView` but with a smooth animation
* [`zoomIn()` / `zoomIn(delta)`](/reference.html#map-zoomin), zooms in `delta` zoom levels, `1` by default
* [`zoomOut()` / `zoomOut(delta)`](/reference.html#map-zoomout), zooms out `delta` zoom levels, `1` by default
* [`setZoomAround(fixedPoint, zoom)`](/reference.html#map-setzoomaround), sets the zoom level while keeping a point fixed (what scrollwheel zooming does)
* [`fitBounds(bounds)`](/reference.html#map-fitbounds), automatically calculates the zoom to fit a rectangular area on the map

## Fractional zoom

A feature introduced in Leaflet 1.0.0 was the concept of fractional zoom.
Before this, the zoom level of the map could be only an integer number (`0`, `1`, `2`, and so on);
but now you can use fractional numbers like `1.5` or `1.25`.

Fractional zoom is disabled by default. To enable it, use the
[map's `zoomSnap` option](/reference.html#map-zoomsnap).
The `zoomSnap` option has a default value of `1` (which means that the zoom level
of the map can be `0`, `1`, `2`, and so on).

If you set the value of `zoomSnap` to `0.5`, the valid zoom levels of the map
will be `0`, `0.5`, `1`, `1.5`, `2`, and so on.

If you set a value of `0.1`, the valid zoom levels of the map will be `0`, `0.1`,
`0.2`, `0.3`, `0.4`, and so on.

The following example uses a `zoomSnap` value of `0.25`:

	var map = L.map('map', {
		zoomSnap: 0.25
	});

{% include frame.html url="example-fractional.html" %}

As you can see, Leaflet will only load the tiles for zoom levels `0` or `1`, and will scale them
as needed.

Leaflet will snap the zoom level to the closest valid one. For example,
if you have `zoomSnap: 0.25` and you try to do `map.setZoom(0.8)`, the zoom will
snap back to `0.75`. The same happens with `map.fitBounds(bounds)`, or when ending
a pinch-zoom gesture on a touchscreen.

`zoomSnap` can be set to zero. This means that Leaflet will not
snap the zoom level.

There is another important map option related to `zoomSnap`: [the `zoomDelta` option](/reference.html#map-zoomdelta).
This controls how many zoom levels to zoom in/out when using the zoom buttons
(from the default [`L.Control.Zoom`](/reference.html#control-zoom))
or the `+`/`-` keys in your keyboard.

For the mousewheel zoom, the [`wheelPxPerZoomLevel`](/reference.html#map-wheelpxperzoomlevel)
option controls how fast the mousewheel zooms in or out.

Here is an example with `zoomSnap` set to zero:

	var map = L.map('map', {
		zoomDelta: 0.25,
		zoomSnap: 0
	});

Try the following, and see how the zoom level changes:

* Pinch-zoom if you have a touchscreen
* Zoom in/out with your mousewheel
* Do a box zoom (drag with your mouse while pressing the `shift` key in your keyboard)
* Use the zoom in/out buttons

{% include frame.html url="example-delta.html" %}

That concludes this tutorial. Now play with your zoom levels in your maps!


text:
/* eslint-env mocha */
'use strict'

const expect = require('chai').expect

const obfuscateString = require('./../../lib/obfuscate-string')

describe('obfuscate-string', function () {
  it('keeps the last n characters', function () {
    const inp = '123456789'
    const keep = 4
    const exp = '*****6789'
    expect(obfuscateString(inp, keep)).to.equal(exp)
  })

  it('keeps the last 3 characters by default', function () {
    const inp = '123456789'
    const exp = '******789'
    expect(obfuscateString(inp)).to.equal(exp)
  })
})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 43: 150 (1916)

#### Original name
Opegrapha chevallieri var. incarnata Riddle

### Remarks
null


text:
package core

import (
	"fmt"

	"github.com/etcinit/phabulous/app/interfaces"
	"github.com/etcinit/phabulous/app/messages"
)

// ModulesCommand allows one to send test messages to the feed channel.
type ModulesCommand struct{}

// GetUsage returns the usage of this command.
func (c *ModulesCommand) GetUsage() string {
	return "modules"
}

// GetDescription returns the description of this command.
func (c *ModulesCommand) GetDescription() string {
	return "Display a listing of all modules loaded."
}

// GetMatchers returns the matchers for this command.
func (c *ModulesCommand) GetMatchers() []string {
	return []string{}
}

// GetIMMatchers returns IM matchers for this command.
func (c *ModulesCommand) GetIMMatchers() []string {
	return []string{"^modules$"}
}

// GetMentionMatchers returns the channel mention matchers for this command.
func (c *ModulesCommand) GetMentionMatchers() []string {
	return []string{"modules"}
}

// GetHandler returns the handler for this command.
func (c *ModulesCommand) GetHandler() interfaces.Handler {
	return func(s interfaces.Bot, m interfaces.Message, matches []string) {
		message := "Loaded modules:\n"

		for _, module := range s.GetModules() {

			message = message + fmt.Sprintf(
				"• *%s*\n",
				module.GetName(),
			)
		}

		s.Post(m.GetChannel(), message, messages.IconTasks, true)
	}
}


text:
/*jslint browser:true */
/*global requirejs */

// define the dependencies with requirejs
requirejs.config({
    // baseUrl is implicitly relative to this file
    waitSeconds: 0,

    paths: {
        jquery: "../lib/jquery/jquery",
        angular: "../lib/angular/angular",
        'angular-animate': "../lib/angular-animate/angular-animate",
        'angular-sanitize': "../lib/angular-sanitize/angular-sanitize",
        'angular-resource': "../lib/angular-resource/angular-resource",
        'angular-ui-router': "../lib/angular-ui-router/angular-ui-router",
        'angular-strap': "../lib/angular-strap/angular-strap",
        'angular-strap-tpl': "../lib/angular-strap/angular-strap.tpl",
        marked: "../lib/marked/marked",
        fastclick: "../lib/fastclick/fastclick",
        moment: "../lib/moment/moment",
        underscore: "../lib/underscore/underscore",
        css: "../lib/require-css/css",
        less: "../lib/require-less/less",
        lessc: "../lib/require-less/lessc",
        normalize: "../lib/require-less/normalize",
        gapi: "../lib/gapi/index",
        'google-plus-signin': "../lib/angular-directive.g-signin/google-plus-signin",
        toaster: "../lib/AngularJS-Toaster/toaster"
    },

    shim: {
        angular: {
            deps: ['jquery'],
            exports: 'angular'
        },
        gapi: {
            exports: 'gapi'
        },
        'angular-animate': ['angular'],
        'angular-sanitize': ['angular'],
        'angular-resource': ['angular'],
        'angular-strap': ['angular', 'angular-animate'],
        'angular-strap-tpl': ['angular', 'angular-animate', 'angular-strap'],
        'angular-ui-router': ['angular'],
        'google-plus-signin': ['angular'],
        toaster: ['angular', 'angular-animate']
    },

    less: {
        relativeUrls: true
    }
});

// This is the main application entry point, invoked by requirejs
// bootstraps the angularjs app with the dom
requirejs([
    'angular',
    'app',
    'fastclick',
    'less!../less/main'
],
    function (angular, app, fastclick) {
        'use strict';

        angular.element().ready(function () {
            angular.bootstrap(document, [app.name]);
            fastclick.attach(document.body);
        });
    });


text:
class HomeWork < ActiveRecord::Base
	has_many :home_works_students
	has_many :students, through: :home_works_students

	scope :completed, -> { where status: 'submitted' }
end


text:
require 'heroku-api'

module HerokuResqueAutoScale
  module Scaler
    class << self
      def heroku
        Heroku::API.new(:api_key => ENV['HEROKU_API_KEY'])
      end

      def workers
        heroku.get_ps(ENV['HEROKU_APP']).body.count { |a| a["process"] =~ /worker/ }
      end

      def workers=(qty)
        heroku.post_ps_scale(ENV['HEROKU_APP'], :worker, qty)
      end

      def job_count
        Resque.info[:pending].to_i
      end

      def working_job_count
        Resque.info[:working].to_i
      end
    end
  end

  def after_perform_scale_down(*args)
    # Nothing fancy, just shut everything down if we have no pending jobs
    # and one working job (which is this job)
    Scaler.workers = 0 if Scaler.job_count.zero? && Scaler.working_job_count == 1
  end

  def after_enqueue_scale_up(*args)
    [
      {
        :workers => 1, # This many workers
        :job_count => 1 # For this many jobs or more, until the next level
      },
      {
        :workers => 2,
        :job_count => 15
      },
      {
        :workers => 3,
        :job_count => 25
      },
      {
        :workers => 4,
        :job_count => 40
      },
      {
        :workers => 5,
        :job_count => 60
      }
    ].reverse_each do |scale_info|
      # Run backwards so it gets set to the highest value first
      # Otherwise if there were 70 jobs, it would get set to 1, then 2, then 3, etc

      # If we have a job count greater than or equal to the job limit for this scale info
      if Scaler.job_count >= scale_info[:job_count]
        # Set the number of workers unless they are already set to a level we want. Don't scale down here!
        if Scaler.workers <= scale_info[:workers]
          Scaler.workers = scale_info[:workers]
        end
        break # We've set or ensured that the worker count is high enough
      end
    end
  end
end


text:
/**
 * Módulo secundario donacionesApp.formularioDonanteDonacion.
 * Dependencias: ninguna.
 * @author Roberto Sottini <robysottini@gmail.com>
 */

(function() {
    'use strict';

    angular
        .module('donacionesApp.formularioDonanteDonacion', []);
})();


text:
/* entity prototype */
(function( $ ) {

$.fn.candidates = function(data, options) {
    var $this = $(this);
    var $data = data;
    var selected=[];

    var settings = $.extend({
        maxEntities: 8
    }, options );

    this.initialize = function() {
        addCandidates($data);
        $this.delegate(".selector", "click", function() {
    		var candidateNode = $(this).parent();
    			id = candidateNode.attr("id"),
    			item = candidateNode.data();
    		toggleCandidate(id, item);
    	});
        return this;
    };

    function addCandidates(data) {
        if(data) {
    		for (var i=0; i < data.length; i++) {
    			var item = data[i],
    				title = item.label,
    				type = item.nerdType.substring(32);
    			$('
'
    				+'<button type="button" class="btn btn-default btn-sm selector">'
    				+''
    				+'</button>'
    				+'
'+title+'
'
    				+'
'+type+'
'
    				+'
'
    			).appendTo($this).data(item);
    		}
    	}
	}

	function toggleCandidate(id, item) {
		var maxEntities = settings.maxEntities,
		    index = selected.indexOf(id),
			iconNode = $("#"+id).find("span.glyphicon");
		if(index>=0) {
			selected = _.without(selected, id)
			iconNode.removeClass("glyphicon-minus")
				.addClass("glyphicon-plus");
			$this.trigger("entityRemove", {index:index});
		} else if(selected.length==maxEntities){
			alert("You already selected "+maxEntities+" entities.\nRemove one of the selected entities to add a new one.");
		} else {
			var next = selected.push(id);
			iconNode.removeClass("glyphicon-plus")
				.addClass("glyphicon-minus");
			$this.trigger("entityAdd", {index:next-1, id:id, title:item.label, uri:item.uri});
		}
	}

    this.update = function(data) {
        addCandidates(data);
    };

    return this.initialize();
}

}( jQuery ));


text:
#ifndef PIERFLIP_TOOL_INCLUDED
#define PIERFLIP_TOOL_INCLUDED

class PierFlipTool
{
public:
    static bool CanRunTool(wxString *error);
    static void ShowPierFlipCalTool();
    static void UpdateUIControls();
};

#endif


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

<info><title>AutoComplete</title></info>

    <para>
        Muchas bibliotecas de Javascript con
        <acronym>AJAX</acronym>
        ofrecen funcionalidad para
        proporcionar autocompletado según la cual un selectlist de
        resultados
        potencialmente concordantes se visualiza a medida que el usuario tipea.
        El ayudante
        <emphasis>AutoComplete</emphasis>
        pretende simplificar el retorno
        de respuestas aceptables a esos métodos.
    </para>

    <para>
        Dado que no todas la bibliotecas JS implementan el autocompletado de
        la misma manera, el
        ayudante
        <emphasis>AutoComplete</emphasis>
        ofrece algunas
        funcionalidades abstractas de base necesarias para muchas bibliotecas,
        e
        implementaciones concretas para distintas bibliotecas.
        Los tipos de datos de retorno son
        generalmente o bien arrays de strings
        <acronym>JSON</acronym>
        , array de arrays
        <acronym>JSON</acronym>
        (donde cada miembro del array está en un array
        asociativo de metadatos utilizado para crear
        la selectlist), o
        <acronym>HTML</acronym>
        .
    </para>

    <para>
        El uso básico para cada aplicación es el mismo:
   </para>

    <programlisting language="php"><![CDATA[
class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        // Ejecutar alguna lógica...

        // Codificar y enviar la respuesta;
        $this->_helper->autoCompleteDojo($data);

        // O explicitamente:
        $response = $this->_helper->autoCompleteDojo
                                  ->sendAutoCompletion($data);

        // O prepare simplemente la respuesta de autocompletado:
        $response = $this->_helper->autoCompleteDojo
                                  ->prepareAutoCompletion($data);
    }
}
]]></programlisting>

    <para>
        Por defecto, el autocompletado hace lo siguiente:
   </para>

    <itemizedlist>
        <listitem>
            <para>
                Desactiva esquemas y a ViewRenderer.
       </para>
        </listitem>

        <listitem>
            <para>
                Establece las cabeceras apropiadas para la respuesta.
       </para>
        </listitem>

        <listitem>
            <para>
                Establece el cuerpo de la respuesta con datos
                codificados o formateados para
                autocompletar.
       </para>
        </listitem>

        <listitem>
            <para>
                Envía la respuesta.
       </para>
        </listitem>
    </itemizedlist>

    <para>
        Los métodos disponibles para el ayudante incluyen:
   </para>

    <itemizedlist>
        <listitem>
            <para>
                <methodname>disableLayouts()</methodname>
                puede ser utilizada para
                desactivar esquemas y a ViewRenderer. Típicamente, esto se
                llama dentro de
                <methodname>prepareAutoCompletion()</methodname>
                .
            </para>
        </listitem>

        <listitem>
            <para>
                <methodname>encodeJson($data, $keepLayouts = false)</methodname>
                codificará datos a
                <acronym>JSON</acronym>
                , y opcionalmente habilitando o
                deshabilitando esquemas. Típicamente, esto se llama
                dentro de
                <methodname>prepareAutoCompletion()</methodname>
                .
            </para>
        </listitem>

        <listitem>
            <para>
                <methodname>prepareAutoCompletion($data, $keepLayouts = false)</methodname>
                se utiliza para preparar datos en el formato necesario de la
                respuesta para la
                aplicación concreta, opcionalmente los
                esquemas pueden habilitarse o deshabilitarse.
                El valor de retorno variará dependiendo de la implementación.
            </para>
        </listitem>

        <listitem>
            <para>
                <methodname>sendAutoCompletion($data, $keepLayouts = false)</methodname>
                se utiliza para preparar datos en el formato necesario de la
                respuesta para la
                aplicación concreta. Esta llama a
                <methodname>prepareAutoCompletion()</methodname>
                , y entonces envía la
                respuesta.
            </para>
        </listitem>

        <listitem>
            <para>
                <methodname>direct($data, $sendNow = true, $keepLayouts =
                    false)</methodname>
                se utiliza cuando se llama al ayudante como
                un método del ayudante intermediario. El flag
                <varname>$sendNow</varname>
                se utiliza para determinar si se debe
                llamar a
                <methodname>sendAutoCompletion()</methodname>
                o a
                <methodname>prepareAutoCompletion()</methodname>
                , respectivamente.
            </para>
        </listitem>
    </itemizedlist>

    <para>
        Actualmente,
        <emphasis>AutoComplete</emphasis>
        soporta las bibliotecas
        <acronym>AJAX</acronym>
        de
        Dojo y Scriptaculous.
    </para>

<info><title>AutoCompletado con Dojo</title></info>

        <para>
            Dojo no tiene un widget de autocompletado per se, pero tiene dos
            widgets que pueden
            ejecutar AutoCompletado: ComboBox y
            FilteringSelect. En ambos casos, necesitan de un
            almacén de datos
            que implemente QueryReadStore; para obtener más información sobre
            estos
            temas, ver la documentación en
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/data-retrieval-dojo-data-0">dojo.data</link>
        </para>

        <para>
            En Zend Framework, puede pasar un simple array indexado al ayudante
            AutoCompleteDojo, y
            este regresará una adecuada respuesta
            <acronym>JSON</acronym>
            para su uso como almacenamiento:
        </para>

        <programlisting language="php"><![CDATA[
// dentro del controlador de acción:
$this->_helper->autoCompleteDojo($data);
]]></programlisting>

        <example xml:id="zend.controller.actionhelpers.autocomplete.dojo.example1"><info><title>AutoCompletion con Dojo Usando Zend MVC</title></info>

            <para>
                AutoCompletion con Dojo via Zend
                <acronym>MVC</acronym>
                requiere varias cosas:
                generar un objeto form para el ComboBox en el que usted quiere
                AutoCompletado, un controlador de acción para prestar servicio
                a los resultados de
                AutoCompletion, creando un QueryReadStore
                personalizado para conectar a la acción
                AutoCompletion,
                y la generación del Javascript a utilizar en la inicializción
                de
                AutoCompletion del lado del servidor.
            </para>

            <para>
                En primer lugar, veamos el Javascript necesario. Dojo ofrece
                un marco completo para
                crear Javascript
                <acronym>OOP</acronym>
                , tal como lo hace
                Zend Framework para
                <acronym>PHP</acronym>
                . Parte de eso es la capacidad de
                crear pseudo-namespaces utilizando la jerarquía de
                directorios.
                Crearemos un directorio 'custom' en el mismo nivel en el cual
                el
                directorio de Dojo forma parte de la distribución Dojo.
                Dentro del directorio,
                crearemos un archivo Javascript,
                <filename>TestNameReadStore.js</filename>
                , con el siguiente contenido:
            </para>

            <programlisting language="javascript"><![CDATA[
dojo.provide("custom.TestNameReadStore");
dojo.declare("custom.TestNameReadStore", dojox.data.QueryReadStore, {
    fetch:function (request) {
        request.serverQuery = { test:request.query.name };
        return this.inherited("fetch", arguments);
    }
});
]]></programlisting>

            <para>
                Esta clase es simplemente una extensión del propio
                QueryReadStore de Dojo, que es
                de por sí misma una clase
                abstracta. Simplemente definimos un método por el cual
                realizamos la solicitud, y se le asigna al elemento 'test'.
           </para>

            <para>
                A continuación, vamos a crear el elemento form para el que
                queremos AutoCompletion:
           </para>

            <programlisting language="php"><![CDATA[
class TestController extends Zend_Controller_Action
{
    protected $_form;

    public function getForm()
    {
        if (null === $this->_form) {
            $this->_form = new Zend_Form();
            $this->_form->setMethod('get')
                ->setAction(
                    $this->getRequest()->getBaseUrl() . '/test/process'
                )
                ->addElements(array(
                    'test' => array('type' => 'text', 'options' => array(
                        'filters'        => array('StringTrim'),
                        'dojoType'       => array('dijit.form.ComboBox'),
                        'store'          => 'testStore',
                        'autoComplete'   => 'false',
                        'hasDownArrow'   => 'true',
                        'label' => 'Your input:',
                    )),
                    'go' => array('type' => 'submit',
                                  'options' => array('label' => 'Go!'))
                ));
        }
        return $this->_form;
    }
}
]]></programlisting>

            <para>
                Aquí, estamos simplemente creando un formulario con los métodos
                'test' y 'go'. El
                método 'test' agrega varios atributos
                especiales específicos de Dojo: dojoType,
                store,
                <emphasis>AutoComplete</emphasis>
                y hasDownArrow. El dojoType es utilizado para indicar que
                estamos creando un
                ComboBox, y que vamos a vincularlo
                a un almacén de datos (clave 'store') de
                'testStore'
                -- veremos más de esto más adelante.
                Especificando '
                <emphasis>AutoComplete</emphasis>
                ' como
                <constant>FALSE</constant>
                se le dice a Dojo que
                no seleccione automáticamente el primer acierto, sino mostrar
                una lista de aciertos. Por último, 'hasDownArrow' crea una
                flecha abajo similar a un
                select box para que podamos
                mostrar y ocultar los aciertos o concordancias.
            </para>

            <para>
                Vamos a añadir un método para mostrar la forma, así como un
                punto final para el
                procesamiento de AutoCompletion:
           </para>

            <programlisting language="php"><![CDATA[
class TestController extends Zend_Controller_Action
{
    // ...

    /**
     * Página final
     */
    public function indexAction()
    {
        $this->view->form = $this->getForm();
    }

    public function autocompleteAction()
    {
        if ('ajax' != $this->_getParam('format', false)) {
            return $this->_helper->redirector('index');
        }
        if ($this->getRequest()->isPost()) {
            return $this->_helper->redirector('index');
        }

        $match = trim($this->getRequest()->getQuery('test', ''));

        $matches = array();
        foreach ($this->getData() as $datum) {
            if (0 === strpos($datum, $match)) {
                $matches[] = $datum;
            }
        }
        $this->_helper->autoCompleteDojo($matches);
    }
}
]]></programlisting>

            <para>
                En nuestro
                <methodname>autocompleteAction()</methodname>
                hacemos una serie
                de cosas. En primer lugar, esperamos a asegurarnos de que
                tengamos
                una petición post, y que existe un parámetro 'form'
                establecido al valor 'ajax'; esto
                es simplemente para ayudar a
                reducir preguntas espúreas a la acción.
                A continuación,
                vamos a comprobar el parámetro 'test', y
                compararlo contra nuestros datos. (Yo
                deliberadamente dejé de
                lado la implementación de
                <methodname>getData()</methodname>
                aquí --
                podría ser cualquier tipo de fuente de datos). Por último,
                enviamos nuestros
                aciertos a nuestro ayudante AutoCompletion.
            </para>

            <para>
                Ahora que tenemos todas las piezas en el backend, veamos lo que
                necesitamos para
                entregar en nuestro script de vista para la
                página final.
                En primer lugar, necesitamos
                configurar nuestro data store,
                luego hacer nuestro formulario, y finalmente
                garantizar que
                las biblotecas Dojo apropiadas -- incluyendo que nuestro data
                store
                personalizado -- estén cargadas.
                Veamos el script de vista, el cual comenta los
                pasos:
           </para>

            <programlisting language="php"><![CDATA[
<?php // establecemos nuestro data store: ?>
<div dojoType="custom.TestNameReadStore" jsId="testStore"
    url="<?php echo $this->baseUrl() ?>/unit-test/autocomplete/format/ajax"
    requestMethod="get">

<?php // mostramos nuestro form: ?>
<?php echo $this->form ?>

<?php // establecemos CSS relacionado con Dojo a cargar en HTML head: ?>
<?php $this->headStyle()->captureStart() ?>
@import "<?php echo $this->baseUrl()
?>/javascript/dijit/themes/tundra/tundra.css";
@import "<?php echo $this->baseUrl() ?>/javascript/dojo/resources/dojo.css";
<?php $this->headStyle()->captureEnd() ?>

<?php // setup de javascript para cargar en HTML head, incluyendo todas las
   // bibliotecas Dojo requeridas: ?>
<?php $this->headScript()
        ->setAllowArbitraryAttributes(true)
        ->appendFile($this->baseUrl() . '/javascript/dojo/dojo.js',
            'text/javascript',
            array('djConfig' => 'parseOnLoad: true'))
        ->captureStart() ?>
djConfig.usePlainJson=true;
dojo.registerModulePath("custom","../custom");
dojo.require("dojo.parser");
dojo.require("dojox.data.QueryReadStore");
dojo.require("dijit.form.ComboBox");
dojo.require("custom.TestNameReadStore");
<?php $this->headScript()->captureEnd()
]]></programlisting>

            <para>
                Note que las llamadas a los ayudantes de vista como headStyle
                y headScript; son
                ubicadores, que podemos suministrar a la
                sección 'head' del
                <acronym>HTML</acronym>
                de nuestro script de vista.
            </para>

            <para>
                Ahora tenemos todas las piezas para que el AutoCompletion
                de Dojo pueda trabajar.
           </para>
        </example>

<info><title>AutoCompletion con Scriptaculous</title></info>

        <para>
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter">Scriptaculous</link>
            espera una respuesta
            <acronym>HTML</acronym>
            en un formato específico.
        </para>

        <para>
            El ayudante para utilizar con esta biblioteca es
            'AutoCompleteScriptaculous'. Simplemente
            proporcionarle un array de
            datos, y el ayudante creará una respuesta
            <acronym>HTML</acronym>
            compatible con
            Ajax.Autocompleter.
        </para>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 500 (1898)

#### Original name
Lophiostoma speciosum Ellis & Everh.

### Remarks
null


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

var port = process.env['PORT'] || 1883;

var counter = 0;
var interval = 5000;

function count() {
  console.log('[send]', Math.round(counter / interval * 1000), 'msg/s');
  counter = 0;
}

setInterval(count, interval);

var client = mqtt.connect({
  port: port,
  host: 'localhost',
  clean: true,
  keepalive: 0,
  encoding: 'binary'
});

function immediatePublish() {
  setImmediate(publish);
}

function publish() {
  counter++;
  client.publish('test', counter.toString(), immediatePublish);
}

client.on('connect', function(){
  console.log('[send] connected to', port);
  publish();
});


text:
using buzz::XmlAttr;
using buzz::XmlElement;

namespace remoting {

TEST(ServerLogEntryHostTest, MakeForSessionStateChange) {
  scoped_ptr<ServerLogEntry> entry(MakeLogEntryForSessionStateChange(true));
  scoped_ptr<XmlElement> stanza = entry->ToStanza();
  std::string error;
  std::map<std::string, std::string> key_value_pairs;
  key_value_pairs["role"] = "host";
  key_value_pairs["event-name"] = "session-state";
  key_value_pairs["session-state"] = "connected";
  std::set<std::string> keys;
  ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error))
      << error;
}

TEST(ServerLogEntryHostTest, MakeForHeartbeat) {
  scoped_ptr<ServerLogEntry> entry(MakeLogEntryForHeartbeat());
  scoped_ptr<XmlElement> stanza = entry->ToStanza();
  std::string error;
  std::map<std::string, std::string> key_value_pairs;
  key_value_pairs["role"] = "host";
  key_value_pairs["event-name"] = "heartbeat";
  std::set<std::string> keys;
  ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error))
      << error;
}

TEST(ServerLogEntryHostTest, AddHostFields) {
  scoped_ptr<ServerLogEntry> entry(MakeLogEntryForSessionStateChange(true));
  AddHostFieldsToLogEntry(entry.get());
  scoped_ptr<XmlElement> stanza = entry->ToStanza();
  std::string error;
  std::map<std::string, std::string> key_value_pairs;
  key_value_pairs["role"] = "host";
  key_value_pairs["event-name"] = "session-state";
  key_value_pairs["session-state"] = "connected";
  std::set<std::string> keys;
  keys.insert("cpu");
#if defined(OS_WIN)
  key_value_pairs["os-name"] = "Windows";
  keys.insert("os-version");
#elif defined(OS_MACOSX)
  key_value_pairs["os-name"] = "Mac";
  keys.insert("os-version");
#elif defined(OS_CHROMEOS)
  key_value_pairs["os-name"] = "ChromeOS";
  keys.insert("os-version");
#elif defined(OS_LINUX)
  key_value_pairs["os-name"] = "Linux";
#endif
  key_value_pairs["host-version"] = STRINGIZE(VERSION);
  ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) <<
      error;
}

TEST(ServerLogEntryHostTest, AddModeField1) {
  scoped_ptr<ServerLogEntry> entry(MakeLogEntryForSessionStateChange(true));
  entry->AddModeField(ServerLogEntry::IT2ME);
  scoped_ptr<XmlElement> stanza = entry->ToStanza();
  std::string error;
  std::map<std::string, std::string> key_value_pairs;
  key_value_pairs["role"] = "host";
  key_value_pairs["event-name"] = "session-state";
  key_value_pairs["session-state"] = "connected";
  key_value_pairs["mode"] = "it2me";
  std::set<std::string> keys;
  ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) <<
      error;
}

TEST(ServerLogEntryHostTest, AddModeField2) {
  scoped_ptr<ServerLogEntry> entry(MakeLogEntryForSessionStateChange(true));
  entry->AddModeField(ServerLogEntry::ME2ME);
  scoped_ptr<XmlElement> stanza = entry->ToStanza();
  std::string error;
  std::map<std::string, std::string> key_value_pairs;
  key_value_pairs["role"] = "host";
  key_value_pairs["event-name"] = "session-state";
  key_value_pairs["session-state"] = "connected";
  key_value_pairs["mode"] = "me2me";
  std::set<std::string> keys;
  ASSERT_TRUE(VerifyStanza(key_value_pairs, keys, stanza.get(), &error)) <<
      error;
}

}  // namespace remoting


text:
package org.drools.benchmarks.dmn.feel.functions;

import java.util.concurrent.TimeUnit;

import org.drools.benchmarks.dmn.feel.AbstractFEELBenchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Warmup;

@Warmup(iterations = 30, time = 200, timeUnit = TimeUnit.MILLISECONDS)
public class FEELCeilingFunctionBenchmark extends AbstractFEELBenchmark {

    @Param({"ceiling( 1.5 )", "ceiling( -1.5 )"})
    private String expression;

    @Override
    public String getExpression() {
        return expression;
    }
}


text:
SOAP Interop Round2 groupB 005 (soap/direct): echoNestedArray
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--INI--
precision=14
--FILE--
<?php
$param = new SoapParam(new SoapVar(array(
    new SoapVar("arg", XSD_STRING, null, null, "varString"),
    new SoapVar(34, XSD_INT, null, null, "varInt"),
    new SoapVar(325.325, XSD_FLOAT, null, null, "varFloat"),
    new SoapVar(array(
	    new SoapVar("red", XSD_STRING),
	    new SoapVar("blue", XSD_STRING),
	    new SoapVar("green", XSD_STRING),
    ), SOAP_ENC_ARRAY, "ArrayOfString", "http://soapinterop.org/xsd", 'varArray')
  ), SOAP_ENC_OBJECT, "SOAPArrayStruct", "http://soapinterop.org/xsd"), "inputStruct");
$client = new SoapClient(NULL,array("location"=>"test://","uri"=>"http://soapinterop.org/","trace"=>1,"exceptions"=>0));
$client->__soapCall("echoNestedArray", array($param), array("soapaction"=>"http://soapinterop.org/","uri"=>"http://soapinterop.org/"));
echo $client->__getlastrequest();
$HTTP_RAW_POST_DATA = $client->__getlastrequest();
include("round2_groupB.inc");
echo "ok\n";
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://soapinterop.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="http://soapinterop.org/xsd" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:echoNestedArray><inputStruct xsi:type="ns2:SOAPArrayStruct"><varString xsi:type="xsd:string">arg</varString><varInt xsi:type="xsd:int">34</varInt><varFloat xsi:type="xsd:float">325.325</varFloat><varArray SOAP-ENC:arrayType="xsd:string[3]" xsi:type="ns2:ArrayOfString"><item xsi:type="xsd:string">red</item><item xsi:type="xsd:string">blue</item><item xsi:type="xsd:string">green</item></varArray></inputStruct></ns1:echoNestedArray></SOAP-ENV:Body></SOAP-ENV:Envelope>
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://soapinterop.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="http://soapinterop.org/xsd" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:echoNestedArrayResponse><return xsi:type="ns2:SOAPArrayStruct"><varString xsi:type="xsd:string">arg</varString><varInt xsi:type="xsd:int">34</varInt><varFloat xsi:type="xsd:float">325.325</varFloat><varArray SOAP-ENC:arrayType="xsd:string[3]" xsi:type="ns2:ArrayOfstring"><item xsi:type="xsd:string">red</item><item xsi:type="xsd:string">blue</item><item xsi:type="xsd:string">green</item></varArray></return></ns1:echoNestedArrayResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
ok


text:
package org.drools.examples.traits;

import org.drools.factmodel.traits.Thing;

public class ScholarImpl<K> implements Scholar<K> {

    private Thing<K> core;

    public ScholarImpl() {

    }

    public ScholarImpl( Thing<K> arg ) {
        this.core = arg;
    }

    public void learn( String subject ) {
        System.out.println( "I " + core.getFields().get( "name" ) + ", now know everything about " + subject );
    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using vivego.MessageBroker.Abstractions;

namespace vivego.MessageBroker.EventStore;

public interface IEventStore
{
	Task<long> Append(
		string topic,
		byte[] data,
		TimeSpan? timeToLive = default,
		IDictionary<string, string>? metaData = default,
		CancellationToken cancellationToken = default);

	Task<EventSourceEvent?> GetEvent(
		string topic,
		long eventId,
		CancellationToken cancellationToken);

	Task<long> GetNextEventId(string topic, CancellationToken cancellationToken = default);

	IAsyncEnumerable<EventSourceEvent> StreamingGet(
		string topic,
		long? fromId,
		CancellationToken cancellationToken = default);
}


text:
package main

import (
	"time"

	"github.com/faiface/pixel"
	"github.com/faiface/pixel/imdraw"
	"github.com/faiface/pixel/pixelgl"
	"golang.org/x/image/colornames"

	"github.com/hueypark/framework/core/random"
	"github.com/hueypark/physics/core"
	"github.com/hueypark/physics/core/body"
	"github.com/hueypark/physics/core/math/rotator"
	"github.com/hueypark/physics/core/math/vector"
	"github.com/hueypark/physics/core/shape/bullet"
	"github.com/hueypark/physics/core/shape/circle"
	"github.com/hueypark/physics/core/shape/convex"
	"github.com/hueypark/physics/examples/util"
)

const WINDOW_WIDTH = 1024
const WINDOW_HEIGHT = 768

func main() {
	pixelgl.Run(run)
}

func run() {
	cfg := pixelgl.WindowConfig{
		Title:  "Rigidbody",
		Bounds: pixel.R(-WINDOW_WIDTH/2, -WINDOW_HEIGHT/2, WINDOW_WIDTH/2, WINDOW_HEIGHT/2),
		VSync:  true,
	}
	win, err := pixelgl.NewWindow(cfg)
	if err != nil {
		panic(err)
	}
	imd := imdraw.New(nil)

	world := physics.New()
	plane := createConvex(
		[]vector.Vector{
			{300, -100},
			{300, -120},
			{-300, -100},
			{-300, -120},
		},
		vector.Vector{0, -200},
		rotator.ZERO(),
		vector.Vector{})
	plane.SetStatic()
	world.Add(plane)

	delta := time.Second / 30
	ticker := time.NewTicker(delta)
	respawnTime := time.Duration(0)
	for range ticker.C {
		if win.Closed() {
			break
		}

		const RESPAWN_TIME = time.Millisecond * 500
		respawnTime -= delta

		if respawnTime < 0 {
			respawnTime = RESPAWN_TIME
			world.Add(
				createRandomShape(
					vector.Vector{random.FRandom(-300, 300), 0},
					rotator.Rotator{random.FRandom(180.0, 360.0)},
					vector.Vector{0, 0}))
		}

		world.Tick(delta.Seconds())

		win.Clear(colornames.Black)
		imd.Clear()

		util.DrawWorld(imd, world)

		for _, b := range world.Bodys() {
			if isOutbound(b.Position()) {
				world.ReservedDelete(b.Id())
			}
		}

		imd.Draw(win)

		win.Update()
	}
}

func createRandomShape(position vector.Vector, rotation rotator.Rotator, velocity vector.Vector) *body.Body {
	var b *body.Body
	switch random.Random(0, 2) {
	case 0:
		b = createBullet(position, velocity)
	case 1:
		b = createCircle(random.FRandom(10, 50), position, velocity)
	case 2:
		b = createConvex(
			[]vector.Vector{
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
				{random.FRandom(-50, 50), random.FRandom(-50, 50)},
			},
			position,
			rotation,
			velocity)
	}

	return b
}

func createBullet(position vector.Vector, velocity vector.Vector) *body.Body {
	b := body.New()
	b.SetMass(1)
	b.SetShape(bullet.New())
	b.SetPosition(position)
	b.Velocity = velocity

	return b
}

func createCircle(radius float64, position vector.Vector, velocity vector.Vector) *body.Body {
	b := body.New()
	b.SetMass(1)
	b.SetShape(&circle.Circle{radius})
	b.SetPosition(position)
	b.Velocity = velocity

	return b
}

func createConvex(vertices []vector.Vector, position vector.Vector, rotation rotator.Rotator, velocity vector.Vector) *body.Body {
	b := body.New()
	b.SetMass(1)
	b.SetShape(convex.New(vertices))
	b.SetPosition(position)
	b.SetRotation(rotation)
	b.Velocity = velocity

	return b
}

func isOutbound(position vector.Vector) bool {
	const MARGIN = 300
	if position.X < -WINDOW_WIDTH/2-MARGIN ||
		position.X > WINDOW_WIDTH/2+MARGIN ||
		position.Y < -WINDOW_HEIGHT/2-MARGIN ||
		position.Y > WINDOW_HEIGHT/2+MARGIN {
		return true
	}
	return false
}


text:
package com.boot.subsidios.controller;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.boot.subsidios.model.Imputacion;
import com.boot.subsidios.repository.ImputacionStub;

@RestController
@RequestMapping("api/v1/")
public class ImputacionController {

	@RequestMapping(value = "imputaciones", method = RequestMethod.GET)
	public List<Imputacion> list() {
		return ImputacionStub.list();
	}

	@RequestMapping(value = "imputaciones/{id}", method = RequestMethod.GET)
	public Imputacion get(@PathVariable long id) {
		return ImputacionStub.get(id);
	}

	@RequestMapping(value = "imputaciones", method = RequestMethod.POST)
	public Imputacion create(@RequestBody Imputacion imputacion) {
		return ImputacionStub.create(imputacion);
	}

	@RequestMapping(value = "imputaciones/{id}", method = RequestMethod.PUT)
	public Imputacion update(@PathVariable long id, @RequestBody Imputacion imputacion) {
		return ImputacionStub.update(id, imputacion);
	}

	@RequestMapping(value = "imputaciones/{id}", method = RequestMethod.DELETE)
	public Imputacion delete(@PathVariable long id) {
		return ImputacionStub.delete(id);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example 11</title>

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

                mobile ready, touch swipe

                finger catchable right to left

                responsive, scale smoothly

                random caption transition

                mobile ready, touch swipe

                finger catchable right to left

                responsive, scale smoothly

                random caption transition

                mobile ready, touch swipe

                finger catchable right to left

        Image Slider


text:
import DashboardSpeakersContainer from 'components/DashboardSpeakers/DashboardSpeakersContainer'
import DashboardSpeakersData from 'components/DashboardSpeakers/DashboardSpeakersData'
import DashboardSpeakersPresentation from 'components/DashboardSpeakers/DashboardSpeakersPresentation'

export default {
  Container: DashboardSpeakersContainer,
  Data: DashboardSpeakersData,
  Presentation: DashboardSpeakersPresentation,
}


text:
package pkg.xfl.binary;

import xfuzzy.lang.*;

public class lukasiewicz extends Binary {
 public lukasiewicz() {
   super("xfl","lukasiewicz");
   Parameter single[] = new Parameter[0];
   setSingleParameters(single);
  }

 public double compute(double a, double b) {
 return (b<a? 1-a+b : 1);
  }

 public double[] derivative(double a, double b) {
   double[] deriv = new double[2];
  deriv[0] = (b<a? -1 : (a==b? -0.5 : 0));
  deriv[1] = (b<a? 1 : (a==b? 0.5 : 0));
   return deriv;
  }

 public boolean test () {
   return true;
  }

 public String getJavaCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (b<a? 1-a+b : 1); "+eol;
   return code;
  }

 public String getCCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (b<a? 1-a+b : 1); "+eol;
   return code;
  }

 public String getCppCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (b<a? 1-a+b : 1); "+eol;
   return code;
  }
}


text:
'use strict';

(function() {
	// Complaints Controller Spec
	describe('Complaints Controller Tests', function() {
		// Initialize global variables
		var ComplaintsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Complaints controller.
			ComplaintsController = $controller('ComplaintsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Complaint object fetched from XHR', inject(function(Complaints) {
			// Create sample Complaint using the Complaints service
			var sampleComplaint = new Complaints({
				name: 'New Complaint'
			});

			// Create a sample Complaints array that includes the new Complaint
			var sampleComplaints = [sampleComplaint];

			// Set GET response
			$httpBackend.expectGET('complaints').respond(sampleComplaints);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.complaints).toEqualData(sampleComplaints);
		}));

		it('$scope.findOne() should create an array with one Complaint object fetched from XHR using a complaintId URL parameter', inject(function(Complaints) {
			// Define a sample Complaint object
			var sampleComplaint = new Complaints({
				name: 'New Complaint'
			});

			// Set the URL parameter
			$stateParams.complaintId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/complaints\/([0-9a-fA-F]{24})$/).respond(sampleComplaint);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.complaint).toEqualData(sampleComplaint);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Complaints) {
			// Create a sample Complaint object
			var sampleComplaintPostData = new Complaints({
				name: 'New Complaint'
			});

			// Create a sample Complaint response
			var sampleComplaintResponse = new Complaints({
				_id: '525cf20451979dea2c000001',
				name: 'New Complaint'
			});

			// Fixture mock form input values
			scope.name = 'New Complaint';

			// Set POST response
			$httpBackend.expectPOST('complaints', sampleComplaintPostData).respond(sampleComplaintResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Complaint was created
			expect($location.path()).toBe('/complaints/' + sampleComplaintResponse._id);
		}));

		it('$scope.update() should update a valid Complaint', inject(function(Complaints) {
			// Define a sample Complaint put data
			var sampleComplaintPutData = new Complaints({
				_id: '525cf20451979dea2c000001',
				name: 'New Complaint'
			});

			// Mock Complaint in scope
			scope.complaint = sampleComplaintPutData;

			// Set PUT response
			$httpBackend.expectPUT(/complaints\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/complaints/' + sampleComplaintPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid complaintId and remove the Complaint from the scope', inject(function(Complaints) {
			// Create new Complaint object
			var sampleComplaint = new Complaints({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Complaints array and include the Complaint
			scope.complaints = [sampleComplaint];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/complaints\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleComplaint);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.complaints.length).toBe(0);
		}));
	});
}());


text:
(function () {
	"use strict";
	var ObjectProto = Object.prototype,
	defineGetter = ObjectProto.__defineGetter__,
	defineSetter = ObjectProto.__defineSetter__,
	lookupGetter = ObjectProto.__lookupGetter__,
	lookupSetter = ObjectProto.__lookupSetter__,
	hasOwnProp = ObjectProto.hasOwnProperty;

	if (defineGetter && defineSetter && lookupGetter && lookupSetter) {

		if (!Object.defineProperty) {
			Object.defineProperty = function (obj, prop, descriptor) {
				if (arguments.length < 3) { // all arguments required
					throw new TypeError("Arguments not optional");
				}

				prop += ""; // convert prop to string

				if (hasOwnProp.call(descriptor, "value")) {
					if (!lookupGetter.call(obj, prop) && !lookupSetter.call(obj, prop)) {
						// data property defined and no pre-existing accessors
						obj[prop] = descriptor.value;
					}

					if ((hasOwnProp.call(descriptor, "get") ||
					     hasOwnProp.call(descriptor, "set")))
					{
						// descriptor has a value prop but accessor already exists
						throw new TypeError("Cannot specify an accessor and a value");
					}
				}

				if (descriptor.get) {
					defineGetter.call(obj, prop, descriptor.get);
				}
				if (descriptor.set) {
					defineSetter.call(obj, prop, descriptor.set);
				}

				return obj;
			};
		}

		if (!Object.getOwnPropertyDescriptor) {
			Object.getOwnPropertyDescriptor = function (obj, prop) {
				if (arguments.length < 2) { // all arguments required
					throw new TypeError("Arguments not optional.");
				}

				prop += ""; // convert prop to string

				var descriptor = {
					configurable: true,
					enumerable  : true,
					writable    : true
				},
				getter = lookupGetter.call(obj, prop),
				setter = lookupSetter.call(obj, prop);

				if (!hasOwnProp.call(obj, prop)) {
					// property doesn't exist or is inherited
					return descriptor;
				}
				if (!getter && !setter) { // not an accessor so return prop
					descriptor.value = obj[prop];
					return descriptor;
				}

				// there is an accessor, remove descriptor.writable;
				// populate descriptor.get and descriptor.set (IE's behavior)
				delete descriptor.writable;
				descriptor.get = descriptor.set = undefined;

				if (getter) {
					descriptor.get = getter;
				}
				if (setter) {
					descriptor.set = setter;
				}

				return descriptor;
			};
		}

		if (!Object.defineProperties) {
			Object.defineProperties = function (obj, props) {
				for (var prop in props) {
					if (hasOwnProp.call(props, prop)) {
						Object.defineProperty(obj, prop, props[prop]);
					}
				}
			};
		}

	}
}());


text:
package org.apache.camel.component.ssh;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

import org.apache.camel.CamelContext;
import org.apache.camel.support.ResourceHelper;
import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider;
import org.apache.sshd.common.util.io.IoUtils;
import org.apache.sshd.common.util.security.SecurityUtils;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This host key provider loads private keys from the specified resources using
 * {@link ResourceHelper}, and Camel's resource syntax for file:, classpath:, and http:.
 * {@link ResourceHelper}, and Camel's resource syntax for file:, classpath:, and http:.
 *
 * Note that this class has a direct dependency on BouncyCastle and won't work
 * unless it has been correctly registered as a security provider.
 */
public class ResourceHelperKeyPairProvider extends AbstractKeyPairProvider {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    private CamelContext camelContext;
    private String[] resources;
    private Supplier<char[]> passwordFinder;

    public ResourceHelperKeyPairProvider() {
    }

    public ResourceHelperKeyPairProvider(String[] resources,
                                         CamelContext camelContext) {
        this.camelContext = camelContext;
        this.resources = resources;
    }

    public ResourceHelperKeyPairProvider(String[] resources,
                                         Supplier<char[]> passwordFinder,
                                         CamelContext camelContext) {
        this.camelContext = camelContext;
        this.resources = resources;
        this.passwordFinder = passwordFinder;
    }

    public CamelContext getCamelContext() {
        return camelContext;
    }

    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }

    public String[] getResources() {
        return resources;
    }

    public void setResources(String[] resources) {
        this.resources = resources;
    }

    public Supplier<char[]> getPasswordFinder() {
        return passwordFinder;
    }

    public void setPasswordFinder(Supplier<char[]> passwordFinder) {
        this.passwordFinder = passwordFinder;
    }

    @Override
    public Iterable<KeyPair> loadKeys() {
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
        }

        final List<KeyPair> keys =
                new ArrayList<>(this.resources.length);

        for (String resource : resources) {
            PEMParser r = null;
            InputStreamReader isr = null;
            InputStream is = null;
            try {
                is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, resource);
                isr = new InputStreamReader(is);
                r = new PEMParser(isr);

                Object o = r.readObject();

                JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
                pemConverter.setProvider("BC");
                if (passwordFinder != null && o instanceof PEMEncryptedKeyPair) {
                    JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
                    PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(passwordFinder.get());
                    o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
                }

                if (o instanceof PEMKeyPair) {
                    o = pemConverter.getKeyPair((PEMKeyPair)o);
                    keys.add((KeyPair) o);
                } else if (o instanceof KeyPair) {
                    keys.add((KeyPair) o);
                }

            } catch (Exception e) {
                log.warn("Unable to read key", e);
            } finally {
                IoUtils.closeQuietly(r, is, isr);
            }
        }

        return keys;
    }

}


text:
module Pohoda
  module Builders
    module MKasa
      class ImportRequestType
        include ParserCore::BaseBuilder

        def builder
          root = Ox::Element.new(name)
          root = add_attributes_and_namespaces(root)

          root << build_element('mKasa:mKasaPackNum', data[:m_kasa_pack_num], data[:m_kasa_pack_num_attributes]) if data.key? :m_kasa_pack_num
          root << build_element('mKasa:name', data[:name], data[:name_attributes]) if data.key? :name
          root << build_element('mKasa:deviceGuid', data[:device_guid], data[:device_guid_attributes]) if data.key? :device_guid
          root << build_element('mKasa:overwriteDeviceGuid', data[:overwrite_device_guid], data[:overwrite_device_guid_attributes]) if data.key? :overwrite_device_guid

          root
        end
      end
    end
  end
end