text:
<?php

/**
 * New products widget
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Block_Product_Widget_New extends Mage_Catalog_Block_Product_New
    implements Mage_Widget_Block_Interface
{
    /**
     * Display products type
     */
    const DISPLAY_TYPE_ALL_PRODUCTS         = 'all_products';
    const DISPLAY_TYPE_NEW_PRODUCTS         = 'new_products';

    /**
     * Default value whether show pager or not
     */
    const DEFAULT_SHOW_PAGER                = false;

    /**
     * Default value for products per page
     */
    const DEFAULT_PRODUCTS_PER_PAGE         = 5;

    /**
     * Name of request parameter for page number value
     */
    const PAGE_VAR_NAME                     = 'np';

    /**
     * Instance of pager block
     *
     * @var Mage_Catalog_Block_Product_Widget_Html_Pager
     */
    protected $_pager;

    /**
     * Default product amount per row
     *
     * @var int
     */
    protected $_defaultColumnCount = 5;

    /**
     * Initialize block's cache and template settings
     */
    protected function _construct()
    {
        parent::_construct();
        $this->addPriceBlockType('bundle', 'bundle/catalog_product_price', 'bundle/catalog/product/price.phtml');
    }

    /**
     * Product collection initialize process
     *
     * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
     */
    protected function _getProductCollection()
    {
        switch ($this->getDisplayType()) {
            case self::DISPLAY_TYPE_NEW_PRODUCTS:
                $collection = parent::_getProductCollection();
                break;
            default:
                $collection = $this->_getRecentlyAddedProductsCollection();
                break;
        }
        return $collection;
    }

    /**
     * Prepare collection for recent product list
     *
     * @return Mage_Catalog_Model_Resource_Product_Collection|Object|Varien_Data_Collection
     */
    protected function _getRecentlyAddedProductsCollection()
    {
        /** @var $collection Mage_Catalog_Model_Resource_Product_Collection */
        $collection = Mage::getResourceModel('catalog/product_collection');
        $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

        $collection = $this->_addProductAttributesAndPrices($collection)
            ->addStoreFilter()
            ->addAttributeToSort('created_at', 'desc')
            ->setPageSize($this->getProductsCount())
            ->setCurPage(1)
        ;
        return $collection;
    }

    /**
     * Get key pieces for caching block content
     *
     * @return array
     */
    public function getCacheKeyInfo()
    {
        return array_merge(parent::getCacheKeyInfo(), array(
            $this->getDisplayType(),
            $this->getProductsPerPage(),
            intval($this->getRequest()->getParam(self::PAGE_VAR_NAME))
        ));
    }

    /**
     * Retrieve display type for products
     *
     * @return string
     */
    public function getDisplayType()
    {
        if (!$this->hasData('display_type')) {
            $this->setData('display_type', self::DISPLAY_TYPE_ALL_PRODUCTS);
        }
        return $this->getData('display_type');
    }

    /**
     * Retrieve how much products should be displayed
     *
     * @return int
     */
    public function getProductsCount()
    {
        if (!$this->hasData('products_count')) {
            return parent::getProductsCount();
        }
        return $this->getData('products_count');
    }

    /**
     * Retrieve how much products should be displayed
     *
     * @return int
     */
    public function getProductsPerPage()
    {
        if (!$this->hasData('products_per_page')) {
            $this->setData('products_per_page', self::DEFAULT_PRODUCTS_PER_PAGE);
        }
        return $this->getData('products_per_page');
    }

    /**
     * Return flag whether pager need to be shown or not
     *
     * @return bool
     */
    public function showPager()
    {
        if (!$this->hasData('show_pager')) {
            $this->setData('show_pager', self::DEFAULT_SHOW_PAGER);
        }
        return (bool)$this->getData('show_pager');
    }

    /**
     * Render pagination HTML
     *
     * @return string
     */
    public function getPagerHtml()
    {
        if ($this->showPager()) {
            if (!$this->_pager) {
                $this->_pager = $this->getLayout()
                    ->createBlock('catalog/product_widget_html_pager', 'widget.new.product.list.pager');

                $this->_pager->setUseContainer(true)
                    ->setShowAmounts(true)
                    ->setShowPerPage(false)
                    ->setPageVarName(self::PAGE_VAR_NAME)
                    ->setLimit($this->getProductsPerPage())
                    ->setTotalLimit($this->getProductsCount())
                    ->setCollection($this->getProductCollection());
            }
            if ($this->_pager instanceof Mage_Core_Block_Abstract) {
                return $this->_pager->toHtml();
            }
        }
        return '';
    }
}


text:
"""
Created on 2015-04-02T21:43:57
"""

from __future__ import division, print_function
from collections import defaultdict
import fiona
from shapely.geometry import shape
from shapely.geometry import Point

import nhrc2
from nhrc2.backend import read_issues as ri

__author__ = "Matt Giguere (github: @mattgiguere)"
__license__ = "MIT"
__version__ = '0.0.1'
__maintainer__ = "Matt Giguere"
__email__ = "matthew.giguere@yale.edu"
__status__ = " Development NOT(Prototype or Production)"

#the project root directory:
nhrc2dir = ('/').join(nhrc2.__file__.split('/')[:-1])+'/'

def match_neighborhoods(scf_df, neighborhoods):
    hoods = []
    for idx in scf_df.index:
        grid_point = Point(scf_df.loc[idx, 'lng'], scf_df.loc[idx, 'lat'])
        for hoodnum, hood in enumerate(neighborhoods):
            if grid_point.within(neighborhoods[hood]):
                hoods.append(hood)
                break
            if hoodnum == 19:
                #There are 20 neighborhoods. If you are the 20th (element 19 in
                #zero-based indexing) and have not continued out of the iteration
                #set the neighborhood name to "Other":
                hoods.append('Other')
    return hoods

def get_neighborhoods(readfile=False, scf_df=''):
    """
    PURPOSE: To take in a pandas DataFrame of issues and a dictionary with the
    shapes and names of the New Haven neighborhoods and output a list
    containing the neighborhood for each issue.
    """
    if len(scf_df) == 0:
        scf_df = ri.get_issues(readfile=readfile)

    #now get the GIS data for the neighborhoods:
    rgns = fiona.open(nhrc2dir+'data/nh_neighborhoods/nh_neighborhoods.shp')

    nhv_geom = defaultdict()

    for rec in rgns:
        #print(rec['geometry']['type'])
        hood = rec['properties']['name']
        nhv_geom[hood] = shape(rec['geometry'])

    hoods = match_neighborhoods(scf_df, nhv_geom)

    return hoods

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.typeconverter.impl;

import jodd.typeconverter.TypeConversionException;
import jodd.typeconverter.TypeConverter;
import jodd.util.ArraysUtil;

import java.sql.Clob;
import java.sql.SQLException;

/**
 * Converts given object to String.
 * Conversion rules:
 *

 *
null value is returned as null

 *
for CharSequence type returns toString value

 *
Class returns cass name

 *
char[] is used for creating string

 *
arrays are converted to comma-separated list of toString values

 *
Clob is converted

 *
finally, toString() value is returned.

 *

 */
public class StringConverter implements TypeConverter<String> {

	public String convert(Object value) {
		if (value == null) {
			return null;
		}

		if (value instanceof CharSequence) {	// for speed
			return value.toString();
		}
		Class type = value.getClass();
		if (type == Class.class) {
			return ((Class) value).getName();
		}
		if (type.isArray()) {
			if (type == char[].class) {
				char[] charArray = (char[]) value;
				return new String(charArray);
			}

			if (type == int[].class) {
				return ArraysUtil.toString((int[]) value);
			}
			if (type == long[].class) {
				return ArraysUtil.toString((long[]) value);
			}
			if (type == byte[].class) {
				return ArraysUtil.toString((byte[]) value);
			}
			if (type == float[].class) {
				return ArraysUtil.toString((float[]) value);
			}
			if (type == double[].class) {
				return ArraysUtil.toString((double[]) value);
			}
			if (type == short[].class) {
				return ArraysUtil.toString((short[]) value);
			}
			if (type == boolean[].class) {
				return ArraysUtil.toString((boolean[]) value);
			}
			return ArraysUtil.toString((Object[])value);
		}
		if (value instanceof Clob) {
			Clob clob = (Clob) value;
			try {
				long length = clob.length();
				if (length > Integer.MAX_VALUE) {
					throw new TypeConversionException("Clob is too big.");
				}
				return clob.getSubString(1, (int) length);
			} catch (SQLException sex) {
				throw new TypeConversionException(value, sex);
			}
		}
		return value.toString();
	}

}


text:
/**
 * Redis Sentinel API for reactive command execution.
 */
package io.lettuce.core.sentinel.api.reactive;


text:
[class^="icon-"], [class*=" icon-"] {
  font-family: 'icone';
  font-style: normal;
  font-weight: normal;

  /* fix buttons height */
  line-height: 1em;

  /* you can be more comfortable with increased icons size */
  /* font-size: 120%; */
}

.icon-search { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-mail-alt { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-star { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-users { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-link { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-right-big { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-left-big { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-facebook-squared { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-gplus { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }
.icon-twitter { *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = ' '); }


text:
"""
   Copyright 2010 Daniel Graziotin <daniel.graziotin@acm.org>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

"""
This module holds the Modality model
"""

from django.db import models, IntegrityError
import copy

MODE_CHOICES = (
    (u'auto', u'Auto'),
    (u'van', u'Van'),
    (u'bus', u'Bus'),
)

class Modality(models.Model):
    """
    Represents additional information about the modality of transportation being used.
    See  See `Modality <http://dycapo.org/Protocol#Modality>`_ for more info.
    """
    kind = models.CharField(max_length=255, choices=MODE_CHOICES, blank=False, null=False, default=MODE_CHOICES[0][0])
    capacity = models.PositiveIntegerField(blank=False, null=False, default=0)
    vacancy = models.IntegerField(blank=False, null=False, default=0)
    make = models.CharField(max_length=255, blank=True)
    model_name = models.CharField(max_length=255, blank=True)
    year = models.PositiveIntegerField(blank=True, null=False, default=0)
    color = models.CharField(max_length=255, blank=True)
    lic = models.CharField(max_length=255, blank=True)
    cost = models.FloatField(blank=True, null=False, default=0.00)
    person = models.ForeignKey('Person', blank=True, null=True)
    href = models.URLField(verify_exists=False, blank=True, null=False)

    def save(self, * args, ** kwargs):
        if not self.kind or not self.capacity or self.vacancy < 0 or not self.make or not self.model_name:
            raise IntegrityError('Attributes kind, capacity, vacancy, make, model_name MUST be given.')
        super(Modality, self).save(*args, **kwargs)

    def to_xmlrpc(self):
        """
        Returns a Python dict that contains just the attributes we want to expose
        in out XML-RPC methods
        """
        mode_dict = copy.deepcopy(self.__dict__)
        del mode_dict['id']
        del mode_dict['_state']
        return mode_dict

    class Meta:
        app_label = 'server'


text:
var Entry, HTML, History, URL, createHistory, createLocation, createWindow, hashChange, parentFrom;

createWindow = require("./window");

HTML = require("jsdom").defaultLevel;

URL = require("url");

createHistory = function(browser, focus) {
  var history;
  history = new History(browser, focus);
  return history.open.bind(history);
};

parentFrom = function(window) {
  if (window.parent !== window.getGlobal()) {
    return window.parent;
  }
};

Entry = (function() {
  function Entry(window, url, pushState) {
    this.window = window;
    this.pushState = pushState;
    this.url = URL.format(url);
    this.next = this.prev = null;
  }

  Entry.prototype.destroy = function(keepAlive) {
    if (this.next) {
      this.next.destroy(keepAlive || this.window);
      this.next = null;
    }
    if (keepAlive === this.window) {
      return;
    }
    if (this.prev && this.prev.window === this.window) {
      return;
    }
    return this.window._destroy();
  };

  Entry.prototype.append = function(newEntry, keepAlive) {
    if (this.next) {
      this.next.destroy(keepAlive);
    }
    newEntry.prev = this;
    return this.next = newEntry;
  };

  return Entry;

})();

History = (function() {
  function History(browser, focus) {
    this.browser = browser;
    this.focus = focus;
    this.first = this.current = null;
  }

  History.prototype.open = function(options) {
    var window;
    options.browser = this.browser;
    options.history = this;
    window = createWindow(options);
    this.addEntry(window, options.url);
    return window;
  };

  History.prototype.destroy = function() {
    var first;
    this.focus(null);
    first = this.first;
    this.first = this.current = null;
    if (first) {
      return first.destroy();
    }
  };

  History.prototype.addEntry = function(window, url, pushState) {
    var entry;
    url || (url = window.location.href);
    entry = new Entry(window, url, pushState);
    this.updateLocation(window, url);
    this.focus(window);
    if (this.current) {
      this.current.append(entry);
      return this.current = entry;
    } else {
      return this.current = this.first = entry;
    }
  };

  History.prototype.replaceEntry = function(window, url, pushState) {
    var entry;
    url || (url = window.location.href);
    entry = new Entry(window, url, pushState);
    this.updateLocation(window, url);
    this.focus(window);
    if (this.current === this.first) {
      if (this.current) {
        this.current.destroy(window);
      }
      return this.current = this.first = entry;
    } else {
      this.current.prev.append(entry, window);
      return this.current = entry;
    }
  };

  History.prototype.updateLocation = function(window, url) {
    var history;
    if (/^(about|file|https?|javascript):/.test(url)) {
      history = this;
      return Object.defineProperty(window, "location", {
        get: function() {
          return createLocation(history, url);
        },
        set: function(url) {
          return history.assign(url);
        },
        enumerable: true
      });
    } else {
      throw new Error("Cannot load resource " + url + ", unsupported protocol");
    }
  };

  History.prototype.submit = function(options) {
    var newWindow, window;
    options.browser = this.browser;
    options.history = this;
    if (window = this.current.window) {
      options.name = window.name;
      options.parent = parentFrom(window);
      options.referer = window.URL;
    }
    newWindow = createWindow(options);
    return this.addEntry(newWindow, options.url);
  };

  History.prototype.__defineGetter__("url", function() {
    var _ref;
    return (_ref = this.current) != null ? _ref.url : void 0;
  });

  History.prototype.assign = function(url) {
    var event, name, parent, window;
    if (this.current) {
      url = HTML.resourceLoader.resolve(this.current.window.document, url);
      name = this.current.window.name;
      parent = parentFrom(this.current.window);
    }
    if (this.current && this.current.url === url) {
      this.replace(url);
      return;
    }
    if (hashChange(this.current, url)) {
      window = this.current.window;
      this.addEntry(window, url);
      event = window.document.createEvent("HTMLEvents");
      event.initEvent("hashchange", true, false);
      window._eventQueue.enqueue(function() {
        return window.dispatchEvent(event);
      });
    } else {
      window = createWindow({
        browser: this.browser,
        history: this,
        name: name,
        url: url,
        parent: parent,
        referer: this.current.window.document.referrer
      });
      this.addEntry(window, url);
    }
  };

  History.prototype.replace = function(url) {
    var event, name, window;
    url = URL.format(url);
    if (this.current) {
      url = HTML.resourceLoader.resolve(this.current.window.document, url);
      name = this.current.window.name;
    }
    if (hashChange(this.current, url)) {
      window = this.current.window;
      this.replaceEntry(window, url);
      event = window.document.createEvent("HTMLEvents");
      event.initEvent("hashchange", true, false);
      window._eventQueue.enqueue(function() {
        return window.dispatchEvent(event);
      });
    } else {
      window = createWindow({
        browser: this.browser,
        history: this,
        name: name,
        url: url,
        parent: parentFrom(this.current.window)
      });
      this.replaceEntry(window, url);
    }
  };

  History.prototype.reload = function() {
    var newWindow, url, window;
    if (window = this.current.window) {
      url = window.location.href;
      newWindow = createWindow({
        browser: this.browser,
        history: this,
        name: window.name,
        url: url
      }, {
        parent: parentFrom(window),
        referer: window.referrer
      });
      return this.replaceEntry(newWindow, url);
    }
  };

  History.prototype.go = function(amount) {
    var event, newHost, oldHost, was, window;
    was = this.current;
    while (amount > 0) {
      if (this.current.next) {
        this.current = this.current.next;
      }
      --amount;
    }
    while (amount < 0) {
      if (this.current.prev) {
        this.current = this.current.prev;
      }
      ++amount;
    }
    if (this.current && was && this.current !== was) {
      window = this.current.window;
      this.updateLocation(window, this.current.url);
      this.focus(window);
      if (this.current.pushState || was.pushState) {
        oldHost = URL.parse(was.url).host;
        newHost = URL.parse(this.current.url).host;
        if (oldHost === newHost) {
          event = window.document.createEvent("HTMLEvents");
          event.initEvent("popstate", false, false);
          event.state = this.current.pushState;
          window._eventQueue.enqueue(function() {
            return window.dispatchEvent(event);
          });
        }
      } else if (hashChange(was, this.current.url)) {
        event = window.document.createEvent("HTMLEvents");
        event.initEvent("hashchange", true, false);
        window._eventQueue.enqueue(function() {
          return window.dispatchEvent(event);
        });
      }
    }
  };

  History.prototype.__defineGetter__("length", function() {
    var entry, length;
    entry = this.first;
    length = 0;
    while (entry) {
      ++length;
      entry = entry.next;
    }
    return length;
  });

  History.prototype.pushState = function(state, title, url) {
    url || (url = this.current.window.location.href);
    url = HTML.resourceLoader.resolve(this.current.window.document, url);
    this.addEntry(this.current.window, url, state || {});
  };

  History.prototype.replaceState = function(state, title, url) {
    url || (url = this.current.window.location.href);
    url = HTML.resourceLoader.resolve(this.current.window.document, url);
    this.replaceEntry(this.current.window, url, state || {});
  };

  History.prototype.__defineGetter__("state", function() {
    if (this.current.pushState) {
      return this.current.pushState;
    }
  });

  History.prototype.dump = function() {
    var cur, dump, i, line;
    cur = this.first;
    i = 1;
    dump = (function() {
      var _results;
      _results = [];
      while (cur) {
        line = cur.next ? '#' + i + ': ' : i + '. ';
        line += URL.format(cur.url);
        cur = cur.next;
        ++i;
        _results.push(line);
      }
      return _results;
    })();
    return dump;
  };

  return History;

})();

hashChange = function(entry, url) {
  var aBase, aHash, bBase, bHash, _ref, _ref1;
  if (!entry) {
    return false;
  }
  _ref = url.split("#"), aBase = _ref[0], aHash = _ref[1];
  _ref1 = entry.url.split("#"), bBase = _ref1[0], bHash = _ref1[1];
  return aBase === bBase && aHash !== bHash;
};

createLocation = function(history, url) {
  var browser, location, prop, _fn, _i, _len, _ref;
  browser = history.browser;
  location = new Object();
  Object.defineProperties(location, {
    assign: {
      value: function(url) {
        return browser.eventLoop.next(function() {
          return history.assign(url);
        });
      }
    },
    replace: {
      value: function(url) {
        return browser.eventLoop.next(function() {
          return history.replace(url);
        });
      }
    },
    reload: {
      value: function(force) {
        return browser.eventLoop.next(function() {
          return history.reload();
        });
      }
    },
    toString: {
      value: function() {
        return url;
      },
      enumerable: true
    },
    hostname: {
      get: function() {
        return URL.parse(url).hostname;
      },
      set: function(hostname) {
        var newUrl;
        newUrl = URL.parse(url);
        if (newUrl.port) {
          newUrl.host = "" + hostname + ":" + newUrl.port;
        } else {
          newUrl.host = hostname;
        }
        return location.assign(URL.format(newUrl));
      },
      enumerable: true
    },
    href: {
      get: function() {
        return url;
      },
      set: function(href) {
        return location.assign(URL.format(href));
      },
      enumerable: true
    }
  });
  _ref = ["hash", "host", "pathname", "port", "protocol", "search"];
  _fn = (function(_this) {
    return function(prop) {
      return Object.defineProperty(location, prop, {
        get: function() {
          return URL.parse(url)[prop] || "";
        },
        set: function(value) {
          var newUrl;
          newUrl = URL.parse(url);
          newUrl[prop] = value;
          return location.assign(URL.format(newUrl));
        },
        enumerable: true
      });
    };
  })(this);
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    prop = _ref[_i];
    _fn(prop);
  }
  return location;
};

module.exports = createHistory;


text:
    <a href="<?php if($lang!='vn') echo site_url($lang."/".$l->lang_url_home[$lang])?>" class="first"><?php echo $l->lang_home[$lang]?>
        <a href="<?php echo site_url($lang."/dang-nhap-cua-hang")?>" class="last"> <?php echo "Đăng nhập cửa hàng"?>

    <?php $this->load->view("front/block/col-banner")?>

<?php echo "Đăng nhập của hàng"?>

    <form action="" method="post">

            Email
            <input type="text" name="email" class="input" id="email">
            <?php echo form_error("email")?>
            <?php echo $l->lang_password[$lang]?>
            <input type="password" name="password" class="input" id="pass">
            <?php echo form_error("password")?>
            <a href="<?php echo site_url($lang."/".$l->lang_url_forgot_pass[$lang])?>" class="forgot-pass ajax "><?php echo $l->lang_forgot_pass[$lang]?>

                <input type="button" class="btn" value="<?php echo $l->lang_login[$lang]?>" onclick="LoginMod()">

    </form>


text:
webctl
===================
[![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://tldrlegal.com/license/mit-license)

What is this?
-------------
A few scripts I use to setup new nginx instances.

Install
------------------
* `sudo git clone https://github.com/kiu/webctl /opt/webctl`
* Add `include /www/*/etc/*.nginx;` to your `nginx.conf` `http` config

Usage
------------------

#### ./bin/generate-domain.sh <FQDN>
* Setup a basic configuration under `/www/<reversed FQDN>/`
* Reloading webserver to activate new configuration

#### ./bin/generate-ssl.sh <FQDN>
* Generate basic https configuration for `./bin/generate-domain.sh` generated domains
* Retrieve letsencrypt certificate (assuming a letsencrypt install under /opt/letsencrypt)
* Reloading webserver to activate new configuration

#### ./bin/reload_webserver.sh
* Used by the other scripts to reload the webserver configuration

#### ./bin/letsencrypt-renew.sh
* Auto-renew letencrypt certificates through cron: `ln -s /opt/webctl/bin/letsencrypt-renew.sh /etc/cron.daily/`

#### ./conf/nginx-www
* Make new directory structure known to logrotate
* `ln -s /opt/webctl/conf/nginx-www /etc/logrotate.d`

License
------------------

Contents are MIT Licensed, see the LICENSE file for more info.


text:
"""
Internal module for console introspection
"""

import sys
import locale
from pandas.io.formats.terminal import get_terminal_size

# -----------------------------------------------------------------------------
# Global formatting options
_initial_defencoding = None

def detect_console_encoding():
    """
    Try to find the most capable encoding supported by the console.
    slighly modified from the way IPython handles the same issue.
    """
    global _initial_defencoding

    encoding = None
    try:
        encoding = sys.stdout.encoding or sys.stdin.encoding
    except AttributeError:
        pass

    # try again for something better
    if not encoding or 'ascii' in encoding.lower():
        try:
            encoding = locale.getpreferredencoding()
        except Exception:
            pass

    # when all else fails. this will usually be "ascii"
    if not encoding or 'ascii' in encoding.lower():
        encoding = sys.getdefaultencoding()

    # GH3360, save the reported defencoding at import time
    # MPL backends may change it. Make available for debugging.
    if not _initial_defencoding:
        _initial_defencoding = sys.getdefaultencoding()

    return encoding

def get_console_size():
    """Return console size as tuple = (width, height).

    Returns (None,None) in non-interactive session.
    """
    from pandas import get_option
    from pandas.core import common as com

    display_width = get_option('display.width')
    # deprecated.
    display_height = get_option('display.height', silent=True)

    # Consider
    # interactive shell terminal, can detect term size
    # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term
    # size non-interactive script, should disregard term size

    # in addition
    # width,height have default values, but setting to 'None' signals
    # should use Auto-Detection, But only in interactive shell-terminal.
    # Simple. yeah.

    if com.in_interactive_session():
        if com.in_ipython_frontend():
            # sane defaults for interactive non-shell terminal
            # match default for width,height in config_init
            from pandas.core.config import get_default_val
            terminal_width = get_default_val('display.width')
            terminal_height = get_default_val('display.height')
        else:
            # pure terminal
            terminal_width, terminal_height = get_terminal_size()
    else:
        terminal_width, terminal_height = None, None

    # Note if the User sets width/Height to None (auto-detection)
    # and we're in a script (non-inter), this will return (None,None)
    # caller needs to deal.
    return (display_width or terminal_width, display_height or terminal_height)


text:
<?php

// load bootstrap
return require "framework.php";


text:
package testcapnp

//go:generate capnp compile -I ../../../std -ogo test.capnp


text:
import Reflux from 'reflux';

import {UserActions} from '../actions';

export default Reflux.createStore({
	listenables: UserActions,

	init: function() {
		this.users = [];
		this.params = {};
	},

	onSearchUsers: function(params) {
		this.params = params;
	},

	onSearchUsersCompleted: function(users) {
		this.users = users;
		this.trigger();
	},

	onCreateUserCompleted: function(response) {
		UserActions.searchUsers(this.params, this.users.length);
	},

	onRemoveUserCompleted: function(response) {
		UserActions.searchUsers(this.params, this.users.length);
	},
});


text:
Pub/Sub Overview

  The gcloud.pubsub method will return a pubsub object, allowing you to create topics, publish messages, subscribe to topics, and more.

  To learn more about Pub/Sub, see the Google Cloud Pub/Sub overview.


text: Codified Likeness Utility


text:
body { background-color: #fff; color: #333; }

body, p, ol, ul, td {
  font-family: verdana, arial, helvetica, sans-serif;
  font-size:   13px;
  line-height: 18px;
}

pre {
  background-color: #eee;
  padding: 10px;
  font-size: 11px;
}

a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }

.fieldWithErrors {
  padding: 2px;
  background-color: red;
  display: table;
}

#errorExplanation {
  width: 400px;
  border: 2px solid red;
  padding: 7px;
  padding-bottom: 12px;
  margin-bottom: 20px;
  background-color: #f0f0f0;
}

#errorExplanation h2 {
  text-align: left;
  font-weight: bold;
  padding: 5px 5px 5px 15px;
  font-size: 12px;
  margin: -7px;
  background-color: #c00;
  color: #fff;
}

#errorExplanation p {
  color: #333;
  margin-bottom: 0;
  padding: 5px;
}

#errorExplanation ul li {
  font-size: 12px;
  list-style: square;
}

/* --Uploadify -- */
.uploadifyQueueItem {
	font: 11px Verdana, Geneva, sans-serif;
	border: 2px solid #E5E5E5;
	background-color: #F5F5F5;
	margin-top: 5px;
	padding: 10px;
	width: 350px;
}
.uploadifyError {
	border: 2px solid #FBCBBC !important;
	background-color: #FDE5DD !important;
}
.uploadifyQueueItem .cancel {
	float: right;
}
.uploadifyProgress {
	background-color: #FFFFFF;
	border-top: 1px solid #808080;
	border-left: 1px solid #808080;
	border-right: 1px solid #C5C5C5;
	border-bottom: 1px solid #C5C5C5;
	margin-top: 10px;
	width: 100%;
}
.uploadifyProgressBar {
	background-color: #0099FF;
	width: 1px;
	height: 3px;
}
#fileQueue .uploadifyQueueItem {
	font: 11px Verdana, Geneva, sans-serif;
	border: none;
	border-bottom: 1px solid #E5E5E5;
	background-color: #FFFFFF;
	padding: 5%;
	width: 90%;
}
#fileQueue .uploadifyError {
	background-color: #FDE5DD !important;
}
#fileQueue .uploadifyQueueItem .cancel {
	float: right;
}


text:
package com.emajliramokade
package services
package impl

import image.proto.ImageProvjera.{ Odgovor, Zahtjev }

import hr.ngs.patterns.ISerialization

class CRemoteImageVerifier()
    extends abstracts.RemoteImageVerifier
    with    RemotingZeroMQ[Zahtjev] {
  def serviceUrlFactory(t: Zahtjev) = "tcp://144.76.184.25:10030"
}


text:
package com.googlecode.jmxtrans.model.output;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Injector;
import com.googlecode.jmxtrans.cli.JmxTransConfiguration;
import com.googlecode.jmxtrans.guice.JmxTransModule;
import com.googlecode.jmxtrans.model.JmxProcess;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.ResultAttribute;

import com.googlecode.jmxtrans.util.ProcessConfigUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDB.ConsistencyLevel;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static com.google.common.collect.Sets.immutableEnumSet;
import static com.googlecode.jmxtrans.model.QueryFixtures.dummyQuery;
import static com.googlecode.jmxtrans.model.ServerFixtures.dummyServer;
import static com.googlecode.jmxtrans.model.output.InfluxDbWriter.TAG_HOSTNAME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link InfluxDbWriter}.
 *
 * @author github.com/sihutch
 */

@RunWith(MockitoJUnitRunner.class)
public class InfluxDbWriterTests {

	private static final String DATABASE_NAME = "database";
	private static final String HOST = "host.example.net";
	private static final ImmutableMap<String, String> DEFAULT_CUSTOM_TAGS = ImmutableMap.of();
	private static final ImmutableList<String> DEFAULT_TYPE_NAMES = ImmutableList.of();

	@Mock
	private InfluxDB influxDB;
	@Captor
	private ArgumentCaptor<BatchPoints> messageCaptor;

	private static final ConsistencyLevel DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.ALL;
	private static final String DEFAULT_RETENTION_POLICY = "default";
	private static final ImmutableSet<ResultAttribute> DEFAULT_RESULT_ATTRIBUTES = immutableEnumSet(EnumSet.allOf(ResultAttribute.class));

	Result result = new Result(2l, "attributeName", "className", "objDomain", "keyAlias", "type=test,name=name",
			ImmutableMap.of("key", (Object) 1));
	ImmutableList<Result> results = ImmutableList.of(result);

	@Test
	public void pointsAreWrittenToInfluxDb() throws Exception {
		InfluxDbWriter writer = getTestInfluxDbWriterWithDefaultSettings();
		writer.doWrite(dummyServer(), dummyQuery(), results);

		verify(influxDB).write(messageCaptor.capture());
		BatchPoints batchPoints = messageCaptor.getValue();

		assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME);

		// Point only exposes its state via a line protocol so we have to
		// make assertions against this.
		// Format is:
		// measurement,<comma separated key=val tags>" " <comma separated
		// key=val fields>
		Map<String, String> expectedTags = new TreeMap<String, String>();
		expectedTags.put(enumValueToAttribute(ResultAttribute.ATTRIBUTE_NAME), result.getAttributeName());
		expectedTags.put(enumValueToAttribute(ResultAttribute.CLASS_NAME), result.getClassName());
		expectedTags.put(enumValueToAttribute(ResultAttribute.OBJ_DOMAIN), result.getObjDomain());
		expectedTags.put(TAG_HOSTNAME, HOST);
		String lineProtocol = buildLineProtocol(result.getKeyAlias(), expectedTags);

		List<Point> points = batchPoints.getPoints();
		assertThat(points).hasSize(1);

		Point point = points.get(0);
		assertThat(point.lineProtocol()).startsWith(lineProtocol);
	}

	@Test
	public void emptyCustomTagsDoesntBotherWrite() throws Exception {
		InfluxDbWriter writer = getTestInfluxDbWriterWithDefaultSettings();
		writer.doWrite(dummyServer(), dummyQuery(), results);
		verify(influxDB).write(messageCaptor.capture());
		BatchPoints batchPoints = messageCaptor.getValue();

		assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME);
		List<Point> points = batchPoints.getPoints();
		assertThat(points).hasSize(1);
	}

	@Test
	public void customTagsAreWrittenToDb() throws Exception {
		ImmutableMap<String, String> tags = ImmutableMap.of("customTag", "customValue");
		InfluxDbWriter writer = getTestInfluxDbWriterWithCustomTags(tags);
		writer.doWrite(dummyServer(), dummyQuery(), results);

		verify(influxDB).write(messageCaptor.capture());
		BatchPoints batchPoints = messageCaptor.getValue();

		assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME);
		List<Point> points = batchPoints.getPoints();
		assertThat(points).hasSize(1);

		Point point = points.get(0);
		assertThat(point.lineProtocol()).contains("customTag=customValue");
	}

	@Test
	public void attributeNameIncludesTypeNames() throws Exception {
		ImmutableList<String> typeNames = ImmutableList.of("name");
		InfluxDbWriter writer = getTestInfluxDbWriterWithTypeNames(typeNames);
		writer.doWrite(dummyServer(), dummyQuery(), results);

		verify(influxDB).write(messageCaptor.capture());
		BatchPoints batchPoints = messageCaptor.getValue();

		assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME);
		List<Point> points = batchPoints.getPoints();
		assertThat(points).hasSize(1);

		Point point = points.get(0);
		assertThat(point.lineProtocol()).contains("name.key");
	}

	@Test
	public void writeConsistencyLevelsAreAppliedToBatchPointsBeingWritten() throws Exception {
		for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) {
			InfluxDbWriter writer = getTestInfluxDbWriterWithWriteConsistency(consistencyLevel);

			writer.doWrite(dummyServer(), dummyQuery(), results);

			verify(influxDB, atLeastOnce()).write(messageCaptor.capture());
			BatchPoints batchPoints = messageCaptor.getValue();
			assertThat(batchPoints.getConsistency()).isEqualTo(consistencyLevel);
		}
	}

	@Test
	public void onlyRequestedResultPropertiesAreAppliedAsTags() throws Exception {
		for (ResultAttribute expectedResultTag : ResultAttribute.values()) {
			ImmutableSet<ResultAttribute> expectedResultTags = ImmutableSet.of(expectedResultTag);
			InfluxDbWriter writer = getTestInfluxDbWriterWithResultTags(expectedResultTags);
			writer.doWrite(dummyServer(), dummyQuery(), results);

			verify(influxDB, atLeastOnce()).write(messageCaptor.capture());
			BatchPoints batchPoints = messageCaptor.getValue();
			String lineProtocol = batchPoints.getPoints().get(0).lineProtocol();

			assertThat(lineProtocol).contains(enumValueToAttribute(expectedResultTag));
			EnumSet<ResultAttribute> unexpectedResultTags = EnumSet.complementOf(EnumSet.of(expectedResultTag));
			for (ResultAttribute unexpectedResultTag : unexpectedResultTags) {
				assertThat(lineProtocol).doesNotContain(enumValueToAttribute(unexpectedResultTag));
			}
		}
	}

	@Test
	public void databaseIsCreated() throws Exception {
		InfluxDbWriter writer = getTestInfluxDbWriterWithDefaultSettings();
		writer.doWrite(dummyServer(), dummyQuery(), results);

		verify(influxDB).createDatabase(DATABASE_NAME);
	}

	@Test
	public void databaseIsNotCreated() throws Exception {
		InfluxDbWriter writer = getTestInfluxDbWriterNoDatabaseCreation();
		writer.doWrite(dummyServer(), dummyQuery(), results);

		verify(influxDB, never()).createDatabase(anyString());
	}

	@Test
	public void loadingFromFile() throws URISyntaxException, IOException {
		File input = new File(InfluxDbWriterTests.class.getResource("/influxDB.json").toURI());
		Injector injector = JmxTransModule.createInjector(new JmxTransConfiguration());
		ProcessConfigUtils processConfigUtils = injector.getInstance(ProcessConfigUtils.class);
		JmxProcess process = processConfigUtils.parseProcess(input);
		assertThat(process.getName()).isEqualTo("influxDB.json");
	}

	private String buildLineProtocol(String measurement, Map<String, String> expectedTags) {
		StringBuilder sb = new StringBuilder(measurement).append(",");
		int loops = 0;
		int tagCount = expectedTags.size();
		for (Map.Entry<String, String> entry : expectedTags.entrySet()) {
			loops++;
			sb.append(entry.getKey()).append("=").append(entry.getValue());
			if (loops < tagCount) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

	private InfluxDbWriter getTestInfluxDbWriterWithDefaultSettings() {
		return getTestInfluxDbWriter(DEFAULT_CONSISTENCY_LEVEL, DEFAULT_RETENTION_POLICY, DEFAULT_CUSTOM_TAGS, DEFAULT_RESULT_ATTRIBUTES, DEFAULT_TYPE_NAMES,true);
	}

	private InfluxDbWriter getTestInfluxDbWriterWithResultTags(ImmutableSet<ResultAttribute> resultTags) {
		return getTestInfluxDbWriter(DEFAULT_CONSISTENCY_LEVEL, DEFAULT_RETENTION_POLICY, DEFAULT_CUSTOM_TAGS, resultTags, DEFAULT_TYPE_NAMES,true);
	}

	private InfluxDbWriter getTestInfluxDbWriterWithCustomTags(ImmutableMap<String, String> tags) {
		return getTestInfluxDbWriter(DEFAULT_CONSISTENCY_LEVEL, DEFAULT_RETENTION_POLICY, tags, DEFAULT_RESULT_ATTRIBUTES, DEFAULT_TYPE_NAMES,true);
	}

	private InfluxDbWriter getTestInfluxDbWriterWithTypeNames(ImmutableList<String> typeNames) {
		return getTestInfluxDbWriter(DEFAULT_CONSISTENCY_LEVEL, DEFAULT_RETENTION_POLICY, DEFAULT_CUSTOM_TAGS, DEFAULT_RESULT_ATTRIBUTES, typeNames,true);
	}

	private InfluxDbWriter getTestInfluxDbWriterWithWriteConsistency(ConsistencyLevel consistencyLevel) {
		return getTestInfluxDbWriter(consistencyLevel, DEFAULT_RETENTION_POLICY, DEFAULT_CUSTOM_TAGS, DEFAULT_RESULT_ATTRIBUTES, DEFAULT_TYPE_NAMES,true);
	}

	private InfluxDbWriter getTestInfluxDbWriterNoDatabaseCreation() {
		return getTestInfluxDbWriter(DEFAULT_CONSISTENCY_LEVEL, DEFAULT_RETENTION_POLICY, DEFAULT_CUSTOM_TAGS, DEFAULT_RESULT_ATTRIBUTES, DEFAULT_TYPE_NAMES,false);
	}

	private InfluxDbWriter getTestInfluxDbWriter(ConsistencyLevel consistencyLevel, String retentionPolicy, ImmutableMap<String, String> tags,
												 ImmutableSet<ResultAttribute> resultTags, ImmutableList<String> typeNames, boolean createDatabase) {
		return new InfluxDbWriter(influxDB, DATABASE_NAME, consistencyLevel, retentionPolicy, tags, resultTags, typeNames, createDatabase);
	}

	private String enumValueToAttribute(ResultAttribute attribute) {
		String[] split = attribute.name().split("_");
		return StringUtils.lowerCase(split[0]) + WordUtils.capitalizeFully(split[1]);
	}
}


text:
using UnityEngine;
using Devdayo.FSM;

namespace Devdayo.Platformer2D.Bot
{
    [RequireComponent(typeof(Tween))]
    public class BotFSM : MonoBehaviour
    {
        private StateMachine<BotFSM> machine;

        internal Rigidbody2D rigidbody;
        internal Animator animator;

        public Collider2D boxCollider;
        public Collider2D polyCollider;

        public Tween tween;

        public float moveSpeed = 3;
        public float jumpPower = 6;

        public bool immortal = false;

        void Awake()
        {
            rigidbody = GetComponent<Rigidbody2D>();
            animator = GetComponent<Animator>();

            machine = new StateMachine<BotFSM>(this);
        }

        void Start()
        {
            machine.Go<OnMove>();
        }

    }
}


text:
using namespace boost::python;

EulerGrid2D::EulerGrid2D(int size, float viscocity, float time)
	:m_size(size), m_viscocity(viscocity), m_time(time)
{
    u = new Velocity2D(size);
    v = new Velocity2D(size);
    density = new Velocity2D(size);
}

EulerGrid2D::~EulerGrid2D()
{
    if (u) delete u;
    if (v) delete v;
    if (density) delete density;
}

void EulerGrid2D::ExportClass()
{
	class_<EulerGrid2D>("EulerGrid2D", init<int, float, float>())
		.def("getCurU", &EulerGrid2D::getCurU)
		.def("getCurV", &EulerGrid2D::getCurV)
		.def("getCurDensity", &EulerGrid2D::getCurDensity)
		.def("getPreU", &EulerGrid2D::getPreU)
		.def("getPreV", &EulerGrid2D::getPreV)
		.def("getPreDensity", &EulerGrid2D::getPreDensity)
		.def("setCurU", &EulerGrid2D::setCurU)
		.def("setCurV", &EulerGrid2D::setCurV)
		.def("setCurDensity", &EulerGrid2D::setCurDensity)
		.def("setPreU", &EulerGrid2D::setPreU)
		.def("setPreV", &EulerGrid2D::setPreV)
		.def("setPreDensity", &EulerGrid2D::setPreDensity);
}

EulerGrid3D::EulerGrid3D( int size, float viscocity, float time )
	:m_size(size), m_viscocity(viscocity), m_time(time)
{
	u = new Velocity3D(size);
	v = new Velocity3D(size);
	w = new Velocity3D(size);
	density = new Velocity3D(size);
}

EulerGrid3D::~EulerGrid3D()
{
	if (u) delete u;
	if (v) delete v;
	if (w) delete w;
	if (density) delete density;
}

void EulerGrid3D::ExportClass()
{
	class_<EulerGrid3D>("EulerGrid3D", init<int, float, float>())
		.def("getCurU", &EulerGrid3D::getCurU)
		.def("getCurV", &EulerGrid3D::getCurV)
		.def("getCurW", &EulerGrid3D::getCurW)
		.def("getCurDensity", &EulerGrid3D::getCurDensity)
		.def("getPreU", &EulerGrid3D::getPreU)
		.def("getPreV", &EulerGrid3D::getPreV)
		.def("getPreW", &EulerGrid3D::getPreW)
		.def("getPreDensity", &EulerGrid3D::getPreDensity)
		.def("setCurU", &EulerGrid3D::setCurU)
		.def("setCurV", &EulerGrid3D::setCurV)
		.def("setCurW", &EulerGrid3D::setCurW)
		.def("setCurDensity", &EulerGrid3D::setCurDensity)
		.def("setPreU", &EulerGrid3D::setPreU)
		.def("setPreV", &EulerGrid3D::setPreV)
		.def("setPreW", &EulerGrid3D::setPreW)
		.def("setPreDensity", &EulerGrid3D::setPreDensity);
}


text:
import glob
import sys

if __name__ == '__main__':
    summaries = []

    def summarise(fname):
        summary = {}
        with open(fname) as fd:
            for line in fd:
                splitline = line.strip().split(' ')
                if len(splitline) == 1:
                    continue
                status = splitline[0]
                test = splitline[-1]
                # track bench runs
                if splitline[1] == 'ns/iter':
                    status = 'bench'
                if status not in summary:
                    summary[status] = []
                summary[status].append(test)
            summaries.append((fname, summary))

    def count(t):
        return sum(map(lambda (f, s): len(s.get(t, [])), summaries))

    logfiles = sys.argv[1:]
    for files in map(glob.glob, logfiles):
        map(summarise, files)
    ok = count('ok')
    failed = count('failed')
    ignored = count('ignored')
    measured = count('bench')
    print "summary of %d test runs: %d passed; %d failed; %d ignored; %d measured" % \
          (len(logfiles), ok, failed, ignored, measured)
    print ""

    if failed > 0:
        print "failed tests:"
        for f, s in summaries:
            failures = s.get('failed', [])
            if len(failures) > 0:
                print "  %s:" % (f)
            for test in failures:
                print "    %s" % (test)


text:
def whyrun_supported?
  true
end

def mailbox
  new_resource.mailbox
end

def password
  new_resource.password
end

def active
  new_resource.active
end

def mail
  new_resource.mail
end

def login_username
  new_resource.login_username
end

def login_password
  new_resource.login_password
end

def db_type
  new_resource.db_type(
    if new_resource.db_type.nil?
      node['postfixadmin']['database']['type']
    else
      new_resource.db_type
    end
  )
end

def db_user
  new_resource.db_user(
    if new_resource.db_user.nil?
      node['postfixadmin']['database']['user']
    else
      new_resource.db_user
    end
  )
end

def db_password
  new_resource.db_password(
    if new_resource.db_password.nil?
      encrypted_attribute_read(%w(postfixadmin database password))
    else
      new_resource.db_password
    end
  )
end

def default_db_port
  case db_type
  when 'mysql'
    node['mysql']['port']
  when 'postgresql'
    node['postgresql']['config']['port']
  else
    fail "Port for \"#{db_type}\" type not known."
  end
end

def db_port
  new_resource.db_port(
    if new_resource.db_port.nil?
      default_db_port
    else
      new_resource.db_port
    end
  )
end

def db_name
  new_resource.db_name(
    if new_resource.db_name.nil?
      node['postfixadmin']['database']['name']
    else
      new_resource.db_name
    end
  )
end

def db_host
  new_resource.db_host(
    if new_resource.db_host.nil?
      node['postfixadmin']['database']['host']
    else
      new_resource.db_host
    end
  )
end

def ssl
  new_resource.ssl(
    if new_resource.ssl.nil?
      node['postfixadmin']['ssl']
    else
      new_resource.ssl
    end
  )
end

def port
  new_resource.port(
    if new_resource.port.nil?
      node['postfixadmin']['port']
    else
      new_resource.port
    end
  )
end

action :create do
  self.class.send(:include, Chef::EncryptedAttributesHelpers)
  @encrypted_attributes_enabled = node['postfixadmin']['encrypt_attributes']
  username, domain = mailbox.split('@', 2)
  if domain.nil?
    fail Chef::Exceptions::ArgumentError,
         'Could not get the domain name from the mailbox argument, it should '\
         'have the following format: user@domain.tld'
  end
  db = PostfixAdmin::DB.new(
    type: db_type, user: db_user, password: db_password, dbname: db_name,
    host: db_host, port: db_port
  )
  next if db.mailbox_exist?(mailbox)
  converge_by("Create #{new_resource}") do
    ruby_block "create mailbox #{mailbox}" do
      block do
        api = PostfixAdmin::API.new(ssl, port, login_username, login_password)
        result = api.create_mailbox(
          username, domain, password, mailbox, active, mail
        )
        Chef::Log.info("Created #{new_resource}: #{result}")
      end
      action :create
    end
  end
end


text:
namespace performance_manager::user_tuning {
namespace {

class ProfileDiscardOptOutListHelperDelegateImpl
    : public ProfileDiscardOptOutListHelper::Delegate {
 public:
  ~ProfileDiscardOptOutListHelperDelegateImpl() override = default;

  void ClearPatterns(const std::string& browser_context_id) override {
    performance_manager::PerformanceManager::CallOnGraph(
        FROM_HERE,
        base::BindOnce(
            [](std::string browser_context_id,
               performance_manager::Graph* graph) {
              policies::PageDiscardingHelper::GetFromGraph(graph)
                  ->ClearNoDiscardPatternsForProfile(browser_context_id);
            },
            browser_context_id));
  }

  void SetPatterns(const std::string& browser_context_id,
                   const std::vector<std::string>& patterns) override {
    performance_manager::PerformanceManager::CallOnGraph(
        FROM_HERE, base::BindOnce(
                       [](std::string browser_context_id,
                          std::vector<std::string> patterns,
                          performance_manager::Graph* graph) {
                         policies::PageDiscardingHelper::GetFromGraph(graph)
                             ->SetNoDiscardPatternsForProfile(
                                 browser_context_id, patterns);
                       },
                       browser_context_id, std::move(patterns)));
  }
};

}  // namespace

ProfileDiscardOptOutListHelper::ProfileDiscardOptOutTracker::
    ProfileDiscardOptOutTracker(const std::string& browser_context_id,
                                PrefService* pref_service,
                                raw_ptr<Delegate> delegate)
    : browser_context_id_(browser_context_id), delegate_(delegate) {
  pref_change_registrar_.Init(pref_service);

  pref_change_registrar_.Add(
      performance_manager::user_tuning::prefs::kTabDiscardingExceptions,
      base::BindRepeating(&ProfileDiscardOptOutListHelper::
                              ProfileDiscardOptOutTracker::OnOptOutListChanged,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      performance_manager::user_tuning::prefs::kManagedTabDiscardingExceptions,
      base::BindRepeating(&ProfileDiscardOptOutListHelper::
                              ProfileDiscardOptOutTracker::OnOptOutListChanged,
                          base::Unretained(this)));
  // Trigger a first update so the list reflects the initial pref value.
  OnOptOutListChanged();
}

ProfileDiscardOptOutListHelper::ProfileDiscardOptOutTracker::
    ~ProfileDiscardOptOutTracker() {
  delegate_->ClearPatterns(browser_context_id_);
}

void ProfileDiscardOptOutListHelper::ProfileDiscardOptOutTracker::
    OnOptOutListChanged() {
  const base::Value::List& user_value_list =
      pref_change_registrar_.prefs()->GetList(
          performance_manager::user_tuning::prefs::kTabDiscardingExceptions);
  const base::Value::List& managed_value_list =
      pref_change_registrar_.prefs()->GetList(
          performance_manager::user_tuning::prefs::
              kManagedTabDiscardingExceptions);

  std::vector<std::string> patterns;
  patterns.reserve(user_value_list.size() + managed_value_list.size());

  // Merge the two lists so that the PageDiscardingHelper only sees a single
  // list of patterns to exclude from discarding.
  std::transform(user_value_list.begin(), user_value_list.end(),
                 std::back_inserter(patterns),
                 [](const base::Value& val) { return val.GetString(); });
  std::transform(managed_value_list.begin(), managed_value_list.end(),
                 std::back_inserter(patterns),
                 [](const base::Value& val) { return val.GetString(); });

  delegate_->SetPatterns(browser_context_id_, patterns);
}

ProfileDiscardOptOutListHelper::ProfileDiscardOptOutListHelper(
    std::unique_ptr<Delegate> delegate)
    : delegate_(delegate ? std::move(delegate)
                         : std::make_unique<
                               ProfileDiscardOptOutListHelperDelegateImpl>()) {}

ProfileDiscardOptOutListHelper::~ProfileDiscardOptOutListHelper() = default;

void ProfileDiscardOptOutListHelper::OnProfileAdded(Profile* profile) {
  OnProfileAddedImpl(profile->UniqueId(), profile->GetPrefs());
}

void ProfileDiscardOptOutListHelper::OnProfileWillBeRemoved(Profile* profile) {
  OnProfileWillBeRemovedImpl(profile->UniqueId());
}

void ProfileDiscardOptOutListHelper::OnProfileAddedImpl(
    const std::string& browser_context_id,
    PrefService* pref_service) {
  discard_opt_out_trackers_.emplace(
      std::piecewise_construct, std::forward_as_tuple(browser_context_id),
      std::forward_as_tuple(browser_context_id, pref_service, delegate_.get()));
}

void ProfileDiscardOptOutListHelper::OnProfileWillBeRemovedImpl(
    const std::string& browser_context_id) {
  auto it = discard_opt_out_trackers_.find(browser_context_id);
  DCHECK(it != discard_opt_out_trackers_.end());
  discard_opt_out_trackers_.erase(it);
}

}  // namespace performance_manager::user_tuning


text:
using MegaMan10;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTestProject1
{
    [TestClass]
    public class ProtomanTeste
    {
        //PROTOMAN X BOOT
        [TestMethod]
        public void ProtomanNasce()
        {
            var protoman = new Protoman();

            string esperado = "Vida: 100, Ataque: 5, Defesa: 2";

            Assert.AreEqual(esperado, protoman.ToString());

        }

        [TestMethod]
        public void ProtomanAtaque1X()
        {
            var protoman = new Protoman();
            var defensor = new Boot();

            protoman.Atacar(defensor);

            Assert.AreEqual(95, defensor.Vida);
        }

        [TestMethod]
        public void ProtomanAtaque2X()
        {
            var protoman = new Protoman();
            var defensor = new Boot();

            protoman.Atacar(defensor);
            protoman.Atacar(defensor);

            Assert.AreEqual(90, defensor.Vida);
        }

        //PROTOMAN X MEGAMAN
        [TestMethod]
        public void ProtomanRenasce()
        {
            var protoman = new Protoman();
            var megaman = new Megaman();

            for(int i = 0; i < 25; i++)
            {
                megaman.Atacar(protoman);
            }

            Assert.AreEqual(20, protoman.Vida);
        }

        [TestMethod]
        public void ProtomanNaoRenasce2X()
        {
            var protoman = new Protoman();
            var megaman = new Megaman();

            for (int i = 0; i < 31; i++)
            {
                megaman.Atacar(protoman);
            }

            Assert.AreEqual(0, protoman.Vida);
        }

        [TestMethod]
        public void ProtomanAtaque7AposMorrer1X()
        {
            var protoman = new Protoman();
            var megaman = new Megaman();

            for (int i = 0; i < 25; i++)
            {
                megaman.Atacar(protoman);
            }

            string esperado = "Vida: 20, Ataque: 7, Defesa: 2";

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void EquiparUpgradeAtaque()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 7, Defesa: 2";

            protoman.EquiparUpgrade(new CanhaoPlasma());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void Equipar2XUpgradeAtaque()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 9, Defesa: 2";

            protoman.EquiparUpgrade(new CanhaoPlasma());
            protoman.EquiparUpgrade(new CanhaoPlasma());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void Equipar1XUpgradeDefesa()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 5, Defesa: 4";

            protoman.EquiparUpgrade(new EscudoEnergia());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void Equipar2XUpgradeDefesa()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 5, Defesa: 6";

            protoman.EquiparUpgrade(new EscudoEnergia());
            protoman.EquiparUpgrade(new EscudoEnergia());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void Equipar1XUpgradeBotas()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 6, Defesa: 3";

            protoman.EquiparUpgrade(new BotasSuperVelocidade());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void Equipar2XUpgradeBotas()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 7, Defesa: 4";

            protoman.EquiparUpgrade(new BotasSuperVelocidade());
            protoman.EquiparUpgrade(new BotasSuperVelocidade());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void EquiparUpgradeCanhaoEscudoBota()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 8, Defesa: 5";

            protoman.EquiparUpgrade(new CanhaoPlasma());
            protoman.EquiparUpgrade(new EscudoEnergia());
            protoman.EquiparUpgrade(new BotasSuperVelocidade());

            Assert.AreEqual(esperado, protoman.ToString());
        }

        [TestMethod]
        public void NaoEquiparMaisDe3Acessorios()
        {
            var protoman = new Protoman();
            string esperado = "Vida: 100, Ataque: 8, Defesa: 5";

            protoman.EquiparUpgrade(new CanhaoPlasma());
            protoman.EquiparUpgrade(new EscudoEnergia());
            protoman.EquiparUpgrade(new BotasSuperVelocidade());
            protoman.EquiparUpgrade(new EscudoEnergia());

            Assert.AreEqual(esperado, protoman.ToString());
        }
    }
}


text:
//Define this library if not already defined
#ifndef _LEDSEGS_
  #define _LEDSEGS_ 26

#include "SPI.h"
#include "LPD8806.h"

//Total spectrum analyzer shield bands and max value for a band read. Do not change this.
const short cSegNumBands=7;

//Frequency band index values bit values. Bit 0 (0x1) is the lowest freq., bit 7 (0x40) is highest.
//These are fixed by the spectrum analyzer chip used on the shield, and the number of bands cannot be changed.
//For most applications it is recommended not to use bands 1 and 7.

const short cSegBand1 = 0x01;  //63Hz center - I recommend omitting this band in most applications
const short cSegBand2 = 0x02;  //160Hz
const short cSegBand3 = 0x04;  //400Hz
const short cSegBand4 = 0x08;  //1.0KHz
const short cSegBand5 = 0x10;  //2.5KHz
const short cSegBand6 = 0x20;  //6.25KHz - Think about omitting this (6KHz is a pretty high "audible" freq.)
const short cSegBand7 = 0x40;  //16KHz - I REALLY recommend omitting this one, just noise energy.

//Software gain control constants. This provides a simple 'fast attack'/'slow decay' AGC for the input.
//InitialMax is the lowest spectrum band value to which AGC processing will apply. (AGC is applied
//separately to each of the seven spectrum bands.) As each sample is read, a fixed, assumed noise
//value is subtracted, then the max value seen for that channel is updated, but only when it is above MaxBandValue.
//Then the sampled value is scaled to the range (0..MaxSegmentLevel) using the actual max seen for that channel
//so far. The decay constant is subtracted from each channel's max on each display cycle. This sample normalization
//is applied before any custom display routine is called.

const static short cInitialMaxBandValue = 200; //Lowest max value allowed (0..1023) Normalized, after noise deduction.
const static short cMaxBandValueDecay = 2;     //Subtracted from detected max on each sample cycle
const short cMaxSegmentLevel = 1023;           //Normalized max sample value coming out of MapBandsToSegments()

//LEDSegs Segment actions. See DefineSegment and SetSegment_Action.

const short cSegActionNone = 0;        //Do nothing (undefined or do-nothing segment)
const short cSegActionFromBottom = 1;  //Fill LEDs from the first LED up, based on the current averaged band level vs the max possible
const short cSegActionFromTop = 2;     //Fill LEDs from the last down
const short cSegActionFromMiddle = 3;  //Fill LEDs from the middle out
const short cSegActionStatic = 4;      //Fill all LEDs in segment. Do not look at spectrum value.
const short cSegActionRandom = 5;      //Illuminate foreground color randomly throughout the segment

//Segment Options

const short cSegOptNoOffOverwrite = 0x01;
const short cSegOptModulateSegment = 0x02;
const short cSegOptInvertLevel = 0x04;

//Max # of segments that can be defined for a strip. Segments are "written" to the strip in index order.
//So higher-index segments can overwrite part or all of an lower-index segment.

#ifndef cMaxSegments
  #define cMaxSegments 100
#endif

//The prototype for a pointer to a segment display customizing routine that can be defined for any segme
//and will be called just before each strip refresh

typedef void (*SegmentDisplayRoutine) (short iSegment);

//Our LED strip class.

class LEDSegs {

  public:

    //Constructor and destructor
    LEDSegs(short nLEDs) {LEDSegsInit(nLEDs, true, 0, 0);}  //Constructor with default data/clock
    LEDSegs(short nLEDs, short pinData, short pinClock) {LEDSegsInit(nLEDs, false, pinData, pinClock);}  //Constructor with explicit data/clock
    ~LEDSegs() {delete[] objLPDStrip;}
    void LEDSegsInit(short, bool, short, short);  //Common constructor code

    void DisplaySpectrum(bool, bool);
    void ResetStrip();
    void ResetRandom();

    void SetSegmentIndex(short Idx) {segCurrentIndex = constrain(Idx, 0, cMaxSegments - 1);}
    short GetSegmentIndex() {return segCurrentIndex;}

    //The SetSegment_xxx routines are overloaded. The segment # parameter can be omitted and defaults to the current index

    void SetSegment_Action(short nSegment, short Action) {if (Action >= 0) {SegmentData[nSegment].segAction = Action;};}
    void SetSegment_Action(short Action) {SetSegment_Action(segCurrentIndex, Action);}
    void SetSegment_BackColor(short nSegment, uint32_t BackColor) {if (BackColor != 0xFFFFFFFF) {SegmentData[nSegment].segBackColor = BackColor;};}
    void SetSegment_BackColor(uint32_t BackColor) {SetSegment_BackColor(segCurrentIndex, BackColor);}
    void SetSegment_Bands(short nSegment, short Bands) {if (Bands >= 0) {SegmentData[nSegment].segBands = Bands;};}
    void SetSegment_Bands(short Bands) {SetSegment_Bands(segCurrentIndex, Bands);}
    void SetSegment_DisplayRoutine(short nSegment, SegmentDisplayRoutine Routine) {SegmentData[nSegment].segDisplayRoutine = *Routine;}
    void SetSegment_DisplayRoutine(SegmentDisplayRoutine Routine) {SetSegment_DisplayRoutine(segCurrentIndex, Routine);}
    void SetSegment_FirstLED(short nSegment, short FirstLED) {if (FirstLED >= 0) {SegmentData[nSegment].segFirstLED = FirstLED;};}
    void SetSegment_FirstLED(short FirstLED) {SetSegment_FirstLED(segCurrentIndex, FirstLED);}
    void SetSegment_ForeColor(short nSegment, uint32_t ForeColor) {if (ForeColor != 0xFFFFFFFF) {SegmentData[nSegment].segForeColor = ForeColor;};}
    void SetSegment_ForeColor(uint32_t ForeColor) {SetSegment_ForeColor(segCurrentIndex, ForeColor);}
    void SetSegment_Level(short nSegment, short level) {SegmentData[nSegment].segLevel = level;}
    void SetSegment_Level(short level) {SetSegment_Level(segCurrentIndex, level);}
    void SetSegment_NumLEDs(short nSegment, short nLEDs) {if (nLEDs >= 0) {SegmentData[nSegment].segNumLEDs = nLEDs;};}
    void SetSegment_NumLEDs(short nLEDs) {SetSegment_NumLEDs(segCurrentIndex, nLEDs);}
    void SetSegment_Options(short nSegment, short Options) {if (Options >= 0) {SegmentData[nSegment].segOptions = Options;};}
    void SetSegment_Options(short Options) {SetSegment_Options(segCurrentIndex, Options);}
    void SetSegment_Spacing(short nSegment, short Spacing) {if (Spacing >= 0) {SegmentData[nSegment].segSpacing = Spacing;};}
    void SetSegment_Spacing(short Spacing) {SetSegment_Spacing(segCurrentIndex, Spacing);}

    short    GetSegment_Action(short nSegment)    {return SegmentData[nSegment].segAction;}
    uint32_t GetSegment_BackColor(short nSegment) {return SegmentData[nSegment].segBackColor;}
    short    GetSegment_Bands(short nSegment)     {return SegmentData[nSegment].segBands;}
    short    GetSegment_FirstLED(short nSegment)  {return SegmentData[nSegment].segFirstLED;}
    uint32_t GetSegment_ForeColor(short nSegment) {return SegmentData[nSegment].segForeColor;}
    short    GetSegment_Level(short nSegment)     {return SegmentData[nSegment].segLevel;}
    short    GetSegment_NumLEDs(short nSegment)   {return SegmentData[nSegment].segNumLEDs;}
    short    GetSegment_Options(short nSegment)   {return SegmentData[nSegment].segOptions;}
    short    GetSegment_Spacing(short nSegment)   {return SegmentData[nSegment].segSpacing;}

    //Initialize a new segment and return the index # of the segment defined.
    //You can set spectrum bands to -1 to include all bands, or 0 to not modulate according to audio level at all
    short DefineSegment(
        short     /* First LED in segment (0 origin) */
      , short     /* # LEDs in segment*/
      , short     /* cSegActionXXX value - defines how the segment works */
      , uint32_t  /* Foreground color */
      , short     /* Bitmask of cSegBandN spectrum band specs, to be averaged together to make this segment's value */
    );

    //Methods that match LPD8806 member function, except declared static and does not set the high bit (this
    //is done by LPD8806 setPixelColor. Return value is GRB (not RGB!) value in long int.
    static uint32_t Color(byte r, byte g, byte b) {
      return ((uint32_t)(g) << 16) | ((uint32_t)(r) <<  8) | b;
    }

    //Get the r/g/b components of a color into byte values (remember value is GRB, not RGB), return array [0..2]
    //is ordered RGB
    static void Colorvals(uint32_t Color, byte rgbvals[]) {
      rgbvals[1] = ((Color >> 16) & 0x7F);
      rgbvals[0] = ((Color >> 8) & 0x7F);
      rgbvals[2] = (Color & 0x7F);
    }

  private:
    const static short cSpectrumReset=5;
    const static short cSpectrumStrobe=4;

    struct stripSegment {
      short segFirstLED;    //The first LED in the segment from the beginning (0-origin)
      short segNumLEDs;  //The number of LEDs in the segment
      uint32_t segForeColor;     //The base color of the segment's LEDs
      uint32_t segBackColor;     //Background color
      short segBands;       //The spectrum bands that are averaged together to make up the value for the segment
      short segAction;      //The way the LEDs in the segment are populated
      short segSpacing;     //Spacing between LEDs that are illuminated in the segment (0 default = no spacing)
      short segOptions;     //Options for the segment (cSegOpt...)
      SegmentDisplayRoutine segDisplayRoutine;  //Optional routine to call just before each display cycle
      short segLevel, segMaxLevel;       //Normalized & max level -- output from MapBandsToSegments
    };

    short segCurrentIndex;    //The "current" (default) index that will be modified
    short segMaxDefinedIndex; //Tracks the highest index defined
    stripSegment SegmentData[cMaxSegments];  //The segment array

    //The per-band level from the spectrum analyzer for the current sample (see ReadSpectrum)
    short SpectrumLevel[cSegNumBands];

    //Max value seen for each spectrum band so far. Used to implement a simple adaptive AGC.
    short maxBandValue[cSegNumBands];

    //Maximum noise values for each band. A band spectrum value of this or lower cause no illumination
    //These were determined by experimentation.
    short nNoiseFloor[cSegNumBands];

    //Spectrum analyzer left/right channels
    const static short cSegSpectrumAnalogLeft=0;  //Left channel
    const static short cSegSpectrumAnalogRight=1; //Right channel

    void MapBandsToSegments();
    void ReadSpectrum(bool, bool);
    void ShowSegments();

    //A pointer to the low-level I/O LBD8806 strip object we talk to
    LPD8806* objLPDStrip;
    short nLEDsInStrip;

    //Array of random cutoff levels (for cSegActionRandom)
    unsigned short segRandomLevels[64];  //Changing this requires code changes
};

//Various colors. The bit format of these is defined by the LPD8806 library.
//Assume nothing about the format except they are an unsigned long int and 0..127

const uint32_t RGBOff =         LEDSegs::Color(0, 0, 0);
const uint32_t RGBBlack =       RGBOff;

const uint32_t RGBWhite =       LEDSegs::Color(127, 127, 127); //Watch out - 60mA per LED with this
const uint32_t RGBGold =        LEDSegs::Color( 90,  40,   8);
const uint32_t RGBSilver =      LEDSegs::Color( 15,  30,  60);
const uint32_t RGBYellow =      LEDSegs::Color( 90,  70,   0);
const uint32_t RGBOrange =      LEDSegs::Color( 60,  20,   0);
const uint32_t RGBRed =         LEDSegs::Color(127,   0,   0);
const uint32_t RGBGreen =       LEDSegs::Color(  0, 127,   0);
const uint32_t RGBBlue =        LEDSegs::Color(  0,   0, 127);
const uint32_t RGBPurple =      LEDSegs::Color( 40,   0,  40);

//White-ish versions of the base colors (except white!)

const uint32_t RGBGoldWhite =   LEDSegs::Color(110,  70,  30);
const uint32_t RGBSilverWhite = LEDSegs::Color( 20,  45,  90);
const uint32_t RGBYellowWhite = LEDSegs::Color(127, 100,  15);
const uint32_t RGBOrangeWhite = LEDSegs::Color( 80,  35,   5);
const uint32_t RGBRedWhite =    LEDSegs::Color(100,   3,   5); //aka "Pink"
const uint32_t RGBGreenWhite =  LEDSegs::Color( 20, 127,  20);
const uint32_t RGBBlueWhite =   LEDSegs::Color( 10,  20, 127);
const uint32_t RGBPurpleWhite = LEDSegs::Color( 40,   8,  40);

//Dimmer versions of the base colors
const uint32_t RGBWhiteDim =       LEDSegs::Color( 8, 15, 15);
const uint32_t RGBSilverDim =      LEDSegs::Color( 8, 15, 24);
const uint32_t RGBGoldDim =        LEDSegs::Color( 8,  4,  1);
const uint32_t RGBYellowDim =      LEDSegs::Color(20, 15,  0);
const uint32_t RGBOrangeDim =      LEDSegs::Color(15,  3,  0);
const uint32_t RGBRedDim =         LEDSegs::Color(32,  0,  0);
const uint32_t RGBGreenDim =       LEDSegs::Color( 0,  6,  0);
const uint32_t RGBBlueDim =        LEDSegs::Color( 0,  0, 24);
const uint32_t RGBPurpleDim =      LEDSegs::Color(10,  0, 10);

//Very dim versions of the colors
const uint32_t RGBWhiteVeryDim =   LEDSegs::Color( 1,  2,  2);
const uint32_t RGBSilverVeryDim =  LEDSegs::Color( 1,  2,  4);
const uint32_t RGBGoldVeryDim =    LEDSegs::Color( 4,  2,  1);
const uint32_t RGBYellowVeryDim =  LEDSegs::Color( 4,  3,  0);
const uint32_t RGBOrangeVeryDim =  LEDSegs::Color( 4,  1,  0);
const uint32_t RGBRedVeryDim =     LEDSegs::Color( 1,  0,  0);
const uint32_t RGBGreenVeryDim =   LEDSegs::Color( 0,  1,  0);
const uint32_t RGBBlueVeryDim =    LEDSegs::Color( 0,  0,  1);
const uint32_t RGBPurpleVeryDim =  LEDSegs::Color( 1,  0,  1);

//General macros
#define SIZEOF_ARRAY(ary) (sizeof(ary) / sizeof(ary[ 0 ]))

/*______________
LEDSegsInit:Common constructor code
*/

void LEDSegs::LEDSegsInit(short nLEDs, bool useSPI, short pinData, short pinClock) {
  unsigned short iBand;

  segCurrentIndex = 0;
  segMaxDefinedIndex = -1;

  //Noise values for each spectrum band (0..1023). Determined by experimentation. YMMV
  nNoiseFloor[0] =  90;
  nNoiseFloor[1] =  90;
  nNoiseFloor[2] =  90;
  nNoiseFloor[3] = 100;
  nNoiseFloor[4] = 100;
  nNoiseFloor[5] = 110;
  nNoiseFloor[6] = 120;

  //Initialize the max level seen for each band.
  for (iBand = 0; iBand < cSegNumBands; iBand++) {maxBandValue[iBand] = cInitialMaxBandValue;}

  //Create an LED strip object. Either SPI or digital pins

  if (useSPI) {objLPDStrip = new LPD8806(nLEDs);}
  else {objLPDStrip = new LPD8806(nLEDs, pinData, pinClock);}

  nLEDsInStrip = nLEDs;

  //Setup pins to drive the spectrum analyzer.
  pinMode(cSpectrumReset, OUTPUT);
  pinMode(cSpectrumStrobe, OUTPUT);

  //Init spectrum analyzer to start reading from lowest band
  digitalWrite(cSpectrumStrobe,LOW);
    delay(1);
  digitalWrite(cSpectrumReset,HIGH);
    delay(1);
  digitalWrite(cSpectrumStrobe,HIGH);
    delay(1);
  digitalWrite(cSpectrumStrobe,LOW);
    delay(1);
  digitalWrite(cSpectrumReset,LOW);
    delay(5);

  //Init this guy
  ResetStrip();
}

/*____________________
LEDSegs::DefineSegment
Set the properties of the current LED segment. A -1 value indicates that the corresponding property should not be changed.
Return value is the segment index.
*/

short LEDSegs::DefineSegment(short FirstLED, short nLEDs, short Action, uint32_t ForeColor, short Bands) {

  //Move to next segment (if no segments yet, start with #0)
  if (segMaxDefinedIndex < 0) {SetSegmentIndex(0);} else {SetSegmentIndex(segCurrentIndex + 1);}

  //Set the segment properties passed in
  SetSegment_FirstLED(FirstLED);
  SetSegment_NumLEDs(nLEDs);
  SetSegment_Action(Action);
  SetSegment_ForeColor(ForeColor);
  SetSegment_Bands(segCurrentIndex, Bands);

  //Segment defaults
  SetSegment_BackColor(RGBOff);
  SetSegment_Spacing(0);
  SetSegment_Options(segCurrentIndex, 0);
  SetSegment_DisplayRoutine(segCurrentIndex, NULL);

  //Track the highest segment index defined. This speeds the refresh loop a bit.
  segMaxDefinedIndex = max(segMaxDefinedIndex, segCurrentIndex);

  //Return the segment index that was updated, before incrementing it
  return segCurrentIndex;
};

/*______________________
LEDSegs::DisplaySpectrum
Sample and display according to the defined segments
*/

void LEDSegs::DisplaySpectrum(bool doLeft, bool doRight) {
  ReadSpectrum(doLeft, doRight);
  MapBandsToSegments();
  ShowSegments();
};

/*_________________________
LEDSegs::MapBandsToSegments
Convert spectrum band samples into LED strip segment values in the range 0 .. (# LEDs in that segment).
We average all the bands defined for the segment, and then scale the final segment value
*/

void LEDSegs::MapBandsToSegments() {
  short iSegment, iBand, nLEDs, segBands;
  unsigned long maxTotal, sampleTotal;
  SegmentDisplayRoutine thisDisplayRoutine;

  //Loop all defined segments to calc the normalized band value. We do this even for ActionNone segments
  //in case a segment display routine wants to change the action
  for (iSegment = 0; iSegment <= segMaxDefinedIndex; iSegment++) {
    nLEDs = SegmentData[iSegment].segNumLEDs;
    segBands = SegmentData[iSegment].segBands;

    //Loop spectrum bands. For any that are mapped into this segment we total both the sample values and the
    //max possible values, in order to do the normalization.
    maxTotal = 0;
    sampleTotal = 0;

    for (iBand = 0; iBand < cSegNumBands; iBand++) {
      if ((segBands >> iBand) & 1) {
        maxTotal += maxBandValue[iBand];
        sampleTotal += SpectrumLevel[iBand];
      }
    }
    if (maxTotal <= 0) {maxTotal = 1;} //Safety for use as divisor

    //Normalize the averaged level to 0..1023 and record in the level array element for this segment
    sampleTotal = (sampleTotal * cMaxSegmentLevel) / maxTotal;
    SegmentData[iSegment].segLevel = sampleTotal;
    SegmentData[iSegment].segMaxLevel = maxTotal;
  } //end segments loop

  //Now that all the segments are setup, call any segment display routines that are defined
  for (iSegment = 0; iSegment <= segMaxDefinedIndex; iSegment++) {
    thisDisplayRoutine = SegmentData[iSegment].segDisplayRoutine;
    if (thisDisplayRoutine != NULL) {thisDisplayRoutine(iSegment);}
  };
};

/*___________________
LEDSegs::ReadSpectrum
Read the spectrum band samples into class array SpectrumLevel[].
"Channels" tells whether to read left, right, or average both channels.
*/
void LEDSegs::ReadSpectrum(bool doLeft, bool doRight) {
  short iBand, thisLevel, bandMax;  //Band 0 is lowest frequencies, Band 6 is the highest.

  //This loop happens nBands times per sample, so keep it quick. It just records the
  //current and max sample values into the band value arrays.
  for(iBand=0; iBand < cSegNumBands; iBand++) {

    //Decay the max a little on each sample
    bandMax = maxBandValue[iBand] - cMaxBandValueDecay;
    if (bandMax < cInitialMaxBandValue) bandMax = cInitialMaxBandValue;

    //Read the spectrum for this band
    thisLevel = 0;
    if (doLeft) {thisLevel += analogRead(cSegSpectrumAnalogLeft);}
    if (doRight) {thisLevel += analogRead(cSegSpectrumAnalogRight);}
    if (doLeft && doRight) {thisLevel = thisLevel >> 1;} //If both channels, then take average

    //Process out assumed noise floor for this band
    thisLevel -= nNoiseFloor[iBand];
    if (thisLevel < 0) {thisLevel = 0;}

    //Set current and max values for this into their respective segment object array slots
    SpectrumLevel[iBand] = thisLevel;
    if (bandMax < thisLevel) {bandMax = thisLevel;}
    maxBandValue[iBand] = bandMax;

    //Toggle to ready for next band
    digitalWrite(cSpectrumStrobe,HIGH);
    digitalWrite(cSpectrumStrobe,LOW);
  }
}

/*_________________
LEDSegs::ResetStrip
Reset the whole thing
*/

void LEDSegs::ResetStrip() {
  short i;

  //Reset segment array
  for (i = 0; i < cMaxSegments; i++) {SegmentData[i].segAction = cSegActionNone;}

  objLPDStrip->begin();  //Clear and init the strip
  objLPDStrip->show();  //Update the LED strip display to show off to start
  segCurrentIndex = 0;
  segMaxDefinedIndex = -1;

  //Init the random permutation array (for cSegActionRandom)
  ResetRandom();
}

/*__________________
LEDSegs::ResetRandom
Init the cSegActionRandom levels array
*/

void LEDSegs::ResetRandom() {
  unsigned short i, imax;

  randomSeed(micros());
  imax = SIZEOF_ARRAY(segRandomLevels);

  //Init the random permutation array (Knuth shuffle)
  for (i=0; i < imax; i++) {segRandomLevels[i] = random(cMaxSegmentLevel);}
}

/*___________________
LEDSegs::ShowSegments
Display the segment values on the LED strip
*/

void LEDSegs::ShowSegments() {
  short    iSegment, iLEDinSegment, iLED, LEDIncrement, segval, ledval;
  short    FirstLED, NumberLEDs, Action, Options, segSpacing1, SpacingCount;
  bool     optOffOverwrite, optModulate, notSpacingLED, doled;
  uint32_t thisColor, backColor, foreColor;
  byte     bcRGB[3], fcRGB[3]; //extra byte for long align
  stripSegment *segptr;

  //First, init all LEDs in the strip to off
  for (iLED = 0; iLED < nLEDsInStrip; iLED++) {objLPDStrip->setPixelColor(iLED, RGBOff);}

  //Write each defined segment
  for (iSegment = 0; iSegment <= segMaxDefinedIndex; iSegment++) {

    segptr = &SegmentData[iSegment];
    Action = segptr->segAction;

    //Process segment if it does something

    if (Action != cSegActionNone) {

      /* Set some local vars for fast reference that we'll need */
      FirstLED = segptr->segFirstLED;
      NumberLEDs = segptr->segNumLEDs;
      backColor = segptr->segBackColor;
      foreColor = segptr->segForeColor;
      segSpacing1 = segptr->segSpacing + 1;

      Options = segptr->segOptions;
      optOffOverwrite = (Options & cSegOptNoOffOverwrite) == 0;
      optModulate = (Options & cSegOptModulateSegment) != 0;

      //The level coming out of MapBandsToSegments() is normalized to 0..1023. Here we
      //scale to the number of LEDs that means for this segment.

      if (Options & cSegOptInvertLevel) {segptr->segLevel = cMaxSegmentLevel - segptr->segLevel;}
      segval = segptr->segLevel;
      segval = (((long) segval) * ((long) (NumberLEDs + 1))) / ((long) (cMaxSegmentLevel + 1));
      segval = constrain(segval, 0, NumberLEDs); //Insure within expected range
      ledval = segval;
      if ((Action == cSegActionStatic) || (Action == cSegActionRandom)) {ledval = NumberLEDs;}

      //If this is a ModulateSegment option segment, then figure the foreground color scaled between
      //backcolor and forecolor according to the segment's spectrum level.
      if (optModulate) {
        Colorvals(backColor, bcRGB);
        Colorvals(foreColor, fcRGB);
        foreColor = LEDSegs::Color(
            bcRGB[0] + (((fcRGB[0] - bcRGB[0]) * segval) / NumberLEDs)
          , bcRGB[1] + (((fcRGB[1] - bcRGB[1]) * segval) / NumberLEDs)
          , bcRGB[2] + (((fcRGB[2] - bcRGB[2]) * segval) / NumberLEDs));
      }

      //Get the starting LED index for this segment and an initial increment to get to the next LED
      switch (Action) {
        case cSegActionFromBottom: //bottom, static and random start iLED the same
        case cSegActionRandom:
        case cSegActionStatic:     LEDIncrement = 1;  iLED = FirstLED; break;

        case cSegActionFromTop:    LEDIncrement = -1; iLED = FirstLED + NumberLEDs - 1; break;

        case cSegActionFromMiddle: LEDIncrement = 0;  iLED = FirstLED + ((NumberLEDs - 1) >> 1); break;
      }

      //Init the spacing counter. This counts down from spacing-1 each time it hits 0 (an illuminated LED).
      //The first LED is always a non-spacer, which is why we init to zero.

      SpacingCount = 0;

      //Loop across the LEDs in the segment being illuminated.
      //NOTE: Keep this loop TIGHT! It is run for every LED in every defined segment

      for (iLEDinSegment = 0; iLEDinSegment < NumberLEDs; iLEDinSegment++) {

        //Figure the color we want this LED to be and write it to the LED
        thisColor = backColor;
        if (ledval > iLEDinSegment) {thisColor = foreColor;}

        //Determine if this LED is blanked out because of spacing > 1
        notSpacingLED = (SpacingCount == 0);

        //Write the color value to the strip, but not if...
        //  1) This is a spacing LED (when segment's spacing value is > 1), or...
        //  2) The color value is RGBOff and this is a no-off-overwrite-option segment
        //  3) This is an ActionRandom segment and the level is too low based on the randomizer

        doled = (notSpacingLED & ((thisColor != RGBOff) | optOffOverwrite));
        if (doled & (Action == cSegActionRandom)) {
          if (segRandomLevels[iLEDinSegment & 0x3F] > segptr->segLevel) {doled = false;}
        }

        if (doled) {objLPDStrip->setPixelColor(iLED, thisColor);}

        //Move to next LED. For from-middle, we jump back and forth around the center of the segment, increasing
        //the increment's absolute value by one more each jump.

        if (Action == cSegActionFromMiddle) {
          if (LEDIncrement <= 0) {
            LEDIncrement--;
            if (notSpacingLED) {SpacingCount = segSpacing1;}
            SpacingCount--;
          }
          else {LEDIncrement++;}
          LEDIncrement = -LEDIncrement;
        }
        else {
          if (notSpacingLED) {SpacingCount = segSpacing1;}
          SpacingCount--;
        }

        iLED += LEDIncrement;
      } //LED-in-segment loop
    } //If an action defined
  }  //Segment loop

  //Finally, refresh the strip.
  objLPDStrip->show();
}
#endif  //_LEDSEGS_


text:
<?php

namespace Immortal\View\Engines;

abstract class Engine
{
    /**
     * The view that was last to be rendered.
     *
     * @var string
     */
    protected $lastRendered;

    /**
     * Get the last view that was rendered.
     *
     * @return string
     */
    public function getLastRendered()
    {
        return $this->lastRendered;
    }
}


text:
- 3f4ad5e30: fix: url of repository in package.json

## 1.1.4

### Patch Changes

- 77af1fc: chore(dependencies): auto update for maintenance purpose

  ```diff
  -    "@neuralegion/cypress-har-generator": "^5.2.3"
  +    "@neuralegion/cypress-har-generator": "^5.3.0"
  ```

## 1.1.3

### Patch Changes

- 9ef83c5: Upgrade dependencies to be aligned with what is used in dev mode

## 1.1.2

### Patch Changes

- c90c604: fix(cypress/api-mock): do not register request with status 0

## 1.1.1

### Patch Changes

- 3f97c46: fix(cypress): api mock set content-type headers

## 1.1.0

### Minor Changes

- 887c729: feat(cypress/api-mock): accept a response modifier

## 1.0.4

### Patch Changes

- 61df75e: fix(cypress): pass string instead of regexp from command to task

## 1.0.3

### Patch Changes

- 16e0b5c: fix(cypress): api mock plugin browser flags as exposed function

## 1.0.2

### Patch Changes

- b66906c: fix(cypress-api-mock-plugin): write har file

## 1.0.1

### Patch Changes

- 5220287: fix(cypress-api-mock-plugin): escape har special chars before write into file

## 1.0.0

### Major Changes

- 8ce1200: feat(Cypress): api mock plugin


text:
import pandas as pd

from great_expectations.execution_engine import (
    PandasExecutionEngine,
    SparkDFExecutionEngine,
    SqlAlchemyExecutionEngine,
)
from great_expectations.expectations.metrics.column_aggregate_metric_provider import (
    ColumnAggregateMetricProvider,
    column_aggregate_partial,
    column_aggregate_value,
)
from great_expectations.expectations.metrics.import_manager import F, sa

class ColumnValuesLengthMax(ColumnAggregateMetricProvider):
    metric_name = "column_values.length.max"

    @column_aggregate_value(engine=PandasExecutionEngine, filter_column_isnull=True)
    def _pandas(cls, column: pd.Series, **kwargs: dict) -> int:
        return column.map(len).max()

    @column_aggregate_partial(
        engine=SqlAlchemyExecutionEngine, filter_column_isnull=True
    )
    def _sqlalchemy(cls, column, **kwargs: dict):  # type: ignore[no-untyped-def]
        return sa.func.max(sa.func.length(column))

    @column_aggregate_partial(engine=SparkDFExecutionEngine, filter_column_isnull=True)
    def _spark(cls, column, **kwargs: dict):  # type: ignore[no-untyped-def]
        return F.max(F.length(column))