text:
var websites = require("./websites.js");
var currencies = require("./currencies.js");
var websiteAnalyzers = require("./websiteAnalyzers.js");
var authenticationHelper = require("./helpers/authenticationHelper.js");
var Product = require("../../database/collections/productsCollection.js");

function getWebsiteFromUrl(urlString, includeFamilyWebsites) {
    if (!urlString) {
        return;
    }

    var hostnames = urlString.match(/^http:\/\/[^/]+/);
    if (!hostnames || hostnames.length == 0) {
        hostnames = urlString.match(/^https:\/\/[^/]+/);
        if (!hostnames || hostnames.length == 0) {
            return "";
        }
    }
    var hostname = hostnames[0];
    if (!hostname) {
        return "";
    }

    for (var websiteKey in websites.Websites) {
        var website = websites.Websites[websiteKey];

        if (includeFamilyWebsites == false) {
            // Family websites like "ebay" or "amazon" should not be included
            // Only "ebay.com" or "ebay.co.uk" should be
            if (website.indexOf(".") == -1) {
                continue;
            }
        }

        if (hostname.indexOf(website) != -1) {
            return website;
        }
    }

    return "";
}

function getNumberFromString(sentence) {
    var sentenceWithoutSpaces = sentence.replace(/\s/g, '');
    var matches = sentenceWithoutSpaces.replace(/,/g, '').match(/(\+|-)?((\d+(\.\d+)?)|(\.\d+))/);
    return matches && matches[0] || null;
}

function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

function is_server() {
    return (typeof process === 'object' && process + '' === '[object process]');
}

function refreshProduct(product, callbackFunction) {
    var currentProduct = product;
    var analyzer = websiteAnalyzers.getAnalyzerFromUrl(currentProduct.objectUrl);
    if (!analyzer) {
        callbackFunction(null);
        return;
    }
    analyzer.getHtmlFromUrl(function() {
        try {
            var price = analyzer.getPrice();
            if (price && price != currentProduct.newPrice) {
                currentProduct.newPrice = price;
            }

            var imageUrl = analyzer.getImageUrl()
            currentProduct.imageUrl = imageUrl;

            // Save updated product in database
            var upsertData = currentProduct.toObject();
            delete upsertData._id;
            upsertData.lastChecked = new Date();
            Product.findOneAndUpdate({ _id: currentProduct._id }, upsertData, { new: true }, function(error, result) {
                callbackFunction(result);
            });
        } catch (err) {
            console.log("error occured: ", err);
        }
    }.bind(this));
}

function populateTemporaryFields(product) {
    var website = getWebsiteFromUrl(product.objectUrl, false);
    var currencySymbol = currencies.getCurrencySymbol(product.currency);
    product.website = website;
    product.currencySymbol = currencySymbol;
}

function parseDocRecursively(cache, callbackFunction) {
    var currentProductNumber = cache.get("productsParsed");
    var currentDate = new Date();
    var currentProduct = cache.get("products")[currentProductNumber];
    var currentProductLastCheckedDate = currentProduct.lastChecked;

    if (!currentProductLastCheckedDate || (currentDate - currentProductLastCheckedDate > 3600000)) { // 3,600,000 milliseconds = 60 minutes
        refreshProduct(currentProduct, function(updatedProduct) {
            if (!updatedProduct) {
                callbackFunction(cache.get("products"));
            }

            populateTemporaryFields(updatedProduct);
            var products = cache.get("products");
            products[currentProductNumber] = updatedProduct;
            cache.put("products", products);

            var productsParsed = cache.get("productsParsed");
            productsParsed += 1;
            cache.put("productsParsed", productsParsed);
            var productsLength = cache.get("productsLength");

            if (productsParsed >= productsLength) {
                callbackFunction(cache.get("products"));
            } else {
                parseDocRecursively(cache, callbackFunction);
            }
        });
    } else {
        populateTemporaryFields(currentProduct);
        var products = cache.get("products");
        products[currentProductNumber] = currentProduct;
        cache.put("products", products);

        var productsParsed = cache.get("productsParsed");
        productsParsed += 1;
        cache.put("productsParsed", productsParsed);
        var productsLength = cache.get("productsLength");

        if (productsParsed >= productsLength) {
            callbackFunction(cache.get("products"));
        } else {
            parseDocRecursively(cache, callbackFunction);
        }
    }
}

function analyzeObject(url, callbackFunction) {
    var website = getWebsiteFromUrl(url);

    if (!website || !url) {
        return;
    }

    var analyzer = websiteAnalyzers.getAnalyzerFromUrl(url);

    analyzer.getHtmlFromUrl(function() {
        var price = analyzer.getPrice();
        var imageUrl = analyzer.getImageUrl();
        var name = analyzer.getName();
        var currencySymbol = analyzer.getCurrencySymbol();

        var result = {
            "name": name,
            "price": price,
            "imageUrl": imageUrl,
            "currency": analyzer.currency,
            "currencySymbol": currencySymbol
        }

        callbackFunction(result);
    });
}

function constructSearchOptions(searchText, accessToken) {
    var searchOptions = {};
    var currentUserId = authenticationHelper.getLoggedUserId(accessToken);

    if (!searchText) {
        searchOptions = {
            user: currentUserId
        };
    } else {
        searchOptions = {
            $text: {
                $search: searchText
            },
            user: currentUserId
        }
    }

    return searchOptions;
}

exports.getWebsiteFromUrl = getWebsiteFromUrl;
exports.getNumberFromString = getNumberFromString;
exports.guid = guid;
exports.parseDocRecursively = parseDocRecursively;
exports.analyzeObject = analyzeObject;
exports.constructSearchOptions = constructSearchOptions;
exports.refreshProduct = refreshProduct;


text:
module Spree
  class LineItem < Spree::Base
    before_validation :adjust_quantity
    belongs_to :order, class_name: "Spree::Order", inverse_of: :line_items, touch: true
    belongs_to :variant, class_name: "Spree::Variant", inverse_of: :line_items
    belongs_to :tax_category, class_name: "Spree::TaxCategory"

    has_one :product, through: :variant

    has_many :adjustments, as: :adjustable, dependent: :destroy
    has_many :inventory_units, inverse_of: :line_item

    before_validation :copy_price
    before_validation :copy_tax_category

    validates :variant, presence: true
    validates :quantity, numericality: {
      only_integer: true,
      greater_than: -1,
      message: Spree.t('validation.must_be_int')
    }
    validates :price, numericality: true
    validates_with Stock::AvailabilityValidator

    validate :ensure_proper_currency
    before_destroy :update_inventory

    after_save :update_inventory
    after_save :update_adjustments

    after_create :create_tax_charge

    delegate :name, :description, :should_track_inventory?, to: :variant

    attr_accessor :target_shipment

    def copy_price
      if variant
        self.price = variant.price if price.nil?
        self.cost_price = variant.cost_price if cost_price.nil?
        self.currency = variant.currency if currency.nil?
      end
    end

    def copy_tax_category
      if variant
        self.tax_category = variant.tax_category
      end
    end

    def amount
      price * quantity
    end
    alias subtotal amount

    def discounted_amount
      amount + promo_total
    end

    def final_amount
      amount + adjustment_total.to_f
    end
    alias total final_amount

    def single_money
      Spree::Money.new(price, { currency: currency })
    end
    alias single_display_amount single_money

    def money
      Spree::Money.new(amount, { currency: currency })
    end
    alias display_total money
    alias display_amount money

    def adjust_quantity
      self.quantity = 0 if quantity.nil? || quantity < 0
    end

    def sufficient_stock?
      Stock::Quantifier.new(variant_id).can_supply? quantity
    end

    def insufficient_stock?
      !sufficient_stock?
    end

    # Remove product default_scope `deleted_at: nil`
    def product
      variant.product
    end

    # Remove variant default_scope `deleted_at: nil`
    def variant
      Spree::Variant.unscoped { super }
    end

    private
      def update_inventory
        if changed?
          Spree::OrderInventory.new(self.order, self).verify(target_shipment)
        end
      end

      def update_adjustments
        if quantity_changed?
          recalculate_adjustments
        end
      end

      def recalculate_adjustments
        Spree::ItemAdjustments.new(self).update
      end

      def create_tax_charge
        Spree::TaxRate.adjust(order.tax_zone, [self])
      end

      def ensure_proper_currency
        unless currency == order.currency
          errors.add(:currency, t(:must_match_order_currency))
        end
      end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * Tracing proxy JDBC driver.  Traces calls to another JDBC driver.
 *
 * @see TracingProxyDriver
 */
package org.apache.drill.jdbc.proxy;


text:
package mf.org.apache.xerces.util;

import mf.org.apache.xerces.impl.Constants;
import mf.org.apache.xerces.xni.XMLAttributes;

import org.xml.sax.AttributeList;
import org.xml.sax.ext.Attributes2;

/**
 * Wraps {@link XMLAttributes} and makes it look like
 * {@link AttributeList} and {@link Attributes2}.
 *
 * @author Arnaud Le Hors, IBM
 * @author Andy Clark, IBM
 *
 * @version $Id: AttributesProxy.java 449487 2006-09-24 21:11:28Z mrglavas $
 */
public final class AttributesProxy
    implements AttributeList, Attributes2 {

    //
    // Data
    //

    /** XML attributes. */
    private XMLAttributes fAttributes;

    //
    // Constructors
    //

    public AttributesProxy(XMLAttributes attributes) {
        fAttributes = attributes;
    }

    //
    // Public methods
    //

    /** Sets the XML attributes to be wrapped. */
    public void setAttributes(XMLAttributes attributes) {
        fAttributes = attributes;
    } // setAttributes(XMLAttributes)

    public XMLAttributes getAttributes() {
        return fAttributes;
    }

    /*
     * Attributes methods
     */

    public int getLength() {
        return fAttributes.getLength();
    }

    public String getQName(int index) {
        return fAttributes.getQName(index);
    }

    public String getURI(int index) {
        // This hides the fact that internally we use null instead of empty string
        // SAX requires the URI to be a string or an empty string
        String uri = fAttributes.getURI(index);
        return uri != null ? uri : XMLSymbols.EMPTY_STRING;
    }

    public String getLocalName(int index) {
        return fAttributes.getLocalName(index);
    }

    public String getType(int i) {
        return fAttributes.getType(i);
    }

    public String getType(String name) {
        return fAttributes.getType(name);
    }

    public String getType(String uri, String localName) {
        return uri.equals(XMLSymbols.EMPTY_STRING) ?
                fAttributes.getType(null, localName) :
                    fAttributes.getType(uri, localName);
    }

    public String getValue(int i) {
        return fAttributes.getValue(i);
    }

    public String getValue(String name) {
        return fAttributes.getValue(name);
    }

    public String getValue(String uri, String localName) {
        return uri.equals(XMLSymbols.EMPTY_STRING) ?
                fAttributes.getValue(null, localName) :
                    fAttributes.getValue(uri, localName);
    }

    public int getIndex(String qName) {
        return fAttributes.getIndex(qName);
    }

    public int getIndex(String uri, String localPart) {
        return uri.equals(XMLSymbols.EMPTY_STRING) ?
                fAttributes.getIndex(null, localPart) :
                    fAttributes.getIndex(uri, localPart);
    }

    /*
     * Attributes2 methods
     */

    public boolean isDeclared(int index) {
        if (index < 0 || index >= fAttributes.getLength()) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return Boolean.TRUE.equals(
            fAttributes.getAugmentations(index).getItem(
            Constants.ATTRIBUTE_DECLARED));
    }

    public boolean isDeclared(String qName) {
        int index = getIndex(qName);
        if (index == -1) {
            throw new IllegalArgumentException(qName);
        }
        return Boolean.TRUE.equals(
            fAttributes.getAugmentations(index).getItem(
            Constants.ATTRIBUTE_DECLARED));
    }

    public boolean isDeclared(String uri, String localName) {
        int index = getIndex(uri, localName);
        if (index == -1) {
            throw new IllegalArgumentException(localName);
        }
        return Boolean.TRUE.equals(
            fAttributes.getAugmentations(index).getItem(
            Constants.ATTRIBUTE_DECLARED));
    }

    public boolean isSpecified(int index) {
        if (index < 0 || index >= fAttributes.getLength()) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return fAttributes.isSpecified(index);
    }

    public boolean isSpecified(String qName) {
        int index = getIndex(qName);
        if (index == -1) {
            throw new IllegalArgumentException(qName);
        }
        return fAttributes.isSpecified(index);
    }

    public boolean isSpecified(String uri, String localName) {
        int index = getIndex(uri, localName);
        if (index == -1) {
            throw new IllegalArgumentException(localName);
        }
        return fAttributes.isSpecified(index);
    }

    /*
     * AttributeList methods
     */

    public String getName(int i) {
        return fAttributes.getQName(i);
    }

}


text:
module SSTG.Core.Execution.Support
    ( SymbolicT(..)
    , fmap
    , pure
    , (<*>)
    , return
    , (>>=)

    , State(..)
    , Symbol(..)
    , Status(..)
    , Stack
    , Frame(..)
    , MemAddr
    , Val(..)
    , Locals
    , Heap
    , HeapRhs(..)
    , HeapObj(..)
    , Globals
    , Code(..)
    , PathCons
    , Constraint(..)

    , null_addr
    , memAddrInt

    , init_status
    , incStatusSteps
    , updateStatusId

    , empty_stack
    , popStack
    , pushStack
    , stackToList

    , empty_locals
    , lookupLocals
    , insertLocalsVal
    , insertLocalsVals
    , localsToList

    , empty_heap
    , lookupHeap
    , insertHeapObj
    , insertHeapObjs
    , insertHeapRedir
    , allocHeapObj
    , allocHeapObjs
    , heapToList

    , empty_globals
    , lookupGlobals
    , insertGlobalsVal
    , insertGlobalsVals
    , globalsToList

    , empty_pathcons
    , insertPathCons
    , insertPathConss
    , pathConsToList

    , lookupVal
    , vlookupHeap
    , memAddrType
    ) where

import SSTG.Core.Language

import qualified Data.Map as M

-- | Symbolic Transformation represents transformations applied to some
-- State`(s). This is useful in allowing us to transfer from different actions
-- within the engine.
newtype SymbolicT s a = SymbolicT { run :: s -> (s, a) }

-- | Functor instance of Symbolic Transformation.
instance Functor (SymbolicT s) where
    fmap f st = SymbolicT (\s0 -> let (s1, a1) = (run st) s0 in (s1, f a1))

-- | Applicative instance of Symbolic Transformation.
instance Applicative (SymbolicT s) where
    pure a = SymbolicT (\s -> (s, a))

    sf <*> st = SymbolicT (\s0 -> let (s1, a1) = (run st) s0
                                      (s2, f2) = (run sf) s1 in (s2, f2 a1))

-- | Monad instance of Symbolic Transformation.
instance Monad (SymbolicT s) where
    return a = pure a

    st >>= fs = SymbolicT (\s0 -> let (s1, a1) = (run st) s0
                                      (s2, a2) = (run (fs a1)) s1 in (s2, a2))

-- | `State` contains the information necessary to perform symbolic execution.
-- Eval/Apply graph reduction semantics are used.
data State = State { state_status :: !Status
                   , state_stack :: !Stack
                   , state_heap :: !Heap
                   , state_globals :: !Globals
                   , state_code :: !Code
                   , state_names :: ![Name]
                   , state_path :: !PathCons
                   } deriving (Show, Eq, Read)

-- | Symbolic variables. The @Maybe (Expr, Locals)@ can be used to trace the
-- source from which the symbolic variable was generated. For instance, this
-- is useful during symbolic function application.
data Symbol = Symbol Var (Maybe (Expr, Locals)) deriving (Show, Eq, Read)

-- | State status.
data Status = Status { status_id :: !Int
                     , status_parent :: !Int
                     , status_steps :: !Int
                     } deriving (Show, Eq, Read)

-- | Execution stack used in graph reduction semnatics.
newtype Stack = Stack [Frame] deriving (Show, Eq, Read)

-- | Frames of a stack.
data Frame = CaseFrame Var [Alt] Locals
           | ApplyFrame [Atom] Locals
           | UpdateFrame MemAddr
           deriving (Show, Eq, Read)

-- | Memory address for things on the `Heap`.
newtype MemAddr = MemAddr Int deriving (Show, Eq, Read, Ord)

-- | A `Val` is something that we aim to reduce our current expression down
-- into. `MemAddr` is a pointer to an object on the heap, such as `FunObj` or
-- `ConObj`, which are "returned" from expression evaluation in this form.
data Val = LitVal Lit
         | MemVal MemAddr
         deriving (Show, Eq, Read)

-- | Locals binds a `Var`'s `Name` to its some `Val`.
newtype Locals = Locals (M.Map Name Val) deriving (Show, Eq, Read)

-- | Heaps map `MemAddr` to `HeapObj`, while keeping track of the last address
-- that was allocated. This allows us to consistently allocate fresh addresses
-- on the `Heap`.
data Heap = Heap (M.Map MemAddr HeapRhs) MemAddr deriving (Show, Eq, Read)

-- | When we look up a `Heap`, we get an intermediary `MemAddr` for lookup
-- redirection, or just the `HeapObj` itself.
data HeapRhs = HeapRedir MemAddr
             | HeapObj HeapObj
             deriving (Show, Eq, Read)

-- | Heap objects.
data HeapObj = LitObj Lit
             | SymObj Symbol
             | ConObj DataCon [Val]
             | FunObj [Var] Expr Locals
             | Blackhole
             deriving (Show, Eq, Read)

-- | Globals are statically loaded at the time when a `State` is loaded.
-- However, because uninterpreted / out-of-scope variables are made symbolic
-- at runtime, it can be modified during execution.
newtype Globals = Globals (M.Map Name Val) deriving (Show, Eq, Read)

-- | Evaluation of the current expression. We are either evaluating, or ready
-- to return with some `Val`.
data Code = Evaluate Expr Locals
          | Return Val
          deriving (Show, Eq, Read)

-- | Path constraints are the conjunctive normal form of `Constraint`s.
newtype PathCons = PathCons [Constraint] deriving (Show, Eq, Read)

-- | Constraints denote logical paths taken in program execution thus far.
data Constraint = Constraint AltCon Var Locals Bool deriving (Show, Eq, Read)

-- Simple functions that require only the immediate data structure.

-- | Null `MemAddr`.
null_addr :: MemAddr
null_addr = MemAddr 0

-- | `MemAddr`'s `Int` value.
memAddrInt :: MemAddr -> Int
memAddrInt (MemAddr int) = int

-- | Initial `Status`.
init_status :: Status
init_status = Status { status_id = 1
                     , status_parent = 0
                     , status_steps = 0 }

-- | Increment `Status` steps.
incStatusSteps :: Status -> Status
incStatusSteps status = status { status_steps = (status_steps status) + 1 }

-- | Update the `Status` id.
updateStatusId :: Int -> Status -> Status
updateStatusId int status = status { status_id = int
                                   , status_parent = status_id status }

-- | Empty `Stack.
empty_stack :: Stack
empty_stack = Stack []

-- | `Stack` pop.
popStack :: Stack -> Maybe (Frame, Stack)
popStack (Stack []) = Nothing
popStack (Stack (frame:fs)) = Just (frame, Stack fs)

-- | `Stack` push.
pushStack :: Frame -> Stack -> Stack
pushStack frame (Stack frames) = Stack (frame : frames)

-- | `Stack` as list of `Frame`s.
stackToList :: Stack -> [Frame]
stackToList (Stack frames) = frames

-- | Empty `Locals`.
empty_locals :: Locals
empty_locals = Locals M.empty

-- | `Locals` lookup.
lookupLocals :: Var -> Locals -> Maybe Val
lookupLocals var (Locals lmap) = M.lookup (varName var) lmap

-- | `Locals` insertion.
insertLocalsVal :: Var -> Val -> Locals -> Locals
insertLocalsVal k v (Locals lmap) = Locals (M.insert (varName k) v lmap)

-- | List insertion into `Locals`.
insertLocalsVals :: [(Var, Val)] -> Locals -> Locals
insertLocalsVals kvs locals = foldr (uncurry insertLocalsVal) locals kvs

-- | `Locals` to key value pairs.
localsToList :: Locals -> [(Name, Val)]
localsToList (Locals lmap) = M.toList lmap

-- | Empty `Heap`.
empty_heap :: Heap
empty_heap = Heap M.empty null_addr

-- | `Heap` lookup.
lookupHeap :: MemAddr -> Heap -> Maybe HeapObj
lookupHeap addr (Heap hmap p) = case M.lookup addr hmap of
    Just (HeapRedir redir) -> lookupHeap redir (Heap hmap p)
    Just (HeapObj hobj) -> Just hobj
    Nothing -> Nothing

-- | `Heap` direct insertion at a specific `MemAddr`.
insertHeapObj :: MemAddr -> HeapObj -> Heap -> Heap
insertHeapObj k v (Heap hmap p) = Heap (M.insert k (HeapObj v) hmap) p

-- | Insert a list of `HeapObj` at specified `MemAddr` locations.
insertHeapObjs :: [(MemAddr, HeapObj)] -> Heap -> Heap
insertHeapObjs kvs heap = foldr (uncurry insertHeapObj) heap kvs

-- | Insert a redirection `MemAddr` into the `Heap`.
insertHeapRedir :: MemAddr -> MemAddr -> Heap -> Heap
insertHeapRedir a r (Heap hmap p) = Heap (M.insert a (HeapRedir r) hmap) p

-- | `Heap` allocation. Updates the last `MemAddr` kept in the `Heap`.
allocHeapObj :: HeapObj -> Heap -> (Heap, MemAddr)
allocHeapObj hobj (Heap hmap p) = (heap', addr)
  where
    addr = MemAddr ((memAddrInt p) + 1)
    heap' = insertHeapObj addr hobj (Heap hmap addr)

-- | Allocate a list of `HeapObj` in a `Heap`, returning in the same order the
-- `MemAddr` at which they have been allocated at.
allocHeapObjs :: [HeapObj] -> Heap -> (Heap, [MemAddr])
allocHeapObjs [] heap = (heap, [])
allocHeapObjs (hobj:hs) heap = (heapf, addr : as)
  where
    (heap', addr) = allocHeapObj hobj heap
    (heapf, as) = allocHeapObjs hs heap'

-- | `Heap` to key value pairs.
heapToList :: Heap -> [(MemAddr, HeapRhs)]
heapToList (Heap hmap _) = M.toList hmap

-- | Empty `Globals`.
empty_globals :: Globals
empty_globals = Globals M.empty

-- | `Globals` lookup.
lookupGlobals :: Var -> Globals -> Maybe Val
lookupGlobals var (Globals gmap) = M.lookup (varName var) gmap

-- | `Globals` insertion.
insertGlobalsVal :: Var -> Val -> Globals -> Globals
insertGlobalsVal k v (Globals gmap) = Globals (M.insert (varName k) v gmap)

-- | Insert a list of `Var` and `Val` pairs into `Globals`. This would
-- typically occur for new symbolic variables created from uninterpreted /
-- out-of-scope variables during runtime.
insertGlobalsVals :: [(Var, Val)] -> Globals -> Globals
insertGlobalsVals kvs globals = foldr (uncurry insertGlobalsVal) globals kvs

-- | `Globals` to key value pairs.
globalsToList :: Globals -> [(Name, Val)]
globalsToList (Globals gmap) = M.toList gmap

-- | Empty `PathCons`.
empty_pathcons :: PathCons
empty_pathcons = PathCons []

-- | `PathCons` insertion.
insertPathCons :: Constraint -> PathCons -> PathCons
insertPathCons cons (PathCons conss) = PathCons (cons : conss)

-- | Insert a list of `Constraint`s into a `PathCons`.
insertPathConss :: [Constraint] -> PathCons -> PathCons
insertPathConss conss pathcons = foldr insertPathCons pathcons conss

-- | `PathCons` to list of `Constraint`s.
pathConsToList :: PathCons -> [Constraint]
pathConsToList (PathCons conss) = conss

-- Complex functions that involve multiple data structures.

-- | `Val` lookup from the `Locals` first, then `Globals`.
lookupVal :: Var -> Locals -> Globals -> Maybe Val
lookupVal var locals globals = case lookupLocals var locals of
    Just val -> Just val
    Nothing -> lookupGlobals var globals

-- | `Heap` lookup. Returns the appropriate. `MemAddr` and `HeapObj` if found.
vlookupHeap :: Var -> Locals -> Globals -> Heap -> Maybe (MemAddr, HeapObj)
vlookupHeap var locals globals heap = do
    val <- lookupVal var locals globals
    case val of
        LitVal _ -> Nothing
        MemVal addr -> lookupHeap addr heap >>= \hobj -> Just (addr, hobj)

-- | Type of `HeapObj` held at `MemAddr`, if found.
memAddrType :: MemAddr -> Heap -> Maybe Type
memAddrType addr heap = do
    hobj <- lookupHeap addr heap
    case hobj of
        LitObj lit -> Just (typeOf lit)
        SymObj (Symbol svar _) -> Just (typeOf svar)
        ConObj dcon _ -> Just (typeOf dcon)
        FunObj ps expr _ -> Just (foldr FunTy (typeOf expr) (map typeOf ps))
        Blackhole -> Just Bottom


text:
<?php namespace Neomerx\JsonApi\Encoder\Parser;

use \Neomerx\JsonApi\Factories\Exceptions;
use \Neomerx\JsonApi\Contracts\Encoder\Stack\StackReadOnlyInterface;

/**
 * @package Neomerx\JsonApi
 */
class ParserEmptyReply extends BaseReply
{
    /**
     * @param int                    $replyType
     * @param StackReadOnlyInterface $stack
     */
    public function __construct($replyType, StackReadOnlyInterface $stack)
    {
        $isOk = ($replyType === self::REPLY_TYPE_NULL_RESOURCE_STARTED ||
            $replyType === self::REPLY_TYPE_EMPTY_RESOURCE_STARTED);
        $isOk ?: Exceptions::throwInvalidArgument('replyType', $replyType);

        parent::__construct($replyType, $stack);
    }
}


text:
/**
 * @ignore
 */
exports['Should correctly connect to server using domain socket'] = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var db = configuration.newDbInstanceWithDomainSocket({w:1}, {poolSize: 1, host: "/tmp/mongodb-27017.sock"});
    db.open(function(err, db) {
      test.equal(null, err);

      db.collection("domainSocketCollection0").insert({a:1}, {w:1}, function(err, item) {
        test.equal(null, err);

        db.collection("domainSocketCollection0").find({a:1}).toArray(function(err, items) {
          test.equal(null, err);
          test.equal(1, items.length);

          db.close();
          test.done();
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should connect to server using domain socket with undefined port'] = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var db = configuration.newDbInstanceWithDomainSocket({w:1}, {poolSize: 1, host: "/tmp/mongodb-27017.sock", port:undefined});
    db.open(function(err, db) {
      test.equal(null, err);

      db.collection("domainSocketCollection1").insert({x:1}, {w:1}, function(err, item) {
        test.equal(null, err);

        db.collection("domainSocketCollection1").find({x:1}).toArray(function(err, items) {
          test.equal(null, err);
          test.equal(1, items.length);

          db.close();
          test.done();
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should fail to connect using non-domain socket with undefined port'] = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Server = configuration.require.Server
      , Db = configuration.require.Db;

    var error;
    try {
      var db = new Db('test', new Server("localhost", undefined), {w:0});
      db.open(function(){ });
    } catch (err){
      error = err;
    }

    test.ok(error instanceof Error);
    test.ok(/port must be specified/.test(error));
    test.done();
  }
}

/**
 * @ignore
 */
function connectionTester(test, testName, callback) {
  return function(err, db) {
    test.equal(err, null);
    db.collection(testName, function(err, collection) {
      test.equal(err, null);
      var doc = {foo:123};
      collection.insert({foo:123}, {w:1}, function(err, docs) {
        test.equal(err, null);
        db.dropDatabase(function(err, done) {
          db.close();
          test.equal(err, null);
          test.ok(done);
          if(callback) return callback(db);
          test.done();
        });
      });
    });
  };
};

/**
 * @ignore
 */
exports.testConnectNoOptions = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;

    connect(configuration.url(), connectionTester(test, 'testConnectNoOptions', function(db) {
      test.done();
    }));
  }
}

/**
 * @ignore
 */
exports.testConnectServerOptions = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;

    connect(configuration.url(),
            { server: {auto_reconnect: true, poolSize: 4} },
            connectionTester(test, 'testConnectServerOptions', function(db) {
      test.equal(4, db.serverConfig.poolSize);
      test.equal(true, db.serverConfig.autoReconnect);
      test.done();
    }));
  }
}

/**
 * @ignore
 */
exports.testConnectAllOptions = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;

    connect(configuration.url(),
            { server: {auto_reconnect: true, poolSize: 4},
              db: {native_parser: (process.env['TEST_NATIVE'] != null)} },
            connectionTester(test, 'testConnectAllOptions', function(db) {
      test.equal(4, db.serverConfig.poolSize);
      test.equal(true, db.serverConfig.autoReconnect);
      test.done();
    }));
  }
}

/**
 * @ignore
 */
exports.testConnectGoodAuth = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;
    var user = 'testConnectGoodAuth', password = 'password';
    // First add a user.
    connect(configuration.url(), function(err, db) {
      test.equal(err, null);

      db.addUser(user, password, function(err, result) {
        test.equal(err, null);
        db.close();
        restOfTest();
      });
    });

    function restOfTest() {
      connect(configuration.url(user, password), connectionTester(test, 'testConnectGoodAuth', function(db) {
        test.done();
      }));
    }
  }
}

/**
 * @ignore
 */
exports.testConnectBadAuth = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;

    connect(configuration.url('slithy', 'toves'), function(err, db) {
      test.ok(err);
      test.equal(null, db);
      test.done();
    });
  }
}

/**
 * @ignore
 */
exports.testConnectThrowsNoCallbackProvided = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var connect = configuration.require;

    test.throws(function() {
      var db = connect(configuration.url());
    });
    test.done();
  }
}

/**
 * @ignore
 */
exports.testConnectBadUrl = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    test.throws(function() {
      connect('mangodb://localhost:27017/test?safe=false', function(err, db) {
        test.ok(false, 'Bad URL!');
      });
    });
    test.done();
  }
}

/**
 * @ignore
 */
exports.shouldCorrectlyReturnTheRightDbObjectOnOpenEmit = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var db_conn = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false});
    var db2 = db_conn.db("test2");

    db2.on('open', function (err, db) {
      test.equal(db2.databaseName, db.databaseName);
    });

    db_conn.on('open', function (err, db) {
      test.equal(db_conn.databaseName, db.databaseName);
    });

    db_conn.open(function (err) {
      if(err) throw err;
      var col1 = db_conn.collection('test');
      var col2 = db2.collection('test');

      var testData = { value : "something" };
      col1.insert(testData, function (err) {
        if (err) throw err;
        col2.insert(testData, function (err) {
          if (err) throw err;
          db2.close();
          test.done();
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports.shouldCorrectlyReturnFalseOnIsConnectBeforeConnectionHappened = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var db_conn = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false});
    test.equal(false, db_conn.serverConfig.isConnected());
    test.done();
  }
}

/**
 * @ignore
 */
exports['Should correctly reconnect and finish query operation'] = {
  metadata: { requires: { topology: 'single' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Db = configuration.require.Db
      , MongoClient = configuration.require.MongoClient
      , Server = configuration.require.Server;

    var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:true});
    db.open(function(err, db) {
      test.equal(null, err);

      db.collection('test_reconnect').insert({a:1}, function(err, doc) {
        test.equal(null, err);

        db.serverConfig.once('reconnect', function() {

          // Await reconnect and re-authentication
          db.collection('test_reconnect').findOne(function(err, doc) {
            test.equal(null, err);
            test.equal(1, doc.a);

            // Attempt disconnect again
            db.serverConfig.connections()[0].destroy();

            // Await reconnect and re-authentication
            db.collection('test_reconnect').findOne(function(err, doc) {
              test.equal(null, err);
              test.equal(1, doc.a);

              db.close();
              test.done();
            });
          });
        })

        // Force close
        db.serverConfig.connections()[0].destroy();
      });
    });
  }
}


text:
Contains function definitions for the Windows API library wuguid. See winapi for types and constants.

```toml
[dependencies]
wuguid-sys = "0.0.1"
```

```rust
extern crate wuguid;
```

[Documentation](https://retep998.github.io/doc/wuguid/)


text:
#import <Foundation/Foundation.h>

@interface EBDateFormatter : NSObject

/* ## Creation */
/* If 'locale' is nil, [NSLocale currentLocale] is used.
   If 'timeZone' is nil, [NSTimeZone defaultTimeZone] is used. */
- (instancetype)initWithFormat: (NSString *)format locale: (NSLocale *)locale timeZone: (NSTimeZone *)timeZone;

/* ## Methods */
- (NSString *)stringFromDate: (NSDate *)date;
- (NSDate *)dateFromString: (NSString *)dateString;

@end


text:
<!DOCTYPE html>

    <title>Extension Console</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="styles/main.css">
    <link rel="icon" type="image/png" href="favicon.gif">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

              </button>

                <form class="navbar-form" role="search">

                    <input type="text" class="form-control" placeholder="Search nothing now..." name="srch-term" id="srch-term">

                      <button class="btn btn-default" type="submit"></button>

                </form>

MES Console Makes Your Life Easier

View Extensions

View Executions

                {{selectedItem}}

Register Extension

Manage Extension

Separated link

One more separated link


text:
function CambiarCSS() {
	document.getElementById("partePrincipal").style.backgroundColor = '#FF9933';
}


text:
package stray.blocks;

import stray.entity.Entity;
import stray.entity.EntityLiving;
import stray.util.MathHelper;
import stray.world.World;

public class BlockFire extends Block {

	public BlockFire(String path) {
		super(path);
	}

	@Override
	public void tickUpdate(World world, int x, int y) {
		for (Entity e : world.entities) {
			if (e instanceof EntityLiving) {
				if (MathHelper.intersects(x, y, 2, 1, e.x, e.y, e.sizex, e.sizey)) {
					((EntityLiving) e).setFire(1);
				}
			}
		}
	}

	@Override
	public boolean isRenderedFront() {
		return true;
	}

}


text:
using namespace std;

int main()
{
	char choice = 'y';
	string firstname;
	string matrix;
	string course;
	string combine;

	while(choice == 'y' || choice == 'Y'){

		cout << "Please enter your first name : ";
		cin.get();
		getline(cin,firstname);

		cout << "Please enter your matrix number : ";
		cin.get();
		getline(cin,matrix);

		cout << "Please enter your course : ";
		cin.get();
		getline(cin,course);

		cout << firstname << " " << matrix << " "<< course  << endl;

		combine = firstname + " - " + matrix + " - " + course;

  		std::transform(combine.begin(), combine.end(),combine.begin(), ::toupper);

		cout << combine << endl;

		cout << "Do you want to continue ? (Y to continue) : ";
		cin >> choice;
	}

	return 0;
}


text:
package me.jeffshaw.scalaz.stream

import scalaz.concurrent.Task
import scalaz.stream._

object ProcessIoIteratorConstructors {
  /**
   * Create a Process from an iterator that requires some external or
   * other mutable resource, while ensuring that the resource is released.
   *
   * Use `iterators` if the resource is associated with multiple iterators.
   */
  def iterator[R, O](
    acquire: Task[R]
  )(createIterator: R => Task[Iterator[O]]
  )(release: R => Task[Unit]
  ): Process[Task, O] = {
    Process.await(acquire)(r => Process.await(createIterator(r))(IteratorConstructors.iteratorGo).onComplete(Process.eval_(release(r))))
  }

  /**
   * Create a Process from an external resource associated with multiple
   * iterators, while ensuring that the resource is released.
   *
   * Use `merge.mergeN` on the result to interleave the iterators, or
   * .flatMap(identity) to emit them in order.
   *
   * @param maxOpen Max number of open (running) processes at a time
   */
  def iterators[R, O](
    maxOpen: Int
  )(acquire: Task[R]
  )(createIterators: R => Task[Iterable[Iterator[O]]]
  )(release: R => Task[Unit]
  ): Process[Task, O] = {
    def createIteratorProcesses(r: R): Task[Iterable[Process[Task, O]]] = {
      for {
        iterators <- createIterators(r)
      } yield iterators.map(iterator => IteratorConstructors.iteratorGo(iterator))
    }
    Process.await(acquire) { r =>
      merge.mergeN(maxOpen)(Process.await(createIteratorProcesses(r)) { iterators =>
        Process.emitAll(iterators.toSeq)
      }).onComplete(Process.eval_(release(r)))
    }
  }

  /**
   * Create a Process from an external resource associated with multiple
   * iterators, while ensuring that the resource is released.
   *
   * Use `merge.mergeN` on the result to interleave the iterators, or
   * .flatMap(identity) to emit them in order.
   */
  def iterators[R, O](
    acquire: Task[R]
  )(createIterators: R => Task[Iterable[Iterator[O]]]
  )(release: R => Task[Unit]
  ): Process[Task, O] = {
    iterators[R, O](0)(acquire)(createIterators)(release)
  }

}


text:
package com.testdomain;

import java.io.Serializable;

public class TopicDescription implements Serializable {

  private String description;

  /*
   * @return Returns the topicDescription.
   */
  public String getDescription() {
    return description;
  }

  /*
   * @param topicDescription The topicDescription to set.
   */
  public void setDescription(String description) {
    this.description = description;
  }
}


text:
<?php

declare(strict_types=1);

namespace Kreait\Firebase;

use Beste\Json;
use Kreait\Firebase\Exception\RemoteConfig\VersionNotFound;
use Kreait\Firebase\RemoteConfig\ApiClient;
use Kreait\Firebase\RemoteConfig\FindVersions;
use Kreait\Firebase\RemoteConfig\Template;
use Kreait\Firebase\RemoteConfig\Version;
use Kreait\Firebase\RemoteConfig\VersionNumber;
use Psr\Http\Message\ResponseInterface;
use Traversable;

use function array_shift;
use function is_string;

/**
 * @internal
 *
 * @phpstan-import-type RemoteConfigTemplateShape from Template
 */
final class RemoteConfig implements Contract\RemoteConfig
{
    private ApiClient $client;

    public function __construct(ApiClient $client)
    {
        $this->client = $client;
    }

    public function get(): Template
    {
        return $this->buildTemplateFromResponse($this->client->getTemplate());
    }

    public function validate($template): void
    {
        $this->client->validateTemplate($this->ensureTemplate($template));
    }

    public function publish($template): string
    {
        $etag = $this->client
            ->publishTemplate($this->ensureTemplate($template))
            ->getHeader('ETag');

        $etag = array_shift($etag);

        if (!is_string($etag)) {
            return '*';
        }

        if ($etag === '') {
            return '*';
        }

        return $etag;
    }

    public function getVersion(VersionNumber|int|string $versionNumber): Version
    {
        $versionNumber = $this->ensureVersionNumber($versionNumber);

        foreach ($this->listVersions() as $version) {
            if ($version->versionNumber()->equalsTo($versionNumber)) {
                return $version;
            }
        }

        throw VersionNotFound::withVersionNumber($versionNumber);
    }

    public function rollbackToVersion(VersionNumber|int|string $versionNumber): Template
    {
        $versionNumber = $this->ensureVersionNumber($versionNumber);

        return $this->buildTemplateFromResponse($this->client->rollbackToVersion($versionNumber));
    }

    public function listVersions($query = null): Traversable
    {
        $query = $query instanceof FindVersions ? $query : FindVersions::fromArray((array) $query);
        $pageToken = null;
        $count = 0;
        $limit = $query->limit();

        do {
            $response = $this->client->listVersions($query, $pageToken);
            $result = Json::decode((string) $response->getBody(), true);

            foreach ((array) ($result['versions'] ?? []) as $versionData) {
                ++$count;

                yield Version::fromArray($versionData);

                if ($count === $limit) {
                    return;
                }
            }

            $pageToken = $result['nextPageToken'] ?? null;
        } while ($pageToken);
    }

    /**
     * @param Template|RemoteConfigTemplateShape $value
     */
    private function ensureTemplate($value): Template
    {
        return $value instanceof Template ? $value : Template::fromArray($value);
    }

    /**
     * @param VersionNumber|int|string $value
     */
    private function ensureVersionNumber($value): VersionNumber
    {
        return $value instanceof VersionNumber ? $value : VersionNumber::fromValue($value);
    }

    private function buildTemplateFromResponse(ResponseInterface $response): Template
    {
        $etagHeader = $response->getHeader('ETag');
        $etag = array_shift($etagHeader) ?: '*';

        $data = Json::decode((string) $response->getBody(), true);

        return Template::fromArray($data, $etag);
    }
}


text:
package api

import (
	"time"

	"k8s.io/apimachinery/pkg/api/resource"
)

// Signal defines a signal that can trigger eviction of pods on a node.
type Signal string

const (
	// SignalMemoryAvailable is memory available (i.e. capacity - workingSet), in bytes.
	SignalMemoryAvailable Signal = "memory.available"
	// SignalNodeFsAvailable is amount of storage available on filesystem that kubelet uses for volumes, daemon logs, etc.
	SignalNodeFsAvailable Signal = "nodefs.available"
	// SignalNodeFsInodesFree is amount of inodes available on filesystem that kubelet uses for volumes, daemon logs, etc.
	SignalNodeFsInodesFree Signal = "nodefs.inodesFree"
	// SignalImageFsAvailable is amount of storage available on filesystem that container runtime uses for storing images and container writable layers.
	SignalImageFsAvailable Signal = "imagefs.available"
	// SignalImageFsInodesFree is amount of inodes available on filesystem that container runtime uses for storing images and container writable layers.
	SignalImageFsInodesFree Signal = "imagefs.inodesFree"
	// SignalAllocatableMemoryAvailable is amount of memory available for pod allocation (i.e. allocatable - workingSet (of pods), in bytes.
	SignalAllocatableMemoryAvailable Signal = "allocatableMemory.available"
	// SignalPIDAvailable is amount of PID available for pod allocation
	SignalPIDAvailable Signal = "pid.available"
)

// ThresholdOperator is the operator used to express a Threshold.
type ThresholdOperator string

const (
	// OpLessThan is the operator that expresses a less than operator.
	OpLessThan ThresholdOperator = "LessThan"
)

// OpForSignal maps Signals to ThresholdOperators.
// Today, the only supported operator is "LessThan". This may change in the future,
// for example if "consumed" (as opposed to "available") type signals are added.
// In both cases the directionality of the threshold is implicit to the signal type
// (for a given signal, the decision to evict will be made when crossing the threshold
// from either above or below, never both). There is thus no reason to expose the
// operator in the Kubelet's public API. Instead, we internally map signal types to operators.
var OpForSignal = map[Signal]ThresholdOperator{
	SignalMemoryAvailable:   OpLessThan,
	SignalNodeFsAvailable:   OpLessThan,
	SignalNodeFsInodesFree:  OpLessThan,
	SignalImageFsAvailable:  OpLessThan,
	SignalImageFsInodesFree: OpLessThan,
	SignalPIDAvailable:      OpLessThan,
}

// ThresholdValue is a value holder that abstracts literal versus percentage based quantity
type ThresholdValue struct {
	// The following fields are exclusive. Only the topmost non-zero field is used.

	// Quantity is a quantity associated with the signal that is evaluated against the specified operator.
	Quantity *resource.Quantity
	// Percentage represents the usage percentage over the total resource that is evaluated against the specified operator.
	Percentage float32
}

// Threshold defines a metric for when eviction should occur.
type Threshold struct {
	// Signal defines the entity that was measured.
	Signal Signal
	// Operator represents a relationship of a signal to a value.
	Operator ThresholdOperator
	// Value is the threshold the resource is evaluated against.
	Value ThresholdValue
	// GracePeriod represents the amount of time that a threshold must be met before eviction is triggered.
	GracePeriod time.Duration
	// MinReclaim represents the minimum amount of resource to reclaim if the threshold is met.
	MinReclaim *ThresholdValue
}

// GetThresholdQuantity returns the expected quantity value for a thresholdValue
func GetThresholdQuantity(value ThresholdValue, capacity *resource.Quantity) *resource.Quantity {
	if value.Quantity != nil {
		return value.Quantity.Copy()
	}
	return resource.NewQuantity(int64(float64(capacity.Value())*float64(value.Percentage)), resource.BinarySI)
}


text:
namespace lightex {
namespace html_converter {

struct Result {
  bool is_successful;

  std::string escaped;
  std::string unescaped;
  std::string error_message;

  bool breaks_paragraph;

  static Result Failure(const std::string& error_message);
  static Result Success(const std::string& escaped, const std::string& unescaped, bool breaks_paragraph = false);
};

class HtmlVisitor : public boost::static_visitor<Result> {
 public:
  HtmlVisitor() {}

  Result operator()(const ast::Program& program);
  Result operator()(const ast::PlainText& plain_text);
  Result operator()(const ast::Paragraph& paragraph);
  Result operator()(const ast::ParagraphBreaker& paragraph_breaker);
  Result operator()(const ast::Argument& argument);
  Result operator()(const ast::ArgumentRef& argument_ref);
  Result operator()(const ast::OuterArgumentRef& outer_argument_ref);
  Result operator()(const ast::InlinedMathText& inlined_math_text);
  Result operator()(const ast::MathText& math_text);
  Result operator()(const ast::CommandMacro& command_macro);
  Result operator()(const ast::EnvironmentMacro& environment_macro);
  Result operator()(const ast::Command& command);
  Result operator()(const ast::UnescapedCommand& unescaped_command);
  Result operator()(const ast::NparagraphCommand& nparagraph_command);
  Result operator()(const ast::Environment& environment);
  Result operator()(const ast::VerbatimEnvironment& verbatim_environment);

 private:
  template <typename Node>
  Result JoinNodeResults(const std::list<Node>& nodes);

  template <typename Macro, typename MacroDefinition>
  Result PrepareMacroArguments(const Macro& macro,
                               const MacroDefinition& macro_definition,
                               std::vector<Result>* output_args);

  const ast::CommandMacro* GetDefinedCommandMacro(const std::string& name) const;
  const ast::EnvironmentMacro* GetDefinedEnvironmentMacro(const std::string& name) const;
  const Result* GetArgumentByReference(int index, bool is_outer) const;

  int active_environment_definitions_num_ = 0;
  int math_text_span_num_ = 0;
  std::vector<std::vector<Result>> arguments_stack_;

  std::list<ast::CommandMacro> defined_command_macros_;
  std::list<ast::EnvironmentMacro> defined_environment_macros_;
};

}  // namespace html_converter
}  // namespace lightex


text:
package com.horcrux.svg;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.TouchEvent;
import com.facebook.react.uimanager.events.TouchEventCoalescingKeyHelper;
import com.facebook.react.uimanager.events.TouchEventType;
import com.facebook.react.uimanager.events.EventDispatcher;

import javax.annotation.Nullable;

/**
 * Custom {@link View} implementation that draws an RNSVGSvg React view and its \childrn.
 */
public class SvgView extends View {
    public enum Events {
        EVENT_DATA_URL("onDataURL");

        private final String mName;

        Events(final String name) {
            mName = name;
        }

        @Override
        public String toString() {
            return mName;
        }
    }

    private @Nullable Bitmap mBitmap;
    private EventDispatcher mEventDispatcher;
    private long mGestureStartTime = TouchEvent.UNSET;
    private int mTargetTag;

    private final TouchEventCoalescingKeyHelper mTouchEventCoalescingKeyHelper =
            new TouchEventCoalescingKeyHelper();

    public SvgView(ReactContext reactContext) {
        super(reactContext);
        mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
    }

    @Override
    public void setId(int id) {
        super.setId(id);
        SvgViewManager.setSvgView(this);
    }

    public void setBitmap(Bitmap bitmap) {
        if (mBitmap != null) {
            mBitmap.recycle();
        }
        mBitmap = bitmap;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBitmap != null) {
            canvas.drawBitmap(mBitmap, 0, 0, null);
        }
    }

    private SvgViewShadowNode getShadowNode() {
        return SvgViewManager.getShadowNodeByTag(getId());
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mTargetTag = getShadowNode().hitTest(new Point((int) ev.getX(), (int) ev.getY()));

        if (mTargetTag != -1) {
            handleTouchEvent(ev);
            return true;
        }

        return super.dispatchTouchEvent(ev);
    }

    private int getAbsoluteLeft(View view) {
        int left = view.getLeft() - view.getScrollX();

        if (view.getParent() == view.getRootView() || view.getParent() instanceof ReactRootView) {
            return left;
        }

        View parent = (View) view.getParent();
        return left + getAbsoluteLeft(parent);
    }

    private int getAbsoluteTop(View view) {
        int top = view.getTop() - view.getScrollY();

        if (view.getParent() == view.getRootView() || view.getParent() instanceof ReactRootView) {
            return top;
        }

        View parent = (View) view.getParent();
        return top + getAbsoluteTop(parent);
    }

    private void dispatch(MotionEvent ev, TouchEventType type) {
        ev.offsetLocation(getAbsoluteLeft(this), getAbsoluteTop(this));
        mEventDispatcher.dispatchEvent(
            TouchEvent.obtain(
                mTargetTag,
                type,
                ev,
                mGestureStartTime,
                ev.getX(),
                ev.getY(),
                mTouchEventCoalescingKeyHelper));
    }

    public void handleTouchEvent(MotionEvent ev) {
        int action = ev.getAction() & MotionEvent.ACTION_MASK;
        if (action == MotionEvent.ACTION_DOWN) {
            mGestureStartTime = ev.getEventTime();
            dispatch(ev, TouchEventType.START);
        } else if (mTargetTag == -1) {
            // All the subsequent action types are expected to be called after ACTION_DOWN thus target
            // is supposed to be set for them.
            Log.e(
                "error",
                "Unexpected state: received touch event but didn't get starting ACTION_DOWN for this " +
                    "gesture before");
        } else if (action == MotionEvent.ACTION_UP) {
            // End of the gesture. We reset target tag to -1 and expect no further event associated with
            // this gesture.
            dispatch(ev, TouchEventType.END);
            mTargetTag = -1;
        } else if (action == MotionEvent.ACTION_MOVE) {
            // Update pointer position for current gesture
            dispatch(ev, TouchEventType.MOVE);
        } else if (action == MotionEvent.ACTION_POINTER_DOWN) {
            // New pointer goes down, this can only happen after ACTION_DOWN is sent for the first pointer
            dispatch(ev, TouchEventType.START);
        } else if (action == MotionEvent.ACTION_POINTER_UP) {
            // Exactly onw of the pointers goes up
            dispatch(ev, TouchEventType.END);
            mTargetTag = -1;
            mGestureStartTime = TouchEvent.UNSET;
        } else if (action == MotionEvent.ACTION_CANCEL) {
            dispatchCancelEvent(ev);
            mTargetTag = -1;
            mGestureStartTime = TouchEvent.UNSET;
        } else {
            Log.w(
                "IGNORE",
                "Warning : touch event was ignored. Action=" + action + " Target=" + mTargetTag);
        }
    }

    private void dispatchCancelEvent(MotionEvent ev) {
        // This means the gesture has already ended, via some other CANCEL or UP event. This is not
        // expected to happen very often as it would mean some child View has decided to intercept the
        // touch stream and start a native gesture only upon receiving the UP/CANCEL event.
        if (mTargetTag == -1) {
            Log.w(
                "error",
                "Can't cancel already finished gesture. Is a child View trying to start a gesture from " +
                    "an UP/CANCEL event?");
            return;
        }

        dispatch(ev, TouchEventType.CANCEL);
    }
}


text:
static NSString * const CDEZipFilePathExtension = @"cdezip";

@implementation CDEZipCloudFileSystem {
    NSFileManager *fileManager;
    NSString *tempDirPath;
}

@synthesize cloudFileSystem = cloudFileSystem;

- (instancetype)initWithCloudFileSystem:(id <CDECloudFileSystem>)wrappedFileSystem
{
    self = [super init];
    if (self) {
        cloudFileSystem = wrappedFileSystem;
        fileManager = [[NSFileManager alloc] init];
        tempDirPath = [NSTemporaryDirectory() stringByAppendingFormat:@"/CDEZipCloudFileSystem/%@", [[NSProcessInfo processInfo] globallyUniqueString]];
        [self clearTempDir];
    }
    return self;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:CDEException reason:@"Wrong initializer invoked" userInfo:nil];
}

- (void)dealloc
{
    [[NSFileManager defaultManager] removeItemAtPath:tempDirPath error:NULL];
}

- (void)clearTempDir
{
    [fileManager removeItemAtPath:tempDirPath error:NULL];
    [fileManager createDirectoryAtPath:tempDirPath withIntermediateDirectories:YES attributes:nil error:NULL];
}

- (void)connect:(CDECompletionBlock)completion
{
    [cloudFileSystem connect:completion];
}

- (BOOL)isConnected
{
    return cloudFileSystem.isConnected;
}

- (void)fetchUserIdentityWithCompletion:(CDEFetchUserIdentityCallback)completion;
{
    [cloudFileSystem fetchUserIdentityWithCompletion:completion];
}

- (void)fileExistsAtPath:(NSString *)path completion:(CDEFileExistenceCallback)completion
{
    NSString *zippedPath = [path stringByAppendingPathExtension:CDEZipFilePathExtension];
    [cloudFileSystem fileExistsAtPath:zippedPath completion:^(BOOL exists, BOOL isDirectory, NSError *error) {
        if (error) {
            if (completion) completion(NO, NO, error);
            return;
        }

        if (!exists) {
            [cloudFileSystem fileExistsAtPath:path completion:completion];
            return;
        }

        if (completion) completion(exists, isDirectory, nil);
    }];
}

- (void)directoryExistsAtPath:(NSString *)path completion:(CDEDirectoryExistenceCallback)completion
{
    if ([cloudFileSystem respondsToSelector:@selector(directoryExistsAtPath:completion:)]) {
        [cloudFileSystem directoryExistsAtPath:path completion:^(BOOL exists, NSError *error) {
            if (completion) completion(error ? NO : exists, error);
        }];
    }
    else {
        [cloudFileSystem fileExistsAtPath:path completion:^(BOOL exists, BOOL isDirectory, NSError *error) {
            exists = exists && isDirectory;
            if (completion) completion(error ? NO : exists, error);
        }];
    }
}

- (void)createDirectoryAtPath:(NSString *)path completion:(CDECompletionBlock)completion
{
    [cloudFileSystem createDirectoryAtPath:path completion:completion];
}

- (void)removeItemAtPath:(NSString *)fromPath completion:(CDECompletionBlock)completion
{
    NSString *zippedPath = [fromPath stringByAppendingPathExtension:CDEZipFilePathExtension];
    [cloudFileSystem removeItemAtPath:zippedPath completion:^(NSError *zipFileError) {
        [cloudFileSystem removeItemAtPath:fromPath completion:^(NSError *nonZipError) {
            NSError *error = (zipFileError && nonZipError) ? nonZipError : nil;
            if (completion) completion(error);
        }];
    }];
}

- (void)removeItemsAtPaths:(NSArray *)paths completion:(CDECompletionBlock)block
{
    NSMutableArray *allPaths = [[NSMutableArray alloc] initWithArray:paths];
    for (NSString *path in paths) {
        NSString *zippedPath = [path stringByAppendingPathExtension:CDEZipFilePathExtension];
        [allPaths addObject:zippedPath];
    }

    [cloudFileSystem removeItemsAtPaths:allPaths completion:^(NSError *error) {
        // There can be errors due to zipped paths not existing, or vice versa. Ignore.
        if (block) block(nil);
    }];
}

- (void)contentsOfDirectoryAtPath:(NSString *)path completion:(CDEDirectoryContentsCallback)completion
{
    [cloudFileSystem contentsOfDirectoryAtPath:path completion:^(NSArray *contents, NSError *error) {
        if (error) {
            if (completion) completion(nil, error);
            return;
        }

        for (id item in contents) {
            CDECloudFile *file = item;
            if ([item isKindOfClass:[CDECloudFile class]] && [file.name.pathExtension isEqualToString:CDEZipFilePathExtension]) {
                file.name = [file.name stringByDeletingPathExtension];
            }
        }
        if (completion) completion(contents, nil);
    }];
}

- (NSString *)tempFilePath
{
    NSString *tempFilePath = [tempDirPath stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
    return tempFilePath;
}

- (NSUInteger) fileDownloadMaximumBatchSize
{
    return [cloudFileSystem fileDownloadMaximumBatchSize];
}

- (void)downloadFromPath:(NSString *)fromPath toLocalFile:(NSString *)toPath completion:(CDECompletionBlock)completion
{
    NSString *tempFilePath = [self tempFilePath];
    NSString *zippedPath = [fromPath stringByAppendingPathExtension:CDEZipFilePathExtension];
    [cloudFileSystem downloadFromPath:zippedPath toLocalFile:tempFilePath completion:^(NSError *error) {
        if (error) {
            [cloudFileSystem downloadFromPath:fromPath toLocalFile:toPath completion:completion];
            return;
        }

        NSError *localError;
        NSString *destinationDir = [toPath stringByDeletingLastPathComponent];
        BOOL unzipSucceeded = [SSZipArchive unzipFileAtPath:tempFilePath toDestination:destinationDir overwrite:NO password:nil error:&localError];
        [fileManager removeItemAtPath:tempFilePath error:NULL];

        if (completion) completion(unzipSucceeded ? nil : localError);
    }];
}

- (void)downloadFromPaths:(NSArray *)fromPaths toLocalFiles:(NSArray *)toPaths completion:(CDECompletionBlock)completion
{
    NSMutableArray *tempPaths = [[NSMutableArray alloc] init];
    NSMutableArray *zippedPaths = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < fromPaths.count; i++) {
        NSString *fromPath = fromPaths[i];
        NSString *tempFilePath = [self tempFilePath];
        NSString *zippedPath = [fromPath stringByAppendingPathExtension:CDEZipFilePathExtension];
        [tempPaths addObject:tempFilePath];
        [zippedPaths addObject:zippedPath];
    }

    [cloudFileSystem downloadFromPaths:zippedPaths toLocalFiles:tempPaths completion:^(NSError *error) {
        if (error) {
            [cloudFileSystem downloadFromPaths:fromPaths toLocalFiles:toPaths completion:completion];
            return;
        }

        NSUInteger i = 0;
        NSError *localError = nil;
        BOOL unzipSucceeded = YES;
        for (NSString *tempFilePath in tempPaths) {
            NSString *toPath = toPaths[i++];
            NSString *destinationDir = [toPath stringByDeletingLastPathComponent];
            unzipSucceeded = [SSZipArchive unzipFileAtPath:tempFilePath toDestination:destinationDir overwrite:NO password:nil error:&localError];
            [fileManager removeItemAtPath:tempFilePath error:NULL];
            if (!unzipSucceeded) break;
        }

        if (completion) completion(unzipSucceeded ? nil : localError);
    }];
}

- (NSUInteger)fileUploadMaximumBatchSize
{
    return [cloudFileSystem fileUploadMaximumBatchSize];
}

- (void)uploadLocalFile:(NSString *)fromPath toPath:(NSString *)toPath completion:(CDECompletionBlock)completion
{
    NSString *tempFilePath = [self tempFilePath];
    [SSZipArchive createZipFileAtPath:tempFilePath withFilesAtPaths:@[fromPath]];
    NSString *zippedPath = [toPath stringByAppendingPathExtension:CDEZipFilePathExtension];
    [cloudFileSystem uploadLocalFile:tempFilePath toPath:zippedPath completion:^(NSError *error) {
        [fileManager removeItemAtPath:tempFilePath error:NULL];
        if (completion) completion(error);
    }];
}

- (void)uploadLocalFiles:(NSArray *)fromPaths toPaths:(NSArray *)toPaths completion:(CDECompletionBlock)completion
{
    NSMutableArray *tempPaths = [[NSMutableArray alloc] init];
    NSMutableArray *zippedPaths = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < fromPaths.count; i++) {
        NSString *fromPath = fromPaths[i];
        NSString *toPath = toPaths[i];
        NSString *tempFilePath = [self tempFilePath];
        [SSZipArchive createZipFileAtPath:tempFilePath withFilesAtPaths:@[fromPath]];
        NSString *zippedPath = [toPath stringByAppendingPathExtension:CDEZipFilePathExtension];
        [tempPaths addObject:tempFilePath];
        [zippedPaths addObject:zippedPath];
    }

    [cloudFileSystem uploadLocalFiles:tempPaths toPaths:zippedPaths completion:^(NSError *error) {
        for (NSString *tempPath in tempPaths) [fileManager removeItemAtPath:tempPath error:NULL];
        if (completion) completion(error);
    }];
}

#pragma mark Message Forwarding

- (BOOL)respondsToSelector:(SEL)aSelector
{
    BOOL result = NO;
    if (@selector(removeItemsAtPaths:completion:) == aSelector ||
        @selector(fileUploadMaximumBatchSize) == aSelector || @selector(uploadLocalFiles:toPaths:completion:) == aSelector ||
        @selector(fileDownloadMaximumBatchSize) == aSelector || @selector(downloadFromPaths:toLocalFiles:completion:) == aSelector ) {
        result = [cloudFileSystem respondsToSelector:aSelector];
    }
    else {
        result = [super respondsToSelector:aSelector];
    }
    return result;
}

@end


text:
create table llx_c_departements
(
  rowid            integer    AUTO_INCREMENT PRIMARY KEY,
  code_departement varchar(6) NOT NULL,
  fk_region        integer,
  cheflieu         varchar(7),
  tncc             integer,
  ncc              varchar(50),
  nom              varchar(50),
  active           tinyint DEFAULT 1  NOT NULL
)type=innodb;


text:
//var apikey=121dea6cb6ea419be7902939b74c9fe0%3A10%3A72139813;

$(document).ready(function(){

	var startnytapi="http://api.nytimes.com/svc/search/v2/articlesearch.json?fq=";
	var query="sports";
	$("button#search").click(function(){
    	$("#search-query").text(query);
    });
	var apikey="&api-key=121dea6cb6ea419be7902939b74c9fe0%3A10%3A72139813";
	var nytapi=startnytapi+query+apikey;
	console.log(nytapi);

	$.getJSON(nytapi, function (json) {

	    for(i=0;i<9;i++){
	    var headline = json.response.docs[i].headline.main;
	    console.log('Headline : ', headline);
	    var category = json.response.docs[i].section_name;
	    console.log('Category : ',category);
	    var weburl = json.response.docs[i].web_url;
	    console.log('weburl : ',weburl);

	   	var img;
	    if($.isEmptyObject(json.response.docs[i].multimedia))
	    {
	    	img="img/portfolio/1.jpg";
	    }
	    else{
	    	 var imgfetch=json.response.docs[i].multimedia[0].url;
	    	 console.log(imgfetch);
	    	 var starturl="http://www.nytimes.com/";
	    	 var img=starturl+imgfetch;
	    	 console.log(img);
	    }/*
	    $('div.project-category').text(category);
	    $('div.project-name').text(headline);
	    */

	    var newscontainer='
\
			                    \
			                    \

\

\

\
			                                    '+category+'\

\

\
			                                    '+headline+'\

\

\

\
			                    \

';
		$("section#portfolio").append(newscontainer);
		}
	});
});


text:
namespace clif_test_absl_int128 {

inline absl::int128 Zero() { return 0; }
inline absl::int128 One() { return 1; }
inline absl::int128 NegativeOne() { return -1; }
inline absl::int128 SetHighLsb() { return absl::MakeInt128(1, 0); }
inline absl::int128 SetNegativeHighLsb() { return absl::MakeInt128(-1, 0); }
inline absl::int128 Min() { return std::numeric_limits<absl::int128>::min(); }
inline absl::int128 Max() { return std::numeric_limits<absl::int128>::max(); }
inline absl::int128 AddInt128(absl::int128 a, absl::int128 b) { return a + b; }

}  // namespace clif_test_absl_int128

#endif  // CLIF_TESTING_ABSL_INT128_H_


text:
<?php

namespace Slim\Interfaces;

use RuntimeException;
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Router Interface
 *
 * @package Slim
 * @since   3.0.0
 */
interface RouterInterface
{
    /**
     * Add route
     *
     * @param string[] $methods Array of HTTP methods
     * @param string   $pattern The route pattern
     * @param callable $handler The route callable
     *
     * @return RouteInterface
     */
    public function map($methods, $pattern, $handler);

    /**
     * Dispatch router for HTTP request
     *
     * @param  ServerRequestInterface $request The current HTTP request object
     *
     * @return array
     *
     * @link   https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
     */
    public function dispatch(ServerRequestInterface $request);

    /**
     * Add a route group to the array
     *
     * @param string   $pattern The group pattern
     * @param callable $callable A group callable
     *
     * @return RouteGroupInterface
     */
    public function pushGroup($pattern, $callable);

    /**
     * Removes the last route group from the array
     *
     * @return bool True if successful, else False
     */
    public function popGroup();

    /**
     * Get named route object
     *
     * @param string $name        Route name
     *
     * @return \Slim\Interfaces\RouteInterface
     *
     * @throws RuntimeException   If named route does not exist
     */
    public function getNamedRoute($name);

    /**
     * @param $identifier
     *
     * @return \Slim\Interfaces\RouteInterface
     */
    public function lookupRoute($identifier);

    /**
     * Build the path for a named route excluding the base path
     *
     * @param string $name        Route name
     * @param array  $data        Named argument replacement data
     * @param array  $queryParams Optional query string parameters
     *
     * @return string
     *
     * @throws RuntimeException         If named route does not exist
     * @throws InvalidArgumentException If required data not provided
     */
    public function relativePathFor($name, array $data = [], array $queryParams = []);

    /**
     * Build the path for a named route including the base path
     *
     * @param string $name        Route name
     * @param array  $data        Named argument replacement data
     * @param array  $queryParams Optional query string parameters
     *
     * @return string
     *
     * @throws RuntimeException         If named route does not exist
     * @throws InvalidArgumentException If required data not provided
     */
    public function pathFor($name, array $data = [], array $queryParams = []);
}


text:
require 'spec_helper'

describe Layer::Block do

  let(:client) { instance_double("Layer::Client") }
  let(:response) do
    {
      'user_id' => '2',
      'url' => '/users/1/blocks/2'
    }
  end

  subject { described_class.from_response(response, client) }

  describe '.delete' do
    it 'should delete the block via the API' do
      expect(client).to receive(:delete).with('/users/1/blocks/2')
      subject.delete
    end
  end
end


text:
<?php

namespace Zenstruck\RedirectBundle\EventListener\Doctrine;

use Doctrine\Common\EventSubscriber;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Zenstruck\RedirectBundle\Model\Redirect;
use Zenstruck\RedirectBundle\Service\NotFoundManager;

/**
 * @author Kevin Bond <kevinbond@gmail.com>
 */
class RemoveNotFoundSubscriber implements EventSubscriber
{
    private NotFoundManager|null $notFoundManager = null;

    public function __construct(private ContainerInterface $container)
    {
    }

    public function getSubscribedEvents(): array
    {
        return [
            'postPersist',
            'postUpdate',
        ];
    }

    public function postUpdate(LifecycleEventArgs $args): void
    {
        $this->remoteNotFoundForRedirect($args);
    }

    public function postPersist(LifecycleEventArgs $args): void
    {
        $this->remoteNotFoundForRedirect($args);
    }

    private function remoteNotFoundForRedirect(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();

        if (!$entity instanceof Redirect) {
            return;
        }

        $this->getNotFoundManager()->removeForRedirect($entity);
    }

    private function getNotFoundManager(): NotFoundManager
    {
        if (null === $this->notFoundManager) {
            $this->notFoundManager = $this->container->get('zenstruck_redirect.not_found_manager');
        }

        return $this->notFoundManager;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hg4.jiangnankezhan.PhoneFindActivity"
    android:fitsSystemWindows="true"
    android:background="@drawable/fgp_bg">

    <ImageButton
        android:id="@+id/back"
        android:layout_width="14dp"
        android:layout_height="27dp"
        app:srcCompat="@drawable/uni_back_icon"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@null"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="24dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="24dp" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="304dp"
        android:layout_height="184dp"
        android:layout_marginRight="29dp"
        android:layout_marginTop="61dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/back"
        app:srcCompat="@drawable/fgp2_rec"
        android:layout_marginEnd="29dp" />

    <EditText
        android:id="@+id/phonenumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="46dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/fgp2_emai_line"
        android:ems="10"
        android:hint="手机号码"
        android:inputType="textPhonetic"
        android:paddingBottom="9dp"
        android:paddingLeft="45dp"
        android:textColor="#ffffff"
        android:textColorHint="#80ffffff"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView3" />

    <Button
        android:id="@+id/sendidentify"
        android:layout_width="304dp"
        android:layout_height="50dp"
        android:layout_marginRight="28dp"
        android:layout_marginTop="17dp"
        android:background="@drawable/fgp2_conf_code"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/phonenumber" />

</android.support.constraint.ConstraintLayout>


text:
#include "tensorflow/lite/delegates/gpu/common/task/texture2d_desc.h"

#include "absl/strings/str_cat.h"

namespace tflite {
namespace gpu {

void Texture2DDescriptor::Release() { data.clear(); }

GPUResources Texture2DDescriptor::GetGPUResources() const {
  GPUResources resources;
  GPUImage2DDescriptor desc;
  desc.data_type = element_type;
  desc.normalized = normalized;
  desc.normalized_type = normalized_type;
  desc.access_type = access_type_;
  resources.images2d.push_back({"tex2d", desc});
  return resources;
}

absl::Status Texture2DDescriptor::PerformSelector(
    const GpuInfo& gpu_info, const std::string& selector,
    const std::vector<std::string>& args,
    const std::vector<std::string>& template_args, std::string* result) const {
  if (selector == "Read") {
    return PerformReadSelector(gpu_info, args, result);
  } else {
    return absl::NotFoundError(absl::StrCat(
        "Texture2DDescriptor don't have selector with name - ", selector));
  }
}

absl::Status Texture2DDescriptor::PerformReadSelector(
    const GpuInfo& gpu_info, const std::vector<std::string>& args,
    std::string* result) const {
  if (args.size() != 2) {
    return absl::NotFoundError(
        absl::StrCat("Texture2DDescriptor Read require two arguments, but ",
                     args.size(), " was passed"));
  }
  if (gpu_info.IsApiMetal()) {
    *result =
        absl::StrCat("tex2d.read(ushort2(", args[0], ", " + args[1] + "))");
    return absl::OkStatus();
  } else if (gpu_info.IsApiOpenCl()) {
    std::string read;
    switch (element_type) {
      case DataType::FLOAT32:
        read = "read_imagef";
        break;
      case DataType::FLOAT16:
        read = "read_imageh";
        break;
      case DataType::INT8:
      case DataType::INT16:
      case DataType::INT32:
        if (normalized) {
          read = normalized_type == DataType::FLOAT16 ? "read_imageh"
                                                      : "read_imagef";
        } else {
          read = "read_imagei";
        }
        break;
      case DataType::UINT8:
      case DataType::UINT16:
      case DataType::UINT32:
        if (normalized) {
          read = normalized_type == DataType::FLOAT16 ? "read_imageh"
                                                      : "read_imagef";
        } else {
          read = "read_imageui";
        }
        break;
      default:
        read = "unknown_type";
        break;
    }
    *result = absl::StrCat(read, "(tex2d, smp_none, (int2)(", args[0],
                           ", " + args[1] + "))");
    return absl::OkStatus();
  } else {
    return absl::UnimplementedError(
        "No implementation of Texture2D.Read for this API.");
  }
}

}  // namespace gpu
}  // namespace tflite


text:
namespace content {
class WebUI;
}  // namespace content

// Loads DataSource at startup for Crosh (the Chromium OS shell).
class CroshUIConfig : public ui::WebUIConfig {
 public:
  CroshUIConfig();
  ~CroshUIConfig() override;
  bool IsWebUIEnabled(content::BrowserContext* browser_context) override;

  std::unique_ptr<content::WebUIController> CreateWebUIController(
      content::WebUI* web_ui) override;
};

class CroshUI : public ui::UntrustedWebUIController {
 public:
  explicit CroshUI(content::WebUI* web_ui);
  CroshUI(const CroshUI&) = delete;
  CroshUI& operator=(const CroshUI&) = delete;
  ~CroshUI() override;
};

#endif  // CHROME_BROWSER_ASH_WEB_APPLICATIONS_CROSH_UI_H_


text:
package com.github.saem.serviceme;

import com.github.saem.serviceme.scaffolding.Application;

public final class GreeterApplication extends Application<GreeterConfig> {
    GreeterApplication(final GreeterConfig configuration) {
        super(configuration, new GreeterComponents(configuration));
    }

    public static void main(final String[] args) {
        new GreeterApplication(new GreeterConfig()).run();
    }
}


text:
_fs = require('fs');
_http = require('http');

//var _forex = { "USD" : 1.0 }; // base is u.s. dollar
_forex = ''; // response buffer (which should be json)

//var _currnames = { "USD" : "United States Dollar" }; // base is u.s. dollar
_currnames = ''; // response buffer (which should be json)

_jdate = (new Date()).toJSON();
_log2stdout = false;

_currlist = 'http://openexchangerates.org/api/currencies.json'; // no apid needed?
_quote = 'http://openexchangerates.org/api/latest.json?app_id=a3aef6b27057437da448f3322a3b660e';
_history = 'http://openexchangerates.org/api/historical/2011-10-18.json?app_id=a3aef6b27057437da448f3322a3b660e';

var _exit = false;

if( _log2stdout ) {
  console.log('nodejs: ' + process.version);
  console.log('according to this reference from: https://openexchangerates.org/quick-start ... using url and appId:');
  console.log(_quote);
}

var applyRates = function(rates) {
  console.log('--------------------------------------------------------------------------------------');
  console.log(_jdate + ': ' + _currnames.CAD + ' == ' + rates.CAD + ' USA dollars.');
  console.log(_jdate + ": 1 " + _currnames.CAD + " dividend yields " + 1.0/rates.CAD + " US dollars.");
  console.log('--------------------------------------------------------------------------------------');
  console.log(_jdate + ': ' + _currnames.GBP + ' == ' + rates.GBP + ' USA dollars.');
  console.log(_jdate + ": 1 " + _currnames.GBP + " dividend yields " + 1.0/rates.GBP + " US dollars.");
  console.log('--------------------------------------------------------------------------------------');
  if( _log2stdout ) {
    console.log(rates);
  }
  _exit = true;
};

var handleRates = function(filename) {
  var dt = _jdate = (new Date()).toJSON();
  var savefile = filename + dt + '.json';
  _fs.writeFile(savefile, _forex, function(err) {
    if( err ) { return console.log(err); }
    //_forex = require(savefile); // this is (potentially) blocking i/o, but provides cache-file validation
    _forex = JSON.parse(_forex); // this avoids the above cache-file-i/o
    // this blocks: _forex = require(savefile); // is this needed? _forex = JSON.parse(_forex);
    if( _log2stdout ) {
      console.log('reply: \n' + _forex.disclaimer + '\n' + _forex.base); // console.log(_forex.rates);
    }
    applyRates(_forex.rates);
  });
};

var getLatestRates = function() {
 _http.get(_quote, function(res) {
  //console.log("response: " + res.statusCode);
  res.setEncoding('utf8');
  res.on('end', function(content) { handleRates('./quote_forex'); });
  res.on('data', function(content) { _forex += content; }); // buffer full quote
  }).on('error', function(err) { console.log("http.get latest exchange rates error: " + err.message); });
};

var handleCurrNames = function(filename) {
  var dt = _jdate = (new Date()).toJSON();
  var savefile = filename + dt + '.json';
  _fs.writeFile(savefile, _currnames, function(err) {
    if( err ) { return console.log(err); }
    //_currnames = require(savefile); // this is (potentially) blocking i/o, but provides cache-file validation
    _currnames = JSON.parse(_currnames); // this avoids the above cache-file-i/o
    // now get the latest/current rates:
    getLatestRates();
    // this blocks: _forex = require(savefile); // is this needed? _forex = JSON.parse(_forex);
    if( _log2stdout ) {
      console.log(_currnames);
    }
  });
};

var startForex = function() {
  // first fect list of currency names. and upon successful completion of
  // first transaction, handler should proceed with rates query...
  _http.get(_currlist, function(res) {
  //console.log("response: " + res.statusCode);
  res.setEncoding('utf8');
  res.on('end', function(content) { handleCurrNames('./currencies.json'); });
  res.on('data', function(content) { _currnames += content; }); // buffer full list
  }).on('error', function(err) { console.log("http.get currencies list error: " + err.message); });
};

var startHeartbeat = function() {
  setInterval((function() {
    if( _exit ) {
      console.log('all transactions have completed, exit ...');
      process.exit(0);
    }
    console.log('... awaiting completion of all transactions ...');
  }), 500); // 500 millisec == 0.5 sec interval
};

var main = function() {
  console.log('nodejs: ' + process.version);
  startHeartbeat();
  startForex();
};

main();


text:
package org.febit.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.QueryMapEncoder;
import feign.codec.Encoder;
import lombok.experimental.UtilityClass;
import org.febit.feign.codec.JacksonEncoder;
import org.febit.feign.codec.JacksonQueryMapEncoder;
import org.febit.lang.util.JacksonUtils;
import org.febit.lang.util.JacksonWrapper;

@UtilityClass
public class Encoders {

    public static Encoder chain(
            ObjectMapper objectMapper,
            Chain... chains
    ) {
        var encoder = jackson(objectMapper);
        for (var action : chains) {
            encoder = action.chain(encoder);
        }
        return encoder;
    }

    public static Encoder jackson(ObjectMapper objectMapper) {
        return jackson(JacksonUtils.wrap(objectMapper));
    }

    public static Encoder jackson(JacksonWrapper jackson) {
        return new JacksonEncoder(jackson);
    }

    public static QueryMapEncoder queryMapEncoder(JacksonWrapper jackson) {
        return new JacksonQueryMapEncoder(jackson);
    }

    @FunctionalInterface
    public interface Chain {
        Encoder chain(Encoder inner);
    }

}


text:
require 'yaml'

reference_tree_yaml = File.read('../../docs/prototype-rails-references.yaml')
@reference_tree = YAML.load(reference_tree_yaml)

solutions_file_name = '../../docs/prototype-rails-solutions.yaml'
solutions_yaml = File.read(solutions_file_name)
@solutions = YAML.load(solutions_yaml)

exploded_file_name = '../../docs/prototype-rails-exploded-references.yaml'
exploded = []

@current_path = []

def explode(block_name, top_level=false)
  block = @reference_tree[block_name]
  if(block["callers"])
    if(@current_path.include?(block_name))
      "#{block_name} (circular)"
    elsif(!top_level and @solutions[block_name] and @solutions[block_name]["solution"])
      "#{block_name} (solved)"
    else
      @current_path.push(block_name)
      caller_names = block["callers"].map{|caller| caller["name"]}
      return_value = {
        # recurse
        # FIXME need to detect infinite loops
        block_name => caller_names.map{|caller_name| explode(caller_name)}
      }
      @current_path.pop()
      return_value
    end
  else
    if(@solutions[block_name] and @solutions[block_name]["solution"])
      "#{block_name} (solved)"
    else
      block_name
    end
  end
end

# Do explosion
@reference_tree.each do |name, block|
  next if(name.start_with?("BASE/"))
  # add the basic callers
  exploded << explode(name, true)
  if(@current_path.length > 0)
    abort("current_path wasn't completely popped on: #{name}")
  end
end

# sorted_exploded = exploded.sort
puts "Writing: #{exploded_file_name}"

File.open(exploded_file_name, 'w') do |f|
  f.write "# This was generated using: cd rails/script; ruby prototype-rails-explode-tree.rb\n"
  f.write exploded.to_yaml
end


text:
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext

from django.contrib.sites.models import Site

from cms.models.pagemodel import Page
from cms.models.permissionmodels import GlobalPagePermission
from cms.utils import permissions, moderator, get_language_from_request

NOT_FOUND_RESPONSE = "NotFound"

def get_admin_menu_item_context(request, page, filtered=False):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)

    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    #slug = page.get_slug(language=lang, fallback=True) # why was this here ??
    metadata = ""
    if settings.CMS_PERMISSION:
        # jstree metadata generator
        md = []

        #if not has_add_page_permission:
        if not has_move_page_permission:
            md.append(('valid_children', False))
            md.append(('draggable', False))
        if md:
            # just turn it into simple javasript object
            metadata = "{" + ", ".join(map(lambda e: "%s: %s" %(e[0],
                isinstance(e[1], bool) and str(e[1]) or e[1].lower() ), md)) + "}"

    moderator_state = moderator.page_moderator_state(request, page)
    has_add_on_same_level_permission = False
    opts = Page._meta
    if settings.CMS_PERMISSION:
        if (request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) and
                GlobalPagePermission.objects.with_user(request.user).filter(can_add=True, sites__in=[page.site_id])):
                has_add_on_same_level_permission = True

    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(page.parent_id, request.user, "add", page.site)
    #has_add_on_same_level_permission = has_add_page_on_same_level_permission(request, page)
    context = {
        'page': page,
        'site': site,
        'lang': lang,
        'filtered': filtered,
        'metadata': metadata,

        'has_change_permission': page.has_change_permission(request),
        'has_publish_permission': page.has_publish_permission(request),
        'has_delete_permission': page.has_delete_permission(request),
        'has_move_page_permission': has_move_page_permission,
        'has_add_page_permission': has_add_page_permission,
        'has_moderate_permission': page.has_moderate_permission(request),
        'page_moderator_state': moderator_state,
        'moderator_should_approve': moderator_state['state'] >= moderator.I_APPROVE,
        'has_add_on_same_level_permission': has_add_on_same_level_permission,
        'CMS_PERMISSION': settings.CMS_PERMISSION,
        'CMS_MODERATOR': settings.CMS_MODERATOR,
    }
    return context

def render_admin_menu_item(request, page):
    """
    Renders requested page item for the tree. This is used in case when item
    must be reloaded over ajax.
    """
    if not page.pk:
        return HttpResponse(NOT_FOUND_RESPONSE) # Not found - tree will remove item

    # languages
    languages = []
    if page.site_id in settings.CMS_SITE_LANGUAGES:
        languages = settings.CMS_SITE_LANGUAGES[page.site_id]
    else:
        languages = [x[0] for x in settings.CMS_LANGUAGES]

    context = RequestContext(request, {
        'has_add_permission': permissions.has_page_add_permission(request),
        'site_languages': languages,
    })

    filtered = 'filtered' in request.REQUEST
    context.update(get_admin_menu_item_context(request, page, filtered))
    return render_to_response('admin/cms/page/menu_item.html', context)


text:
layout: post
title: Digital Playground - Tennis Coach Gets Balls Licked by 2 Latinas
titleinfo: pornvd
desc: Watch Digital Playground - Tennis Coach Gets Balls Licked by 2 Latinas. Pornhub is the ultimate xxx porn and sex site.
---

Digital Playground - Tennis Coach Gets Balls Licked by 2 Latinas

Watch Digital Playground - Tennis Coach Gets Balls Licked by 2 Latinas. Pornhub is the ultimate xxx porn and sex site.


text:
module LiteAccessControl

  class AccessError < Exception; end
  class AccessDenied < AccessError; end

  module ClassMethods
    def set_rights(rights)
      write_inheritable_attribute :rights, rights
    end
  end

  def self.included(base)
    base.extend(ClassMethods)
  end

  def access_control(user)
    required_rights = lookup_by_controller_and_action(controller_name, action_name)
    return true if required_rights.blank?
    raise AccessDenied if user.permissions.blank? || (user.permissions & required_rights).empty?
    true
  end

  private
  def rights
    @rights ||= self.class.read_inheritable_attribute(:rights) || {}
  end

  def reversed_rights
    reversed_rights = {}
    rights.each do |r|
      permission_name = r[0]
      controller_name = r[1][:controller]
      action_names = r[1][:actions]

      tmp_rules_set = reversed_rights.fetch(controller_name, {})

      if action_names == :all
        tmp_rules_set[:all_controller_actions]= (tmp_rules_set[:all_controller_actions]||[] << permission_name.to_sym)
      else
        action_names.each do |a|
          tmp_rules_set[a] = (tmp_rules_set[a] || [] ) << permission_name
        end
      end

      reversed_rights[controller_name] = tmp_rules_set
    end

    reversed_rights
  end

  # Lookup rights name by controller name
  def lookup_by_controller_and_action(controller, action)
    actions = reversed_rights[controller.to_s]
    if actions
      required_actions = []
      required_actions += actions[action] if actions[action]
      required_actions += actions[:all_controller_actions] if actions[:all_controller_actions]
      required_actions
    end
  end

end# LiteAccessControl


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Score Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache Lucene.Net 2.4.0 Class Library API

Scorer.Score Method

Returns the score of the current document matching the query. Initially invalid, until {@link #Next()} or {@link #SkipTo(int)} is called the first time.

Overload List

Returns the score of the current document matching the query. Initially invalid, until {@link #Next()} or {@link #SkipTo(int)} is called the first time.

        public abstract float Score();

        public virtual void Score(HitCollector);

Expert: Collects matching documents in a range. Hook for optimization. Note that {@link #Next()} must be called once before this method is called for the first time.

        protected internal virtual bool Score(HitCollector,int);

See Also

        Scorer Class | Lucene.Net.Search Namespace

Generated from assembly Lucene.Net [2.4.0.2]


text:
/*global ol:false */
/*
    BW.registerHoverEvents registers hover/click events on a given vector layer on a given map.
    The events are triggered as Backbone events, so it's assumed that prevoius code has done
    _.extend(feature, Backbone.events);

    This code does not change style or anything else, just triggers the "on" and "off" events.

    See ol3demo.html for example use.
*/

var BW = this.BW || {};
BW.SelectEvents = BW.SelectEvents || {};
(function (ns) {
    'use strict';

    function registerSelectEvents(map, layer, style, condition, on, off) {
        var interaction = new ol.interaction.Select({
            condition: condition,
            layers: [layer],
            style: style
        });
        map.addInteraction(interaction);
        var features = interaction.getFeatures();
        var selectedHere = null;

        features.on('change:length', function () {
            if (features.getLength() > 0) {
                var sel = features.getArray()[0];
                sel.trigger(on, sel);
                sel.set('selected', true);
            } else {
                layer.getSource().forEachFeature(function (e) {
                    e.trigger(off, e);
                });
            }
        });
        return interaction;
    }

    ns.registerHoverEvents = function (map, layer, hightlightStyle) {
        var on = 'over';
        var off = 'out';
        var condition = ol.events.condition.pointerMove;
        return registerSelectEvents(map, layer, hightlightStyle, condition, on, off);
    };

    ns.registerClickEvents = function (map, layer, selectStyle) {
        var on = 'select';
        var off = 'deselect';
        var condition = ol.events.condition.click;
        return registerSelectEvents(map, layer, selectStyle, condition, on, off);
    };

}(BW.SelectEvents));


text:
package org.houxg.pixiurss.utils.toolbox;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

/**
 * 打开新Activity
 *

 * author: houxg
 *

 * create on 2015/7/10
 **/
public class OpenTool {

    public static void startActivity(Context ctx, Class<?> cls) {
        startActivity(ctx, cls, null, null);
    }

    public static void startActivity(Context ctx, Class<?> cls, String action) {
        startActivity(ctx, cls, action, null);
    }

    public static void startActivity(Context ctx, Class<?> cls, Bundle data) {
        startActivity(ctx, cls, null, data);
    }

    public static void startActivity(Context ctx, Class<?> cls, String action, Bundle data) {
        Intent intent = new Intent(ctx, cls);
        if (action != null) {
            intent.setAction(action);
        }
        if (data != null) {
            intent.putExtras(data);
        }
        ctx.startActivity(intent);
    }

    public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode) {
        startActivityForResult(activity, cls, requestCode, null, null);
    }

    public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode, Bundle data) {
        startActivityForResult(activity, cls, requestCode, null, data);
    }

    public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode, String action, Bundle data) {
        Intent intent = new Intent(activity, cls);
        if (action != null) {
            intent.setAction(action);
        }
        if (data != null) {
            intent.putExtras(data);
        }
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startActivityForResult(Fragment fragment, Class<?> cls, int requestCode) {
        startActivityForResult(fragment, cls, requestCode, null, null);
    }

    public static void startActivityForResult(Fragment fragment, Class<?> cls, int requestCode, Bundle data) {
        startActivityForResult(fragment, cls, requestCode, null, data);
    }

    public static void startActivityForResult(Fragment fragment, Class<?> cls, int requestCode, String action, Bundle data) {
        Intent intent = new Intent(fragment.getActivity(), cls);
        if (action != null) {
            intent.setAction(action);
        }
        if (data != null) {
            intent.putExtras(data);
        }
        fragment.startActivityForResult(intent, requestCode);
    }
}


text:
package nl.korthout.baubillious.brain.graph;

public class Edge {

    private final Node one;
    private final Node two;
    private int weight;

    public Edge(Node one, Node two) {
        this.one = one;
        this.two = two;
        this.weight = 1;
    }

    public Node getNeighbour(Node current){
        if(!(current.equals(one) || current.equals(two))){
            return null;
        }
        return (current.equals(one)) ? two : one;
    }

    public void increaseWeight() {
        weight++;
    }

    public void decreaseWeight() {
        weight = Math.max(weight - 1, 1);
    }

}


text:
from .helper import encode_response

__all__ = ['encode_response']


text:
using System;
using RulesEngine.AspNetCore;

namespace RulesEngine.Specs
{
    public class ConfigurationFixture : IDisposable
    {
        public void Dispose()
        {
            Engine.Reset();
        }
    }
}