text:
"""This module contains base classes and functions for the nodes and some
inference utils.
"""

import builtins
import collections

from astroid import context as contextmod
from astroid import exceptions, util

objectmodel = util.lazy_import("interpreter.objectmodel")
helpers = util.lazy_import("helpers")
BUILTINS = builtins.__name__
manager = util.lazy_import("manager")
MANAGER = manager.AstroidManager()

# TODO: check if needs special treatment
BUILTINS = "builtins"
BOOL_SPECIAL_METHOD = "__bool__"

PROPERTIES = {BUILTINS + ".property", "abc.abstractproperty"}
# List of possible property names. We use this list in order
# to see if a method is a property or not. This should be
# pretty reliable and fast, the alternative being to check each
# decorator to see if its a real property-like descriptor, which
# can be too complicated.
# Also, these aren't qualified, because each project can
# define them, we shouldn't expect to know every possible
# property-like decorator!
POSSIBLE_PROPERTIES = {
    "cached_property",
    "cachedproperty",
    "lazyproperty",
    "lazy_property",
    "reify",
    "lazyattribute",
    "lazy_attribute",
    "LazyProperty",
    "lazy",
    "cache_readonly",
}

def _is_property(meth, context=None):
    decoratornames = meth.decoratornames(context=context)
    if PROPERTIES.intersection(decoratornames):
        return True
    stripped = {
        name.split(".")[-1] for name in decoratornames if name is not util.Uninferable
    }
    if any(name in stripped for name in POSSIBLE_PROPERTIES):
        return True

    # Lookup for subclasses of *property*
    if not meth.decorators:
        return False
    for decorator in meth.decorators.nodes or ():
        inferred = helpers.safe_infer(decorator, context=context)
        if inferred is None or inferred is util.Uninferable:
            continue
        if inferred.__class__.__name__ == "ClassDef":
            for base_class in inferred.bases:
                if base_class.__class__.__name__ != "Name":
                    continue
                module, _ = base_class.lookup(base_class.name)
                if module.name == BUILTINS and base_class.name == "property":
                    return True

    return False

class Proxy:
    """a simple proxy object

    Note:

    Subclasses of this object will need a custom __getattr__
    if new instance attributes are created. See the Const class
    """

    _proxied = None  # proxied object may be set by class or by instance

    def __init__(self, proxied=None):
        if proxied is not None:
            self._proxied = proxied

    def __getattr__(self, name):
        if name == "_proxied":
            return getattr(self.__class__, "_proxied")
        if name in self.__dict__:
            return self.__dict__[name]
        return getattr(self._proxied, name)

    def infer(self, context=None):
        yield self

def _infer_stmts(stmts, context, frame=None):
    """Return an iterator on statements inferred by each statement in *stmts*."""
    inferred = False
    if context is not None:
        name = context.lookupname
        context = context.clone()
    else:
        name = None
        context = contextmod.InferenceContext()

    for stmt in stmts:
        if stmt is util.Uninferable:
            yield stmt
            inferred = True
            continue
        context.lookupname = stmt._infer_name(frame, name)
        try:
            for inferred in stmt.infer(context=context):
                yield inferred
                inferred = True
        except exceptions.NameInferenceError:
            continue
        except exceptions.InferenceError:
            yield util.Uninferable
            inferred = True
    if not inferred:
        raise exceptions.InferenceError(
            "Inference failed for all members of {stmts!r}.",
            stmts=stmts,
            frame=frame,
            context=context,
        )

def _infer_method_result_truth(instance, method_name, context):
    # Get the method from the instance and try to infer
    # its return's truth value.
    meth = next(instance.igetattr(method_name, context=context), None)
    if meth and hasattr(meth, "infer_call_result"):
        if not meth.callable():
            return util.Uninferable
        try:
            for value in meth.infer_call_result(instance, context=context):
                if value is util.Uninferable:
                    return value

                inferred = next(value.infer(context=context))
                return inferred.bool_value()
        except exceptions.InferenceError:
            pass
    return util.Uninferable

class BaseInstance(Proxy):
    """An instance base class, which provides lookup methods for potential instances."""

    special_attributes = None

    def display_type(self):
        return "Instance of"

    def getattr(self, name, context=None, lookupclass=True):
        try:
            values = self._proxied.instance_attr(name, context)
        except exceptions.AttributeInferenceError as exc:
            if self.special_attributes and name in self.special_attributes:
                return [self.special_attributes.lookup(name)]

            if lookupclass:
                # Class attributes not available through the instance
                # unless they are explicitly defined.
                return self._proxied.getattr(name, context, class_context=False)

            raise exceptions.AttributeInferenceError(
                target=self, attribute=name, context=context
            ) from exc
        # since we've no context information, return matching class members as
        # well
        if lookupclass:
            try:
                return values + self._proxied.getattr(
                    name, context, class_context=False
                )
            except exceptions.AttributeInferenceError:
                pass
        return values

    def igetattr(self, name, context=None):
        """inferred getattr"""
        if not context:
            context = contextmod.InferenceContext()
        try:
            # avoid recursively inferring the same attr on the same class
            if context.push((self._proxied, name)):
                raise exceptions.InferenceError(
                    message="Cannot infer the same attribute again",
                    node=self,
                    context=context,
                )

            # XXX frame should be self._proxied, or not ?
            get_attr = self.getattr(name, context, lookupclass=False)
            yield from _infer_stmts(
                self._wrap_attr(get_attr, context), context, frame=self
            )
        except exceptions.AttributeInferenceError as error:
            try:
                # fallback to class.igetattr since it has some logic to handle
                # descriptors
                # But only if the _proxied is the Class.
                if self._proxied.__class__.__name__ != "ClassDef":
                    raise
                attrs = self._proxied.igetattr(name, context, class_context=False)
                yield from self._wrap_attr(attrs, context)
            except exceptions.AttributeInferenceError as error:
                raise exceptions.InferenceError(**vars(error)) from error

    def _wrap_attr(self, attrs, context=None):
        """wrap bound methods of attrs in a InstanceMethod proxies"""
        for attr in attrs:
            if isinstance(attr, UnboundMethod):
                if _is_property(attr):
                    yield from attr.infer_call_result(self, context)
                else:
                    yield BoundMethod(attr, self)
            elif hasattr(attr, "name") and attr.name == "<lambda>":
                if attr.args.arguments and attr.args.arguments[0].name == "self":
                    yield BoundMethod(attr, self)
                    continue
                yield attr
            else:
                yield attr

    def infer_call_result(self, caller, context=None):
        """infer what a class instance is returning when called"""
        context = contextmod.bind_context_to_node(context, self)
        inferred = False
        for node in self._proxied.igetattr("__call__", context):
            if node is util.Uninferable or not node.callable():
                continue
            for res in node.infer_call_result(caller, context):
                inferred = True
                yield res
        if not inferred:
            raise exceptions.InferenceError(node=self, caller=caller, context=context)

class Instance(BaseInstance):
    """A special node representing a class instance."""

    # pylint: disable=unnecessary-lambda
    special_attributes = util.lazy_descriptor(lambda: objectmodel.InstanceModel())

    def __repr__(self):
        return "<Instance of {}.{} at 0x{}>".format(
            self._proxied.root().name, self._proxied.name, id(self)
        )

    def __str__(self):
        return f"Instance of {self._proxied.root().name}.{self._proxied.name}"

    def callable(self):
        try:
            self._proxied.getattr("__call__", class_context=False)
            return True
        except exceptions.AttributeInferenceError:
            return False

    def pytype(self):
        return self._proxied.qname()

    def display_type(self):
        return "Instance of"

    def bool_value(self, context=None):
        """Infer the truth value for an Instance

        The truth value of an instance is determined by these conditions:

           * if it implements __bool__ on Python 3 or __nonzero__
             on Python 2, then its bool value will be determined by
             calling this special method and checking its result.
           * when this method is not defined, __len__() is called, if it
             is defined, and the object is considered true if its result is
             nonzero. If a class defines neither __len__() nor __bool__(),
             all its instances are considered true.
        """
        context = context or contextmod.InferenceContext()
        context.callcontext = contextmod.CallContext(args=[])
        context.boundnode = self

        try:
            result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context)
        except (exceptions.InferenceError, exceptions.AttributeInferenceError):
            # Fallback to __len__.
            try:
                result = _infer_method_result_truth(self, "__len__", context)
            except (exceptions.AttributeInferenceError, exceptions.InferenceError):
                return True
        return result

    # This is set in inference.py.
    def getitem(self, index, context=None):
        pass

class UnboundMethod(Proxy):
    """a special node representing a method not bound to an instance"""

    # pylint: disable=unnecessary-lambda
    special_attributes = util.lazy_descriptor(lambda: objectmodel.UnboundMethodModel())

    def __repr__(self):
        frame = self._proxied.parent.frame()
        return "<{} {} of {} at 0x{}".format(
            self.__class__.__name__, self._proxied.name, frame.qname(), id(self)
        )

    def implicit_parameters(self):
        return 0

    def is_bound(self):
        return False

    def getattr(self, name, context=None):
        if name in self.special_attributes:
            return [self.special_attributes.lookup(name)]
        return self._proxied.getattr(name, context)

    def igetattr(self, name, context=None):
        if name in self.special_attributes:
            return iter((self.special_attributes.lookup(name),))
        return self._proxied.igetattr(name, context)

    def infer_call_result(self, caller, context):
        """
        The boundnode of the regular context with a function called
        on ``object.__new__`` will be of type ``object``,
        which is incorrect for the argument in general.
        If no context is given the ``object.__new__`` call argument will
        correctly inferred except when inside a call that requires
        the additional context (such as a classmethod) of the boundnode
        to determine which class the method was called from
        """

        # If we're unbound method __new__ of builtin object, the result is an
        # instance of the class given as first argument.
        if (
            self._proxied.name == "__new__"
            and self._proxied.parent.frame().qname() == "%s.object" % BUILTINS
        ):
            if caller.args:
                node_context = context.extra_context.get(caller.args[0])
                infer = caller.args[0].infer(context=node_context)
            else:
                infer = []
            return (Instance(x) if x is not util.Uninferable else x for x in infer)
        return self._proxied.infer_call_result(caller, context)

    def bool_value(self, context=None):
        return True

class BoundMethod(UnboundMethod):
    """a special node representing a method bound to an instance"""

    # pylint: disable=unnecessary-lambda
    special_attributes = util.lazy_descriptor(lambda: objectmodel.BoundMethodModel())

    def __init__(self, proxy, bound):
        UnboundMethod.__init__(self, proxy)
        self.bound = bound

    def implicit_parameters(self):
        if self.name == "__new__":
            # __new__ acts as a classmethod but the class argument is not implicit.
            return 0
        return 1

    def is_bound(self):
        return True

    def _infer_type_new_call(self, caller, context):
        """Try to infer what type.__new__(mcs, name, bases, attrs) returns.

        In order for such call to be valid, the metaclass needs to be
        a subtype of ``type``, the name needs to be a string, the bases
        needs to be a tuple of classes
        """
        # pylint: disable=import-outside-toplevel; circular import
        from astroid import node_classes

        # Verify the metaclass
        mcs = next(caller.args[0].infer(context=context))
        if mcs.__class__.__name__ != "ClassDef":
            # Not a valid first argument.
            return None
        if not mcs.is_subtype_of("%s.type" % BUILTINS):
            # Not a valid metaclass.
            return None

        # Verify the name
        name = next(caller.args[1].infer(context=context))
        if name.__class__.__name__ != "Const":
            # Not a valid name, needs to be a const.
            return None
        if not isinstance(name.value, str):
            # Needs to be a string.
            return None

        # Verify the bases
        bases = next(caller.args[2].infer(context=context))
        if bases.__class__.__name__ != "Tuple":
            # Needs to be a tuple.
            return None
        inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts]
        if any(base.__class__.__name__ != "ClassDef" for base in inferred_bases):
            # All the bases needs to be Classes
            return None

        # Verify the attributes.
        attrs = next(caller.args[3].infer(context=context))
        if attrs.__class__.__name__ != "Dict":
            # Needs to be a dictionary.
            return None
        cls_locals = collections.defaultdict(list)
        for key, value in attrs.items:
            key = next(key.infer(context=context))
            value = next(value.infer(context=context))
            # Ignore non string keys
            if key.__class__.__name__ == "Const" and isinstance(key.value, str):
                cls_locals[key.value].append(value)

        # Build the class from now.
        cls = mcs.__class__(
            name=name.value,
            lineno=caller.lineno,
            col_offset=caller.col_offset,
            parent=caller,
        )
        empty = node_classes.Pass()
        cls.postinit(
            bases=bases.elts,
            body=[empty],
            decorators=[],
            newstyle=True,
            metaclass=mcs,
            keywords=[],
        )
        cls.locals = cls_locals
        return cls

    def infer_call_result(self, caller, context=None):
        context = contextmod.bind_context_to_node(context, self.bound)
        if (
            self.bound.__class__.__name__ == "ClassDef"
            and self.bound.name == "type"
            and self.name == "__new__"
            and len(caller.args) == 4
        ):
            # Check if we have a ``type.__new__(mcs, name, bases, attrs)`` call.
            new_cls = self._infer_type_new_call(caller, context)
            if new_cls:
                return iter((new_cls,))

        return super().infer_call_result(caller, context)

    def bool_value(self, context=None):
        return True

class Generator(BaseInstance):
    """a special node representing a generator.

    Proxied class is set once for all in raw_building.
    """

    # pylint: disable=unnecessary-lambda
    special_attributes = util.lazy_descriptor(lambda: objectmodel.GeneratorModel())

    # pylint: disable=super-init-not-called
    def __init__(self, parent=None):
        self.parent = parent

    def callable(self):
        return False

    def pytype(self):
        return "%s.generator" % BUILTINS

    def display_type(self):
        return "Generator"

    def bool_value(self, context=None):
        return True

    def __repr__(self):
        return "<Generator({}) l.{} at 0x{}>".format(
            self._proxied.name, self.lineno, id(self)
        )

    def __str__(self):
        return "Generator(%s)" % (self._proxied.name)

class AsyncGenerator(Generator):
    """Special node representing an async generator"""

    def pytype(self):
        return "%s.async_generator" % BUILTINS

    def display_type(self):
        return "AsyncGenerator"

    def __repr__(self):
        return "<AsyncGenerator({}) l.{} at 0x{}>".format(
            self._proxied.name, self.lineno, id(self)
        )

    def __str__(self):
        return "AsyncGenerator(%s)" % (self._proxied.name)


text:
#ifndef TR3DUtils_RenderVAO_hpp
#define TR3DUtils_RenderVAO_hpp

#include <TR3DUtils/Common.hpp>
#include <TR3DUtils/Disposable.hpp>

namespace TR3DUtils
{
	class RenderBuffer;

	class RenderVAO : public Disposable
	{
	public:
		RenderVAO(const std::vector<std::shared_ptr<const RenderBuffer>> & buffers, GLenum primitiveType);

		virtual ~RenderVAO(void);

		virtual void dispose(void);

        bool isUsable(void) const;

		size_t getVertexCount(void) const;

		void draw(void) const;

		void draw(GLint vertexStart, GLsizei vertexCount) const;

	private:
		void bindBuffers(void) const;

	private:
		const std::vector<std::shared_ptr<const RenderBuffer>> buffers;

		const GLenum primitiveType;

		GLuint vaoId;
	};
}

#endif

redpajama_set_name: RedPajamaGithub


text:
title: "Forms"
section: "AngleSharp.Core"
---
# Form Submission by Example

## Standard Forms

One of the most needed functionalities of a dynamic DOM is the possibility to submit forms. Submitting a form with AngleSharp can be as simple as:

```cs
IBrowsingContext context = BrowsingContext.New(Configuration.Default.WithDefaultLoader());
IDocument queryDocument = await context.OpenAsync("https://google.com");
IHtmlFormElement form = queryDocument.QuerySelector<IHtmlFormElement>("form");
IDocument resultDocument = await form.SubmitAsync(new { q = "anglesharp" });
// e.g., resultDocument.QuerySelectorAll<IHtmlAnchorElement>("#ires .g h3.r a").Select(m => m.Href).Dump();
```

The shown example uses a special overload of the `SubmitAsync` method of an `IHtmlFormElement`, which allows us to pass in an anonymous object that consists of the names of the form fields with their desired values. Alternatively, we could have written code like

```cs
// ...
var queryInput = form.Elements["q"] as IHtmlInputElement;

if (queryInput != null)
{
    queryInput.Value = "anglesharp";
}
```

The latter version is much more verbose and requires additional checking on our side. The upside of this version is that we can also treat the error case (i.e., the expected field with the name `q` is not found or is not an `IHtmlInputElement`), which is completely ignored in the former version.

An important aspect of submitting forms is that we require at least a default loader. Forms usually require making an HTTP request for loading a new document (mostly using the POST verb), which yields the demand for having a requester configured upfront. Note that sometimes forms even come with stronger requirements, especially if they are properly secured. In such cases the use of `WithCookies()` to configure a cookie container could be mandatory.

The code for using a cookie container looks almost identical:

```cs
Iconfiguration config = Configuration.Default
    .WithDefaultLoader()
    .WithCookies();
IBrowsingContext context = BrowsingContext.New(config);
// ...
```

## AJAX / JavaScript Powered Forms

AngleSharp itself does not provide a JavaScript parser or engine. Some libraries exist or try to solve this problem, however, at the moment no library is mature or powerful enough to cope with JavaScript powered forms in general.

Once a form is no longer a real form, but relies on JavaScript manipulation (or just uses a bunch of input fields to form a set of data that is ultimately transferred to a server via a constructed XHR / `fetch` call) AngleSharp is essentially out of the game. At this point one may try to reverse engineer the logic of the JavaScript to perform the same steps and submit the same data. AngleSharp may assist here, but is certainly not the greatest help, if any.


text:
namespace Tall.Gitnub.Core
{
    using System.Collections.Generic;

    /// <summary>
    /// Interface describing a repository of configuration information.
    /// </summary>
    public interface IConfigurationStore
    {
        /// <summary>
        ///   Gets the values for the given name.
        /// </summary>
        /// <param name = "name">The name.</param>
        /// <returns></returns>
        IEnumerable<string> GetValues(string name);
    }
}


text:
require 'clean_slate_spec_helper'

describe 'Image API' do
  include_context 'mocked data'

  let :images_request_body do
    query = %(
      query {
        images {
          url
        }
      }
    )
    {
      query: query,
      variables: nil
    }
  end

  let :single_image_request_body do
    query = %(
      query Image($id: ID!) {
        image(id: $id) {
          url
        }
      }
    )
    {
      query: query,
      variables: {
        id: image_one.id
      }
    }
  end

  let :create_image_request_body do
    query = %(
      mutation CreateImage($taskId: ID!, $url: String!) {
        createImage(taskId: $taskId, url: $url) {
          url
        }
      }
    )
    {
      query: query,
      variables: {
        taskId: task_two.id,
        url: 'http://www.newurl.com'
      }
    }
  end

  let :delete_image_request_body do
    query = %(
      mutation DeleteImage($id: ID!) {
        deleteImage(id: $id) {
          url
        }
      }
    )
    {
      query: query,
      variables: {
        id: image_two.id
      }
    }
  end

  context 'when a user is not logged in' do
  end

  context 'when a user is logged in' do
    it 'queries all images for the current user' do
      send_authorized_request(images_request_body)
      response_body = parse_json(response)
      images = response_body['data']['images']
      expect(images).to have(2).images
      first_image_url = images[0]['url']
      expect(first_image_url).to eq(image_one.url)
    end

    it 'queries a single image' do
      send_authorized_request(single_image_request_body)
      response_body = parse_json(response)
      image = response_body['data']['image']
      expect(image['url']).to eq(image_one.url)
    end

    it 'creates a new image' do
      send_authorized_request(create_image_request_body)
      response_body = parse_json(response)
      image = response_body['data']['createImage']
      expected_url = create_image_request_body[:variables][:url]
      expect(image['url']).to eq(expected_url)
    end

    it 'deletes an image' do
      send_authorized_request(delete_image_request_body)
      response_body = parse_json(response)
      image = response_body['data']['deleteImage']
      expected_url = image_two.url
      expect(image['url']).to eq(expected_url)
      deleted_image = Image.find_by_id(image_two.id)
      expect(deleted_image).to be_nil
    end
  end
end


text:
package com.easyooo.framework.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.easyooo.framework.demo.domain.TUser;
import com.easyooo.framework.demo.domain.TUserDetail;
import com.easyooo.framework.demo.mapper.TUserDetailMapper;
import com.easyooo.framework.demo.mapper.TUserMapper;

/**
 *
 * @author Killer
 */
@Service
public class SimpleService {

	@Autowired
	private TUserMapper tUserMapper;
	@Autowired
	private TUserDetailMapper tUserDetailMapper;

	public void insertUser(Long userId) {

		//List<TUser> users = tUserMapper.selectAll();
		//System.out.println(users);

		TUserDetail detail = new TUserDetail();
		detail.setUserId(userId);
		detail.setSex("M");
		detail.setTel(10000);
		detail.setLinkman("ZS");
		tUserDetailMapper.insert(detail);

		TUser user = new TUser(userId);
		user.setStatus("UNOK");
		user.setUserName("killer");
		tUserMapper.insert(user);
	}

	public boolean deleteUser(Long userId) {

		int row1 = tUserMapper.deleteByPrimaryKey(new TUser(userId));
		int row2 = tUserDetailMapper.deleteByPrimaryKey(new TUserDetail(userId));

		if(row1 != row2){
			return false;
		}
		return true;
	}

}


text:
export default {
    /**
     * @ngInject
     */
    event: function($stateParams) {
        // TODO(ewinslow): Actually fetch something from server/local storage
        return {
            id: $stateParams.event
        };
    }
};


text:
Home Page

          <button type="button" (click)="clickSign()" class="btn btn-default">Sign Guestbook</button>
          <button type="button" (click)="clickBrowse()" class="btn btn-default">Browse Guestbook</button>
          <button type="button" (click)="clickSearch()" class="btn btn-default">Search Guestbook</button>

          <sign-guestbook></sign-guestbook>

          <browse-guestbook></browse-guestbook>

          <search-guestbook></search-guestbook>

<clock></clock>


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class MenuRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'sometimes|required|unique:menus',
            'display_name' => 'sometimes|required',
            'description' => 'sometimes|required',
            'content' => 'sometimes|required',
        ];
    }

    /**
     * Get validation messages.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'unique' => ':attribute已经存在,请更换',
        ];
    }

    /**
     * Get validation attributes.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => '菜单名称',
            'display_name' => '显示名称',
            'description' => '菜单描述',
            'content' => '菜单内容',
        ];
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>MetricsRegionWrapper xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

View Javadoc

1
18
19  package org.apache.hadoop.hbase.regionserver;
20
21  import java.util.Map;
22
23  import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
24
25  /**
26   * Interface of class that will wrap an HRegion and export numbers so they can be
27   * used in MetricsRegionSource
28   */
29  public interface MetricsRegionWrapper {
30
31    /**
32     * Get the name of the table the region belongs to.
33     *
34     * @return The string version of the table name.
35     */
36    String getTableName();
37
38    /**
39     * Get the name of the namespace this table is in.
40     * @return String version of the namespace.  Can't be empty.
41     */
42    String getNamespace();
43
44    /**
45     * Get the name of the region.
46     *
47     * @return The encoded name of the region.
48     */
49    String getRegionName();
50
51    /**
52     * Get the number of stores hosted on this region server.
53     */
54    long getNumStores();
55
56    /**
57     * Get the number of store files hosted on this region server.
58     */
59    long getNumStoreFiles();
60
61    /**
62     * Get the size of the memstore on this region server.
63     */
64    long getMemstoreSize();
65
66    /**
67     * Get the total size of the store files this region server is serving from.
68     */
69    long getStoreFileSize();
70
71    /**
72     * Get the total number of read requests that have been issued against this region
73     */
74    long getReadRequestCount();
75
76    /**
77     * Get the total number of mutations that have been issued against this region.
78     */
79    long getWriteRequestCount();
80
81    long getNumFilesCompacted();
82
83    long getNumBytesCompacted();
84
85    long getNumCompactionsCompleted();
86
87    /**
88     * Get the time spent by coprocessors in this region.
89     */
90    Map<String, DescriptiveStatistics> getCoprocessorExecutionStatistics();
91  }

This page was automatically generated by Maven


text:
import expect from 'expect';
import userReducer from '../../../client/reducers/userReducer';
import * as actions from '../../../client/actions/userActions';
import currentlySelectedReducer from
'../../../client/reducers/currentlySelectedReducers';

describe('User Reducer', () => {
  it('should add user when passed CREATE_USER_SUCCESS', (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };
    // arrange
    const user = {
      name: 'test reducer',
      username: 'testreduce',
      email: 'testreduce@gmail.com',
      password: 'password',
      roleId: 2
    };

    const action = actions.createUserSuccess(user);

    // act
    const newState = userReducer(initialState.manageUsers, action);

    // assert
    expect(newState.length).toEqual(1);
    expect(newState[0].users.name).toEqual('test reducer');
    done();
  });

  it('should get user when passed GET_USERS_SUCCESS', (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };

    const action = actions.getUserSuccess('Subair Oyindamola');

    // act
    const newState = userReducer(initialState.manageUsers, action);
    // assert
    expect(newState.length).toEqual(1);
    expect(newState[0].owner).toEqual('Subair Oyindamola');
    done();
  });

  it('should load users when passed LOAD_USERS_SUCCESS', (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };
    // arrange
    const data = { user: [{
      name: 'test reducer',
      username: 'testreduce',
      email: 'testreduce@gmail.com',
      password: 'password',
      roleId: 2
    },
    {
      name: 'test user',
      username: 'usertest',
      email: 'usere@gmail.com',
      password: 'password',
      roleId: 2
    }],
      pageMeta: {
        limit: 1,
        offset: 0,
        total_count: 2
      } };

    const action = actions.loadUserSuccess(data);

    // act
    const newState = userReducer(initialState.manageUsers, action);
    // assert
    expect(newState.allUsers.length).toEqual(2);
    expect(newState.allUsers[0].name).toEqual('test reducer');
    expect(newState.allUsers[1].name).toEqual('test user');
    done();
  });

  it('should set selected users when passed SET_SELECTED_USER', (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };
    // arrange
    const user = [{
      id: 1,
      name: 'test reducer',
      username: 'testreduce',
      email: 'testreduce@gmail.com',
      password: 'password',
      roleId: 1
    }, {
      id: 2,
      name: 'test user',
      username: 'usertest',
      email: 'usere@gmail.com',
      password: 'password',
      roleId: 2
    }];

    const action = actions.setSelectedUser(user[0].id);

    // act
    const newState = currentlySelectedReducer(initialState.manageUsers, action);

    // assert
    expect(newState.selectedUser).toEqual(1);
    done();
  });

  it('should set userDetails to true when passed DISPLAY_SELECT_USER',
  (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };
    // arrange
    const user = [{
      id: 1,
      name: 'test reducer',
      username: 'testreduce',
      email: 'testreduce@gmail.com',
      password: 'password',
      roleId: 1
    }, {
      id: 2,
      name: 'test user',
      username: 'usertest',
      email: 'usere@gmail.com',
      password: 'password',
      roleId: 2
    }];

    const action = actions.displaySelectedUser(String(user[0].id));

    // act
    const newState = userReducer(initialState.manageUsers, action);

    // assert
    expect(newState.userDetails).toEqual(true);
    done();
  });

  it('should get user when passed DELETE_SELECTED_USER', (done) => {
    const initialState = {
      manageUsers: { allUsers: [], userDetails: false, authUser: [] }
    };
    // arrange
    const user = [{
      id: 1,
      name: 'test reducer',
      username: 'testreduce',
      email: 'testreduce@gmail.com',
      password: 'password',
      roleId: 1
    }, {
      id: 2,
      name: 'test user',
      username: 'usertest',
      email: 'usere@gmail.com',
      password: 'password',
      roleId: 2
    }];
    let newState;
    let action;
    action = actions.setSelectedUser(user[0].id);

    newState = currentlySelectedReducer(initialState.manageUsers, action);
    expect(newState.selectedUser).toEqual(1);

    action = actions.deleteSelectedUser(user[0].id);

    // act
    newState = currentlySelectedReducer(initialState.manageUsers, action);
    // assert
    expect(newState.selectedUser).toNotExist();
    done();
  });
});


text:
namespace ash {

namespace {

display::ManagedDisplayInfo CreateDisplayInfo(int64_t id,
                                              const gfx::Rect& bounds,
                                              float scale = 1.f) {
  display::ManagedDisplayInfo info(
      id, base::StringPrintf("x-%d", static_cast<int>(id)), false);
  info.SetBounds(bounds);
  info.set_device_scale_factor(scale);
  return info;
}

class MirrorOnBootTest : public AshTestBase {
 public:
  MirrorOnBootTest() = default;
  ~MirrorOnBootTest() override = default;

  void SetUp() override {
    base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        ::switches::kHostWindowBounds, "1+1-300x300,1+301-300x300");
    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        ::switches::kEnableSoftwareMirroring);
    AshTestBase::SetUp();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MirrorOnBootTest);
};

}  // namespace

using MirrorWindowControllerTest = AshTestBase;

// Make sure that the compositor based mirroring can switch
// from/to dock mode.
TEST_F(MirrorWindowControllerTest, DockMode) {
  const int64_t internal_id = 1;
  const int64_t external_id = 2;

  const display::ManagedDisplayInfo internal_display_info =
      CreateDisplayInfo(internal_id, gfx::Rect(0, 0, 500, 500));
  const display::ManagedDisplayInfo external_display_info =
      CreateDisplayInfo(external_id, gfx::Rect(1, 1, 100, 100));
  std::vector<display::ManagedDisplayInfo> display_info_list;

  // software mirroring.
  display_info_list.push_back(internal_display_info);
  display_info_list.push_back(external_display_info);
  display_manager()->OnNativeDisplaysChanged(display_info_list);
  const int64_t internal_display_id =
      display::test::DisplayManagerTestApi(display_manager())
          .SetFirstDisplayAsInternalDisplay();
  EXPECT_EQ(internal_id, internal_display_id);

  display_manager()->SetMirrorMode(display::MirrorMode::kNormal, base::nullopt);
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(1U, display_manager()->GetNumDisplays());
  EXPECT_TRUE(display_manager()->IsInSoftwareMirrorMode());
  EXPECT_EQ(external_id,
            display_manager()->GetMirroringDestinationDisplayIdList()[0]);

  // dock mode.
  display_info_list.clear();
  display_info_list.push_back(external_display_info);
  display_manager()->OnNativeDisplaysChanged(display_info_list);
  EXPECT_EQ(1U, display_manager()->GetNumDisplays());
  EXPECT_FALSE(display_manager()->IsInMirrorMode());

  // back to software mirroring.
  display_info_list.clear();
  display_info_list.push_back(internal_display_info);
  display_info_list.push_back(external_display_info);
  display_manager()->OnNativeDisplaysChanged(display_info_list);
  EXPECT_EQ(1U, display_manager()->GetNumDisplays());
  EXPECT_TRUE(display_manager()->IsInMirrorMode());
  EXPECT_EQ(external_id,
            display_manager()->GetMirroringDestinationDisplayIdList()[0]);
}

TEST_F(MirrorOnBootTest, MirrorOnBoot) {
  EXPECT_TRUE(display_manager()->IsInMirrorMode());

  base::RunLoop().RunUntilIdle();
  MirrorWindowTestApi test_api;
  EXPECT_EQ(1U, test_api.GetHosts().size());
}

class MirrorWindowControllerRotationAndPanelOrientationTest
    : public MirrorWindowControllerTest,
      public testing::WithParamInterface<
          std::tuple<display::Display::Rotation, display::PanelOrientation>> {};

// Test that the mirror display matches the size and rotation of the source.
TEST_P(MirrorWindowControllerRotationAndPanelOrientationTest, MirrorSize) {
  const int64_t primary_id = 1;
  const int64_t mirror_id = 2;

  const display::Display::Rotation active_rotation = std::get<0>(GetParam());
  const display::PanelOrientation panel_orientation = std::get<1>(GetParam());

  // Run the test with and without display scaling.
  int scale_factors[] = {1, 2};
  for (int scale : scale_factors) {
    display::ManagedDisplayInfo primary_display_info =
        CreateDisplayInfo(primary_id, gfx::Rect(0, 0, 400, 300), scale);
    primary_display_info.set_panel_orientation(panel_orientation);
    primary_display_info.SetRotation(active_rotation,
                                     display::Display::RotationSource::ACTIVE);

    const display::ManagedDisplayInfo mirror_display_info =
        CreateDisplayInfo(mirror_id, gfx::Rect(400, 0, 600, 500), scale);
    std::vector<display::ManagedDisplayInfo> display_info_list = {
        primary_display_info, mirror_display_info};

    // Start software mirroring.
    display_manager()->OnNativeDisplaysChanged(display_info_list);
    display_manager()->SetMirrorMode(display::MirrorMode::kNormal,
                                     base::nullopt);
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(1U, display_manager()->GetNumDisplays());
    EXPECT_TRUE(display_manager()->IsInSoftwareMirrorMode());

    // Check the size of the mirror window.
    const display::Display& primary_display =
        display_manager()->GetDisplayForId(primary_id);
    aura::Window* root_window = Shell::GetRootWindowForDisplayId(mirror_id);
    aura::Window* mirror_window = root_window->children()[0];
    EXPECT_EQ(primary_display.GetSizeInPixel(), root_window->bounds().size());
    EXPECT_EQ(primary_display.GetSizeInPixel(), mirror_window->bounds().size());

    // Mirror should have a display transform hint that matches the active
    // rotation (excluding the panel orientation) of the source.
    EXPECT_EQ(display::DisplayRotationToOverlayTransform(active_rotation),
              root_window->GetHost()->compositor()->display_transform_hint());
  }
}

INSTANTIATE_TEST_SUITE_P(
    All,
    MirrorWindowControllerRotationAndPanelOrientationTest,
    testing::Combine(testing::Values(display::Display::ROTATE_0,
                                     display::Display::ROTATE_90,
                                     display::Display::ROTATE_180,
                                     display::Display::ROTATE_270),
                     testing::Values(display::PanelOrientation::kNormal,
                                     display::PanelOrientation::kBottomUp,
                                     display::PanelOrientation::kLeftUp,
                                     display::PanelOrientation::kRightUp)));

}  // namespace ash


text:
package org.cloudfoundry.client.v2.shareddomains;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;

/**
 * The entity response payload for the Domain resource
 */
@JsonDeserialize
@Value.Immutable
abstract class _SharedDomainEntity {

    /**
     * The name
     */
    @JsonProperty("name")
    @Nullable
    abstract String getName();

    /**
     * The router group id
     */
    @JsonProperty("router_group_guid")
    @Nullable
    abstract String getRouterGroupId();

    /**
     * The router group type
     */
    @JsonProperty("router_group_type")
    @Nullable
    abstract String getRouterGroupType();

}


text:
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=PDF.co%20Web%20API%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=PDF.co%20Web%20API%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore Documentation](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Explore Source Code Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://app.pdf.co/signup?utm_source=github-readme)
[Security](https://pdf.co/security)
[Explore Web API Documentation](https://apidocs.pdf.co?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### **ManageBackgroundJob.py:**

```
import requests

url = "https://api.pdf.co/v1/job/check"

payload = {'jobid': '123'}
files = [

]
headers = {
		'x-api-key': '{{x-api-key}}'
}

response = requests.request("POST", url, headers=headers, json = payload, files = files)

print(response.text.encode('utf8'))

```

<!-- code block end -->


text:
namespace views {
class ImageButton;
class ScrollView;
}

namespace message_center {

class MessageCenter;
class MessageViewContextMenuController;

// Individual notifications constants.
const int kPaddingBetweenItems = 10;
const int kPaddingHorizontal = 18;
const int kWebNotificationButtonWidth = 32;
const int kWebNotificationIconSize = 40;

// An abstract class that forms the basis of a view for a notification entry.
class MESSAGE_CENTER_EXPORT MessageView : public views::SlideOutView,
                                          public views::ButtonListener {
 public:
  MessageView(const Notification& notification,
              MessageCenter* message_center,
              bool expanded);
  virtual ~MessageView();

  // Returns the insets for the shadow it will have for rich notification.
  static gfx::Insets GetShadowInsets();

  bool IsCloseButtonFocused();
  void RequestFocusOnCloseButton();

  void set_accessible_name(const string16& name) { accessible_name_ = name; }

  // Overridden from views::View:
  virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;
  virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE;
  virtual bool OnKeyPressed(const ui::KeyEvent& event) OVERRIDE;
  virtual bool OnKeyReleased(const ui::KeyEvent& event) OVERRIDE;
  virtual void OnPaintFocusBorder(gfx::Canvas* canvas) OVERRIDE;

  // Overridden from ui::EventHandler:
  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;

  // Overridden from ButtonListener:
  virtual void ButtonPressed(views::Button* sender,
                             const ui::Event& event) OVERRIDE;

  const std::string& notification_id() { return notification_id_; }
  void set_scroller(views::ScrollView* scroller) { scroller_ = scroller; }

 protected:
  MessageView();

  // Overridden from views::SlideOutView:
  virtual void OnSlideOut() OVERRIDE;

  MessageCenter* message_center() { return message_center_; }
  views::ImageButton* close_button() { return close_button_.get(); }
  views::ImageButton* expand_button() { return expand_button_.get(); }
  views::ScrollView* scroller() { return scroller_; }
  const bool is_expanded() { return is_expanded_; }

 private:
  MessageCenter* message_center_;  // Weak reference.
  std::string notification_id_;

  scoped_ptr<MessageViewContextMenuController> context_menu_controller_;
  scoped_ptr<views::ImageButton> close_button_;
  scoped_ptr<views::ImageButton> expand_button_;
  views::ScrollView* scroller_;

  string16 accessible_name_;

  bool is_expanded_;

  DISALLOW_COPY_AND_ASSIGN(MessageView);
};

}  // namespace message_center

#endif // UI_MESSAGE_CENTER_VIEWS_MESSAGE_VIEW_H_


text:
title=Iterate through ActionScript Object properties – AS Reflection
date=2009-09-20
author=Manik Magar
type=post
guid=http://manikmagar.wordpress.com/2009/09/20/iterate-through-actionscript-object-properties-as-reflection/
permalink=/iterate-through-actionscript-object-properties-as-reflection/
tags=Flex
status=published
~~~~~~

I was wondering if reflection is possible in ActionScript or not. After diving into API, i got something which seems like reflection in Flex.

ActionScript API provide one class ObjectUtil. It contains some helper methods like compare, dateComapre etc for handling objects.

This class also has one very useful method getClassInfo(). Below code shows usage of this method to iterate through properties of an object –

```
 <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        width="100%" height="100%" creationComplete="init(event)">
       <mx:Script>
           <![CDATA[
               import mx.utils.ObjectUtil;
               private function init(event:Event):void{
                   printProperties1();
                   printProperties2();
               }
               private function printProperties1():void{
                   var props:Object = ObjectUtil.getClassInfo(this);
                   for each (var p:QName in props.properties){
                       var propName:String = p.localName;
                       var propValue:Object = this[propName];
                       trace(propName +":"+ propValue);
                   }
              }
              private function printProperties2():void{
                  var excludes:Array = ['x','y'];
                  var props:Object = ObjectUtil.getClassInfo(this,excludes);
                  for each (var p:QName in props.properties){
                      var propName:String = p.localName;
                      var propValue:Object = this[propName];
                      trace(propName +":"+ propValue);
                  }
              }
          ]]>
      </mx:Script>
  </mx:Application>
```

printProperties1() method should print all properties of Application class. Second implementation printProperties2() shows excluding certain properties from search.

Even though this introspection is not like java or any other language reflection but still its very useful since flex supports dynamic objects. To iterate through properties of dynamic objects this method can be used.

Hope this helps!


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit015edf51f027b261c4c4c16a5158c02f::getLoader();


text:
package controller

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"sync"
	"time"

	"github.com/coreos/etcd-operator/pkg/analytics"
	"github.com/coreos/etcd-operator/pkg/backup/s3/s3config"
	"github.com/coreos/etcd-operator/pkg/cluster"
	"github.com/coreos/etcd-operator/pkg/spec"
	"github.com/coreos/etcd-operator/pkg/util/k8sutil"

	"github.com/Sirupsen/logrus"
	k8sapi "k8s.io/kubernetes/pkg/api"
	unversionedAPI "k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apis/extensions"
	"k8s.io/kubernetes/pkg/client/unversioned"
)

const (
	tprName = "etcd-cluster.coreos.com"

	defaultVersion = "v3.1.0-alpha.1"
)

var (
	supportedPVProvisioners = map[string]struct{}{
		"kubernetes.io/gce-pd":  {},
		"kubernetes.io/aws-ebs": {},
	}

	ErrVersionOutdated = errors.New("requested version is outdated in apiserver")

	initRetryWaitTime = 30 * time.Second
)

type rawEvent struct {
	Type   string
	Object json.RawMessage
}

type Event struct {
	Type   string
	Object *spec.EtcdCluster
}

type Controller struct {
	logger *logrus.Entry

	Config
	clusters    map[string]*cluster.Cluster
	stopChMap   map[string]chan struct{}
	waitCluster sync.WaitGroup
}

type Config struct {
	MasterHost    string
	Namespace     string
	PVProvisioner string
	s3config.S3Context
	KubeCli *unversioned.Client
}

func (c *Config) validate() error {
	if _, ok := supportedPVProvisioners[c.PVProvisioner]; !ok {
		return fmt.Errorf(
			"persistent volume provisioner %s is not supported: options = %v",
			c.PVProvisioner, supportedPVProvisioners,
		)
	}
	return nil
}

func New(cfg Config) *Controller {
	if err := cfg.validate(); err != nil {
		panic(err)
	}
	return &Controller{
		logger: logrus.WithField("pkg", "controller"),

		Config:    cfg,
		clusters:  make(map[string]*cluster.Cluster),
		stopChMap: map[string]chan struct{}{},
	}
}

func (c *Controller) Run() error {
	var (
		watchVersion string
		err          error
	)

	for {
		watchVersion, err = c.initResource()
		if err == nil {
			break
		}
		c.logger.Errorf("initialization failed: %v", err)
		c.logger.Infof("retry in %v...", initRetryWaitTime)
		time.Sleep(initRetryWaitTime)
		// todo: add max retry?
	}

	c.logger.Infof("starts running from watch version: %s", watchVersion)

	defer func() {
		for _, stopC := range c.stopChMap {
			close(stopC)
		}
		c.waitCluster.Wait()
	}()

	eventCh, errCh := c.monitor(watchVersion)

	go func() {
		for event := range eventCh {
			if s := event.Object.Spec; len(s.Version) == 0 {
				// TODO: set version in spec in apiserver
				s.Version = defaultVersion
			}

			clusterName := event.Object.ObjectMeta.Name
			switch event.Type {
			case "ADDED":
				stopC := make(chan struct{})
				nc, err := cluster.New(c.makeClusterConfig(), event.Object, stopC, &c.waitCluster)
				if err != nil {
					c.logger.Errorf("cluster (%q) is dead: %v", clusterName, err)
					continue
				}

				c.stopChMap[clusterName] = stopC
				c.clusters[clusterName] = nc

				analytics.ClusterCreated()
			case "MODIFIED":
				if c.clusters[clusterName] == nil {
					c.logger.Warningf("ignore modification: cluster %q not found (or dead)", clusterName)
					break
				}
				c.clusters[clusterName].Update(event.Object)
			case "DELETED":
				if c.clusters[clusterName] == nil {
					c.logger.Warningf("ignore deletion: cluster %q not found (or dead)", clusterName)
					break
				}
				c.clusters[clusterName].Delete()
				delete(c.clusters, clusterName)
				analytics.ClusterDeleted()
			}
		}
	}()
	return <-errCh
}

func (c *Controller) findAllClusters() (string, error) {
	c.logger.Info("finding existing clusters...")
	resp, err := k8sutil.ListETCDCluster(c.MasterHost, c.Namespace, c.KubeCli.RESTClient.Client)
	if err != nil {
		return "", err
	}
	d := json.NewDecoder(resp.Body)
	list := &EtcdClusterList{}
	if err := d.Decode(list); err != nil {
		return "", err
	}
	for _, item := range list.Items {
		clusterName := item.Name
		stopC := make(chan struct{})
		nc, err := cluster.Restore(c.makeClusterConfig(), &item, stopC, &c.waitCluster)
		if err != nil {
			c.logger.Errorf("cluster (%q) is dead: %v", clusterName, err)
			continue
		}
		c.stopChMap[clusterName] = stopC
		c.clusters[clusterName] = nc
	}
	return list.ListMeta.ResourceVersion, nil
}

func (c *Controller) makeClusterConfig() cluster.Config {
	return cluster.Config{
		PVProvisioner: c.PVProvisioner,
		S3Context:     c.S3Context,
		KubeCli:       c.KubeCli,
	}
}

func (c *Controller) initResource() (string, error) {
	watchVersion := "0"
	err := c.createTPR()
	if err != nil {
		if k8sutil.IsKubernetesResourceAlreadyExistError(err) {
			// TPR has been initialized before. We need to recover existing cluster.
			watchVersion, err = c.findAllClusters()
			if err != nil {
				return "", err
			}
		} else {
			return "", fmt.Errorf("fail to create TPR: %v", err)
		}
	}
	err = k8sutil.CreateStorageClass(c.KubeCli, c.PVProvisioner)
	if err != nil {
		if !k8sutil.IsKubernetesResourceAlreadyExistError(err) {
			return "", fmt.Errorf("fail to create storage class: %v", err)
		}
	}
	return watchVersion, nil
}

func (c *Controller) createTPR() error {
	tpr := &extensions.ThirdPartyResource{
		ObjectMeta: k8sapi.ObjectMeta{
			Name: tprName,
		},
		Versions: []extensions.APIVersion{
			{Name: "v1"},
		},
		Description: "Managed etcd clusters",
	}
	_, err := c.KubeCli.ThirdPartyResources().Create(tpr)
	if err != nil {
		return err
	}

	return k8sutil.WaitEtcdTPRReady(c.KubeCli.Client, 3*time.Second, 30*time.Second, c.MasterHost, c.Namespace)
}

func (c *Controller) monitor(watchVersion string) (<-chan *Event, <-chan error) {
	host := c.MasterHost
	ns := c.Namespace
	httpClient := c.KubeCli.Client

	eventCh := make(chan *Event)
	// On unexpected error case, controller should exit
	errCh := make(chan error, 1)

	go func() {
		defer close(eventCh)

		for {
			resp, err := k8sutil.WatchETCDCluster(host, ns, httpClient, watchVersion)
			if err != nil {
				errCh <- err
				return
			}
			if resp.StatusCode != 200 {
				resp.Body.Close()
				errCh <- errors.New("Invalid status code: " + resp.Status)
				return
			}

			c.logger.Infof("start watching at %v", watchVersion)

			decoder := json.NewDecoder(resp.Body)
			for {
				ev, st, err := pollEvent(decoder)

				if err != nil {
					if err == io.EOF { // apiserver will close stream periodically
						c.logger.Debug("apiserver closed stream")
						break
					}

					c.logger.Errorf("received invalid event from API server: %v", err)
					errCh <- err
					return
				}

				if st != nil {
					if st.Code == http.StatusGone { // event history is outdated
						errCh <- ErrVersionOutdated // go to recovery path
						return
					}
					c.logger.Fatalf("unexpected status response from API server: %v", st.Message)
				}

				c.logger.Debugf("etcd cluster event: %v %v", ev.Type, ev.Object.Spec)

				watchVersion = ev.Object.ObjectMeta.ResourceVersion
				eventCh <- ev
			}

			resp.Body.Close()
		}
	}()

	return eventCh, errCh
}

func pollEvent(decoder *json.Decoder) (*Event, *unversionedAPI.Status, error) {
	re := &rawEvent{}
	err := decoder.Decode(re)
	if err != nil {
		if err == io.EOF {
			return nil, nil, err
		}
		return nil, nil, fmt.Errorf("fail to decode raw event from apiserver (%v)", err)
	}

	if re.Type == "ERROR" {
		status := &unversionedAPI.Status{}
		err = json.Unmarshal(re.Object, status)
		if err != nil {
			return nil, nil, fmt.Errorf("fail to decode (%s) into unversioned.Status (%v)", re.Object, err)
		}
		return nil, status, nil
	}

	ev := &Event{
		Type:   re.Type,
		Object: &spec.EtcdCluster{},
	}
	err = json.Unmarshal(re.Object, ev.Object)
	if err != nil {
		return nil, nil, fmt.Errorf("fail to unmarshal EtcdCluster object from data (%s): %v", re.Object, err)
	}
	return ev, nil, nil
}


text:
![screenshot](media/screenshot.png)

An offline Javscript, Python, Coffescript and Markdown editor. This editor is aimed at beginners who want an easy to use tool for learning programming. This editor is not to be used as a full development environment as there are more powerful ones like [Sublime](http://www.sublimetext.com) and [Atom](https://atom.io).

# Install

# Features

# Setup

# Usage

# Licence


text:
require 'test_datastructures'

class TestTreeNode < Test::Unit::TestCase

  context "TestTreeNode" do

    setup do
      @tree = DataStructures::TreeNode.new('grandmother')
    end

    should "be able to create a new instance" do
      @tree = DataStructures::TreeNode.new('')
    end

    should "begin empty" do
      assert @tree.empty?, "knows it's empty"
      assert @tree.child_count == 0, "0 children in empty tree"
      assert @tree.is_leaf?, "an empty tree is a leaf"
    end

    should "be able to add, recognise and remove children" do
      child = DataStructures::TreeNode.new('child')
      assert @tree.is_leaf?, "should start out as leaf"

      @tree.add_child child
      assert_equal @tree.child_count, 1, "child count should be 1"
      assert !@tree.is_leaf?, "should no longer be leaf"
      assert_equal @tree.children.first, child, "only child should be the one just added"

      @tree.remove_child! child
      assert_not_include @tree.children, child, "deleted child is forgotten by parent"
    end

    should "know its family tree" do
      # make a happy family
      mother = DataStructures::TreeNode.new('the mother')
      daughter = DataStructures::TreeNode.new('the daughter')
      son = DataStructures::TreeNode.new('the son')
      mother.add_child daughter
      mother.add_child son
      uncle = DataStructures::TreeNode.new('the uncle')
      cousin = DataStructures::TreeNode.new('the cousin')
      uncle << cousin
      @tree << mother
      @tree << uncle

      assert_equal @tree.siblings, nil, "grandmother has no siblings :("

      [mother, daughter, son, uncle, cousin].each do |descendent|
        assert_include @tree.descendents, descendent, "should recognise #{descendent.data} as descendent"
      end

      assert_not_include mother.siblings, mother, "mother not her own sibling"
      assert_not_include son.siblings, son, "son not his own sibling"

      assert_equal uncle, mother.siblings.first, "mother sees uncle as sibling"
      assert_equal mother, uncle.siblings.first, "uncle sees mother as sibling"
      assert_equal son, daughter.siblings.first, "daughter sees son as sibling"
      assert_equal daughter, son.siblings.first, "son sees daughter as sibling"

      assert_equal daughter.parent, mother, "daughter recogises her own mother"
      assert_equal mother.parent, @tree, "mother knows grandmother is her mother"
      assert_equal cousin.parent.parent, @tree, "cousin recognises her own grandmother"

      assert son.is_leaf?
      assert !mother.is_leaf?
      assert !@tree.is_leaf?
      assert @tree.is_root?

      @tree.clear
      assert @tree.empty?
      assert @tree.is_leaf?
    end

  end # Tree context

end # TestTree


text:
package org.elasticsearch.search.aggregations.bucket.filters;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.Bits;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.bucket.BucketsAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class FiltersAggregator extends BucketsAggregator {

    static class KeyedFilter {

        final String key;
        final Query filter;

        KeyedFilter(String key, Query filter) {
            this.key = key;
            this.filter = filter;
        }
    }

    private final String[] keys;
    private Weight[] filters;
    private final boolean keyed;
    private final boolean showOtherBucket;
    private final String otherBucketKey;
    private final int totalNumKeys;

    public FiltersAggregator(String name, AggregatorFactories factories, String[] keys, Weight[] filters, boolean keyed, String otherBucketKey,
            AggregationContext aggregationContext,
            Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData)
            throws IOException {
        super(name, factories, aggregationContext, parent, pipelineAggregators, metaData);
        this.keyed = keyed;
        this.keys = keys;
        this.filters = filters;
        this.showOtherBucket = otherBucketKey != null;
        this.otherBucketKey = otherBucketKey;
        if (showOtherBucket) {
            this.totalNumKeys = keys.length + 1;
        } else {
            this.totalNumKeys = keys.length;
        }
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
            final LeafBucketCollector sub) throws IOException {
        // no need to provide deleted docs to the filter
        final Bits[] bits = new Bits[filters.length];
        for (int i = 0; i < filters.length; ++i) {
            bits[i] = Lucene.asSequentialAccessBits(ctx.reader().maxDoc(), filters[i].scorer(ctx));
        }
        return new LeafBucketCollectorBase(sub, null) {
            @Override
            public void collect(int doc, long bucket) throws IOException {
                boolean matched = false;
                for (int i = 0; i < bits.length; i++) {
                    if (bits[i].get(doc)) {
                        collectBucket(sub, doc, bucketOrd(bucket, i));
                        matched = true;
                    }
                }
                if (showOtherBucket && !matched) {
                    collectBucket(sub, doc, bucketOrd(bucket, bits.length));
                }
            }
        };
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException {
        List<InternalFilters.InternalBucket> buckets = new ArrayList<>(filters.length);
        for (int i = 0; i < keys.length; i++) {
            long bucketOrd = bucketOrd(owningBucketOrdinal, i);
            InternalFilters.InternalBucket bucket = new InternalFilters.InternalBucket(keys[i], bucketDocCount(bucketOrd), bucketAggregations(bucketOrd), keyed);
            buckets.add(bucket);
        }
        // other bucket
        if (showOtherBucket) {
            long bucketOrd = bucketOrd(owningBucketOrdinal, keys.length);
            InternalFilters.InternalBucket bucket = new InternalFilters.InternalBucket(otherBucketKey, bucketDocCount(bucketOrd),
                    bucketAggregations(bucketOrd), keyed);
            buckets.add(bucket);
        }
        return new InternalFilters(name, buckets, keyed, pipelineAggregators(), metaData());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        InternalAggregations subAggs = buildEmptySubAggregations();
        List<InternalFilters.InternalBucket> buckets = new ArrayList<>(filters.length);
        for (int i = 0; i < keys.length; i++) {
            InternalFilters.InternalBucket bucket = new InternalFilters.InternalBucket(keys[i], 0, subAggs, keyed);
            buckets.add(bucket);
        }
        return new InternalFilters(name, buckets, keyed, pipelineAggregators(), metaData());
    }

    final long bucketOrd(long owningBucketOrdinal, int filterOrd) {
        return owningBucketOrdinal * totalNumKeys + filterOrd;
    }

    public static class Factory extends AggregatorFactory {

        private final List<KeyedFilter> filters;
        private final String[] keys;
        private boolean keyed;
        private String otherBucketKey;

        public Factory(String name, List<KeyedFilter> filters, boolean keyed, String otherBucketKey) {
            super(name, InternalFilters.TYPE.name());
            this.filters = filters;
            this.keyed = keyed;
            this.otherBucketKey = otherBucketKey;
            this.keys = new String[filters.size()];
            for (int i = 0; i < filters.size(); ++i) {
                KeyedFilter keyedFilter = filters.get(i);
                this.keys[i] = keyedFilter.key;
            }
        }

        // TODO: refactor in order to initialize the factory once with its parent,
        // the context, etc. and then have a no-arg lightweight create method
        // (since create may be called thousands of times)

        private IndexSearcher searcher;
        private Weight[] weights;

        @Override
        public Aggregator createInternal(AggregationContext context, Aggregator parent, boolean collectsFromSingleBucket,
                List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException {
            IndexSearcher contextSearcher = context.searchContext().searcher();
            if (searcher != contextSearcher) {
                searcher = contextSearcher;
                weights = new Weight[filters.size()];
                for (int i = 0; i < filters.size(); ++i) {
                    KeyedFilter keyedFilter = filters.get(i);
                    this.weights[i] = contextSearcher.createNormalizedWeight(keyedFilter.filter, false);
                }
            }
            return new FiltersAggregator(name, factories, keys, weights, keyed, otherBucketKey, context, parent, pipelineAggregators, metaData);
        }
    }

}


text:
package energy.usef.core.repository;

import static org.junit.Assert.assertNotNull;
import static org.powermock.reflect.Whitebox.setInternalState;

import energy.usef.core.model.ConnectionGroup;
import energy.usef.core.util.DateTimeUtil;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.joda.time.LocalDate;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * JUnit test for the GridPointRepository class.
 */
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.persistence.*")
public class ConnectionGroupRepositoryTest {

    /** The factory that produces entity manager. */
    private static EntityManagerFactory entityManagerFactory;
    /** The entity manager that persists and queries the DB. */
    private static EntityManager entityManager;

    private ConnectionGroupRepository repository;

    @BeforeClass
    public static void initTestFixture() throws Exception {
        // Get the entity manager for the tests.
        entityManagerFactory = Persistence.createEntityManagerFactory("test");
        entityManager = entityManagerFactory.createEntityManager();
    }

    /**
     * Cleans up the session.
     */
    @AfterClass
    public static void closeTestFixture() {
        entityManager.close();
        entityManagerFactory.close();
    }

    @Before
    public void init() {
        repository = new ConnectionGroupRepository();
        setInternalState(repository, "entityManager", entityManager);

        // clear the entity manager to avoid unexpected results
        repository.getEntityManager().clear();
    }

    /**
     * Tests for GridPointRepository.getGridPointByEntityAddress method.
     */
    @Test
    public void testGetGridPointByEntityAddress() {
        String entityAddress = "ea1.1992-01.com.example:gridpoint.4f76ff19-a53b-49f5-84e6";
        ConnectionGroup connectionGroup = repository.find(entityAddress);
        assertNotNull(connectionGroup);
    }

    @Test
    public void testFindAllGridPoints() {
        List<ConnectionGroup> connectionGroups = repository.findAll();
        assertNotNull(connectionGroups);
        Assert.assertEquals(4, connectionGroups.size());
    }

    @Test
    public void testFindAllForDateTimeFindsSuccessfull() {
        LocalDate period = DateTimeUtil.getCurrentDate();
        List<ConnectionGroup> connectionGroups = repository.findAllForDateTime(period);
        Assert.assertEquals(2, connectionGroups.size());
    }

}


text:
namespace Serenity.Web
{
    ///
    ///   <see cref="ImageChecker"/>'s result codes.
    public enum ImageCheckResult
    {
        ///
        ///   Checked image is a GIF
        GIFImage,
        ///
        ///   Checked image is a JPEG
        JPEGImage,
        ///
        ///   Checked image is a PNG
        PNGImage,
        ///
        ///   Checked file is a FLASH .SWF, ImageChecker itself won't return such a result,
        ///   used by TemporaryImage
        FlashMovie,
        ///
        ///   Unsupported format
        UnsupportedFormat,
        ///
        ///   Error occurred during reading
        StreamReadError,
        ///
        ///   File size too high
        DataSizeTooHigh,
        ///
        ///   Image file is invalid
        InvalidImage,
        ///
        ///   Image is empty, its height or width is zero
        ImageIsEmpty,
        ///
        ///   Image is not at exact pixel width/height
        SizeMismatch,
        ///
        ///   Image doesn't have an exact width
        WidthMismatch,
        ///
        ///   Image is wider than maximum allowed
        WidthTooHigh,
        ///
        ///   Image is shorter than minimum allowed
        WidthTooLow,
        ///
        ///   Image doesn't have an exact height
        HeightMismatch,
        ///
        ///   Image is taller than maximum allowed
        HeightTooHigh,
        ///
        ///   Image is shorter than minimum allowed
        HeightTooLow
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="jp.ne.sakura.kkkon.android.exceptionhandler.testapp"
      android:versionCode="1"
      android:versionName="0.1"
      android:installLocation="preferExternal"
    >
    <application android:label="@string/app_name" >
        <activity android:name=".ExceptionHandlerTestApp"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ExceptionHandlerReportApp"
                  android:label="@string/app_name">
<!--
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
-->
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" />
    <!--<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />-->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>


text:
<?php
// prepare.php

require_once __DIR__.'/config.php';

use Payum\Core\Model\Payment;

$storage = $payum->getStorage($paymentClass);

/**
 * @var Payment
 */
$payment = $storage->create();
$payment->setNumber(uniqid());
$payment->setCurrencyCode('EUR');
$payment->setTotalAmount(1.23); // 1.23 EUR
$payment->setDescription('A description');
$payment->setClientId('anId');
$payment->setClientEmail('foo@example.com');

$payment->setDetails([]);

$storage->update($payment);

$captureToken = $payum->getTokenFactory()->createCaptureToken($gatewayName, $payment, 'Examples/done.php');

header('Location: '.$captureToken->getTargetUrl());


text:
import { formatFileSize, isDefinedGlobally } from './utils';

const messages = {
  _default: (field) => `El camp ${field} no és vàlid.`,
  after: (field, [target]) => `El camp ${field} ha de ser posterior a ${target}.`,
  alpha_dash: (field) => `El camp ${field} només ha de contenir lletres, números i guions.`,
  alpha_num: (field) => `El camp ${field} només ha de contenir lletres i números.`,
  alpha_spaces: (field) => `El camp ${field} només ha de contenir lletres i espais.`,
  alpha: (field) => `El camp ${field} només ha de contenir lletres.`,
  before: (field, [target]) => `El camp ${field} ha de ser anterior a ${target}.`,
  between: (field, [min, max]) => `El camp ${field} ha d'estar entre ${min} i ${max}.`,
  confirmed: (field, [confirmedField]) => `El camp ${field} no coincideix amb el camp ${confirmedField}.`,
  credit_card: (field, [confirmedField]) => `El camp ${field} és invàlid.`,
  date_between: (field, [min, max]) => `El camp ${field} ha d'estar entre ${min} i ${max}.`,
  date_format: (field, [format]) => `El camp ${field} ha de tenir el format ${format}.`,
  decimal: (field, [decimals = '*'] = []) => `El camp ${field} ha de ser numèric i contenir ${decimals === '*' ? '' : decimals} punts decimals.`,
  digits: (field, [length]) => `El camp ${field} ha de ser numèric i contenir exactament ${length} dígits.`,
  dimensions: (field, [width, height]) => `El camp ${field} ha de ser de ${width} píxels per ${height} píxels.`,
  email: (field) => `El camp ${field} ha de ser un correu electrònic vàlid.`,
  ext: (field) => `El camp ${field} ha de ser un fitxer vàlid.`,
  image: (field) => `El camp ${field} ha de ser una imatge.`,
  in: (field) => `El camp ${field} ha de ser un valor vàlid.`,
  ip: (field) => `El camp ${field} ha de ser una adreça ip vàlida.`,
  max: (field, [length]) => `El camp ${field} no ha de ser major a ${length} caràcters.`,
  max_value: (field, [length]) => `El camp ${field} ha de ser de ${length} o menys.`,
  mimes: (field) => `El camp ${field} ha de ser un tipus de fitxer vàlid.`,
  min: (field, [length]) => `El camp ${field} ha de tenir almenys ${length} caràcters.`,
  min_value: (field, [length]) => `El camp ${field} ha de ser de ${length} o superior.`,
  not_in: (field) => `El camp ${field} ha de ser un valor vàlid.`,
  numeric: (field) => `El camp ${field} ha de contenir només caràcters numèrics.`,
  regex: (field) => `El format del camp ${field} no és vàlid.`,
  required: (field) => `El camp ${field} és obligatori.`,
  size: (field, [size]) => `El camp ${field} ha de ser menor a ${formatFileSize(size)}.`,
  url: (field) => `El camp ${field} no és un URL vàlid.`
};

const locale = {
  name: 'ca',
  messages,
  attributes: {}
};

if (isDefinedGlobally()) {
  VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;


text:
.jp-Inspector .p-TabBar {
  min-width: 300px;
  min-height: 24px;
  color: var(--jp-ui-font-color1);
  font-size: 13px;
}

.jp-Inspector .p-TabBar-content {
  min-width: 0;
  padding-right: 1px;
}

.jp-Inspector .p-TabBar-tab {
  flex-basis: 144px;
  min-height: 23px;
  min-width: 35px;
  padding: 0px 7px;
  background: #EEEEEE;
  border: var(--jp-border-width) solid var(--jp-border-color1);
  transform: translateY(-1px);
  border-bottom: none;
  margin-right: -1px;
}

.jp-Inspector .p-TabBar-tab.p-mod-current {
  min-height: 24px;
  background: #FFFFFF;
  border-top: var(--jp-border-width) solid var(--jp-brand-color1);
}

.jp-Inspector .p-TabBar-tab:hover:not(.p-mod-current) {
  background: #FAFAFA;
}

.jp-Inspector .p-TabBar-tabIcon,
.jp-Inspector .p-TabBar-tabText {
  line-height: 24px;
}

.jp-InspectorItem {
  border: var(--jp-border-width) solid var(--jp-border-color2);
}

.jp-InspectorItem .jp-NBToolbar {
    display: flex;
    flex-direction: row;
    border-bottom: var(--jp-border-width) solid var(--jp-border-color2);
    height: 24px;
}

.jp-InspectorItem-content {
  height: calc(100% - 24px); /* Subtract the height of the toolbar. */
  overflow: auto;
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-clear::before {
   content: "\f05e";  /* ban */
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-back::before {
   content: "\f060";  /* arrow-left */
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-forward::before {
   content: "\f061";  /* arrow-right */
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-bottom {
  position: absolute;
  right: 0;
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-bottom::before {
   content: "\f103";  /* angle-double-down */
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-right {
  position: absolute;
  right: 0;
}

.jp-InspectorItem .jp-NBToolbar-button.jp-InspectorItem-right::before {
   content: "\f101";  /* angle-double-right */
}

.jp-InspectorItem pre {
  font-size: 11px;
  margin: 0;
  padding: 2px;
  white-space: pre-wrap;
}

/* ansi_up creates classed spans for console foregrounds and backgrounds. */
.jp-InspectorItem pre .ansi-black-fg { color: #3A3A3A; }

.jp-InspectorItem pre .ansi-red-fg { color: #DD948E; }

.jp-InspectorItem pre .ansi-green-fg { color: #B6D1AA; }

.jp-InspectorItem pre .ansi-yellow-fg { color: #F3D57C; }

.jp-InspectorItem pre .ansi-blue-fg { color: #8AA9D5; }

.jp-InspectorItem pre .ansi-magenta-fg { color: #CBAFD5; }

.jp-InspectorItem pre .ansi-cyan-fg { color: #9AD1D4; }

.jp-InspectorItem pre .ansi-white-fg { color: #EFEFEF; }

.jp-InspectorItem pre .ansi-bright-black-fg { color: #5E5D5E; }

.jp-InspectorItem pre .ansi-bright-red-fg { color: #E69B94; }

.jp-InspectorItem pre .ansi-bright-green-fg { color: #D1F0C3; }

.jp-InspectorItem pre .ansi-bright-yellow-fg { color: #F4D799; }

.jp-InspectorItem pre .ansi-bright-blue-fg { color: #A6CBFE; }

.jp-InspectorItem pre .ansi-bright-magenta-fg { color: #E8C8F3; }

.jp-InspectorItem pre .ansi-bright-cyan-fg { color: #B1F1F6; }

.jp-InspectorItem pre .ansi-bright-white-fg { color: #FFFFFF; }

.jp-InspectorItem pre .ansi-black-bg { background-color: #3B3B3B; }

.jp-InspectorItem pre .ansi-red-bg { background-color: #DE958F; }

.jp-InspectorItem pre .ansi-green-bg { background-color: #B7D2AB; }

.jp-InspectorItem pre .ansi-yellow-bg { background-color: #F4D67D; }

.jp-InspectorItem pre .ansi-blue-bg { background-color: #8BAAD6; }

.jp-InspectorItem pre .ansi-magenta-bg { background-color: #CCB0D6; }

.jp-InspectorItem pre .ansi-cyan-bg { background-color: #9BD2D5; }

.jp-InspectorItem pre .ansi-white-bg { background-color: #F0F0F0; }

.jp-InspectorItem pre .ansi-bright-black-bg { background-color: #5F5E5F; }

.jp-InspectorItem pre .ansi-bright-red-bg { background-color: #E79C95; }

.jp-InspectorItem pre .ansi-bright-green-bg { background-color: #D2F1C4; }

.jp-InspectorItem pre .ansi-bright-yellow-bg { background-color: #F5D89A; }

.jp-InspectorItem pre .ansi-bright-blue-bg { background-color: #A7CCFF; }

.jp-InspectorItem pre .ansi-bright-magenta-bg { background-color: #E8C8F3; }

.jp-InspectorItem pre .ansi-bright-cyan-bg { background-color: #B1F1F6; }

.jp-InspectorItem pre .ansi-bright-white-bg { background-color: #FFFFFF; }

/* default inspector items: hints */
.jp-InspectorItem.jp-HintsInspectorItem,
.jp-InspectorItem.jp-HintsInspectorItem .p-Widget {
  background: #FFFFCA;
}

/* default inspector items: details */
.jp-InspectorItem.jp-DetailsInspectorItem .p-Widget {
  background: #FFFFFF;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="file://$PROJECT_DIR$/spec/install" libraries="{protractor/spec/install/node_modules}" />
  </component>
</project>


text:
int encrypt_aes(char* infile, char* outfile, char* enckey) {
	return aes_enc(infile, outfile, enckey);
}
int decrypt_aes(char* infile, char* outfile, char* deckey) {
	return aes_dec(infile, outfile, deckey);
}


text:
#ifndef _MArrayDataHandle
#define _MArrayDataHandle
//-
// ==========================================================================
// Copyright (C) 1995 - 2006 Autodesk, Inc., and/or its licensors.  All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Autodesk, Inc. ("Autodesk") and/or its
// licensors,  which is protected by U.S. and Canadian federal copyright law
// and by international treaties.
//
// The Data may not be disclosed or distributed to third parties or be
// copied or duplicated, in whole or in part, without the prior written
// consent of Autodesk.
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the following
// disclaimer, must be included in all copies of the Software, in whole
// or in part, and all derivative works of the Software, unless such copies
// or derivative works are solely in the form of machine-executable object
// code generated by a source language processor.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
// AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
// WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
// NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE,
// OR ARISING FROM A COURSE OF DEALING, USAGE, OR TRADE PRACTICE. IN NO
// EVENT WILL AUTODESK AND/OR ITS LICENSORS BE LIABLE FOR ANY LOST
// REVENUES, DATA, OR PROFITS, OR SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK AND/OR ITS LICENSORS HAS
// BEEN ADVISED OF THE POSSIBILITY OR PROBABILITY OF SUCH DAMAGES.
// ==========================================================================
//+
//
// CLASS:    MArrayDataHandle
//
// ****************************************************************************

#if defined __cplusplus

// ****************************************************************************
// INCLUDED HEADER FILES

class MArrayDataBuilder;
class MDataHandle;

#include <maya/MStatus.h>
#include <maya/MTypes.h>
#include <string.h>

// ****************************************************************************
// CLASS DECLARATION (MArrayDataHandle)

//! \ingroup OpenMaya
//! \brief Data block handle for array data.
/*!
  An MArrayDataHandle is a smart pointer into a data block (MDataBlock) that
  handles access to array data.  MArrayDataHandle supports attributes that
  can have an array of data.

  The array indices do not have to be continuous.  The array can be
  sparse.  Thus, an array could have four elements with the indicies
  1, 6, 8, and 10.

  MArrayDataHandle methods cannot be assumed to be threadsafe. The
  jumpToElement() method sets an internal pointer so definitely cannot
  be called by multiple threads simultaneously.

*/
class OPENMAYA_EXPORT MArrayDataHandle {

public:
	MArrayDataHandle( const MDataHandle & in, MStatus * ReturnStatus = NULL );

	MDataHandle       inputValue(MStatus *ReturnStatus = NULL);
	MDataHandle       outputValue(MStatus *ReturnStatus = NULL);
	MArrayDataHandle  inputArrayValue( MStatus * ReturnStatus = NULL );
	MArrayDataHandle  outputArrayValue( MStatus * ReturnStatus = NULL );
    MStatus           next();
	unsigned int          elementCount(MStatus *ReturnStatus = NULL);
	unsigned int          elementIndex(MStatus *ReturnStatus = NULL);
    MStatus           jumpToElement( unsigned int index );
    MStatus           jumpToArrayElement( unsigned int position );
    MStatus           setClean();
    MStatus           setAllClean();
	MArrayDataBuilder builder(MStatus *ReturnStatus = NULL);
	MStatus           set( MArrayDataBuilder &builder );

    MArrayDataHandle( const MArrayDataHandle &other );
	MArrayDataHandle& operator=( const MArrayDataHandle& other );

	static	const char*	className();

protected:
// No protected members

private:
	friend class MDataBlock;
	friend class MArrayDataBuilder;
	MArrayDataHandle( void* );
	MArrayDataHandle();
#ifdef MBits64_
	char data[40];
#else
	char data[20];
#endif
	bool fIsNull;
};

inline MArrayDataHandle::MArrayDataHandle( const MArrayDataHandle &other )
{
	memcpy( this, &other, sizeof(MArrayDataHandle) );
}

inline MArrayDataHandle& MArrayDataHandle::operator=(
											const MArrayDataHandle &other )
{
	memcpy( this, &other, sizeof(MArrayDataHandle) );
	return *this;
}

#endif /* __cplusplus */
#endif /* _MArrayDataHandle */


text:
package errors

import (
	"fmt"
	"reflect"
	"time"
)

type Nature string

const (
	Structural     Nature = "Invalid structure"        // Requests, parameters or inputs are wrong. Retry won't work.
	NotFound       Nature = "Unable to find entity"    // Failed to lookup something, somewhere
	Behavioural    Nature = "Wrong behavior or result" // No error but the result isn't the one expected
	Operational    Nature = "Invalid operation"        // An operation failed due to external causes, a retry could work
	Implementation Nature = "Illegal call"             // Method not implemented or unsupported for the given structure
)

// Failure states for fault that occurs during a process.
type Failure struct {
	Nature    Nature    // Kind of error, used a comparator
	Timestamp time.Time // The moment the error was created
	Fault     error     // The source of the failure
}

// NewFailure creates a new Failure from a source error
func New(nat Nature, src interface{}) Failure {
	var fault error
	switch src.(type) {
	case string:
		fault = fmt.Errorf("%s", src.(string))
	case error:
		fault = src.(error)
	default:
		panic("Unexpected error source")
	}

	failure := Failure{
		Nature:    nat,
		Timestamp: time.Now(),
		Fault:     fault,
	}

	// Pop one level if we made a failure from a failure
	t := reflect.TypeOf(src)
	tf := reflect.TypeOf(failure)
	if t == tf {
		failure.Fault = src.(Failure).Fault
	}

	return failure
}

// Error implements the error built-in interface
func (err Failure) Error() string {
	if err.Fault == nil {
		return fmt.Sprintf("%s", err.Nature)
	}
	return fmt.Sprintf("%s: %s", err.Nature, err.Fault.Error())
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.tailf.navu Class Hierarchy (CONF API Version 5.4)</title>
<meta name="date" content="2015-03-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.tailf.navu

Package Hierarchies:

All Packages

Class Hierarchy

Object

AbstractMap<K,V> (implements Map<K,V>)

HashMap<K,V> (implements Cloneable, Map<K,V>, Serializable)

LinkedHashMap<K,V> (implements Map<K,V>)

com.tailf.navu.NavuLinkedHashMap<K,V>

com.tailf.navu.AbstractNavuNode (implements com.tailf.navu.NavuNode)

com.tailf.navu.NavuContainer (implements com.tailf.maapi.MaapiDiffIterate, com.tailf.navu.NavuNode)

com.tailf.navu.NavuListEntry

com.tailf.navu.NavuLeaf (implements com.tailf.navu.NavuNode)

com.tailf.navu.NavuList (implements Iterable<T>, com.tailf.navu.NavuNode)

com.tailf.navu.IterationEntry

com.tailf.navu.KeyPath2NavuNode

com.tailf.navu.NavuAction (implements com.tailf.navu.NavuNode)

com.tailf.navu.NavuCdbSubscribers (implements com.tailf.navu.NavuCdbSubscriber)

com.tailf.navu.NavuCdbConfigSubscriber (implements com.tailf.navu.NavuCdbSubscriber, Runnable)

com.tailf.navu.NavuCdbTwoPhaseSubscriber (implements com.tailf.navu.NavuCdbSubscriber, Runnable)

com.tailf.navu.NavuCdbOperSubscriber (implements com.tailf.navu.NavuCdbSubscriber, Runnable)

com.tailf.navu.NavuCdbSubscriptionIterQueue

com.tailf.navu.NavuChange

com.tailf.navu.NavuChoice

com.tailf.navu.NavuContext

com.tailf.navu.NavuListContext (implements Iterable<T>)

com.tailf.navu.NavuNodeInfo

com.tailf.navu.NavuXPathContext

com.tailf.navu.PreparedXMLStatement (implements Serializable)

com.tailf.navu.SessionContainer

Throwable (implements Serializable)

Exception

com.tailf.conf.ConfException

com.tailf.navu.NavuException

com.tailf.navu.NoSuchNavuCaseException

com.tailf.navu.NoSuchNavuChoiceException

com.tailf.navu.NoSuchNavuNodeException

Interface Hierarchy

com.tailf.navu.NavuCdbDiffIterate

com.tailf.navu.NavuCdbConfigDiffIterate

com.tailf.navu.NavuCdbConfigDiffIterateExtended

com.tailf.navu.NavuCdbTwoPhaseDiffIterate

com.tailf.navu.NavuCdbOperDiffIterate

com.tailf.navu.NavuCdbOperDiffIterateExtended

com.tailf.navu.NavuCdbSessionPoolable

com.tailf.navu.NavuCdbStoppedHandler

com.tailf.navu.NavuCdbSubscriber

com.tailf.navu.NavuCdbSubscriptionContext

com.tailf.navu.NavuCdbSubscriptionConfigContext

com.tailf.navu.NavuCdbSubscriptionTwoPhaseContext

com.tailf.navu.NavuCdbSubscriptionOperContext

com.tailf.navu.NavuNode

com.tailf.navu.NavuNodeSetIterate

Enum Hierarchy

Object

Enum<E> (implements Comparable<T>, Serializable)

com.tailf.navu.NavuContext.UnSetCaseInChoice

com.tailf.navu.NavuList.WhereTo

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.linecorp.armeria.client.cookie;

import static java.util.Objects.requireNonNull;

import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;

import com.linecorp.armeria.common.Cookie;
import com.linecorp.armeria.common.CookieBuilder;
import com.linecorp.armeria.common.Cookies;
import com.linecorp.armeria.common.Scheme;
import com.linecorp.armeria.common.SessionProtocol;

import io.netty.util.NetUtil;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;

/**
 * A default in-memory {@link CookieJar} implementation.
 */
final class DefaultCookieJar implements CookieJar {

    private final Object2LongOpenHashMap<Cookie> store;
    /**
     * Used to find cookies for a host that matches a domain. For example, if there is a domain example.com,
     * host example.com or foo.example.com will match all cookies in that entry.
     */
    private final Map<String, Set<Cookie>> filter;
    private final CookiePolicy cookiePolicy;
    private final ReentrantLock lock;

    DefaultCookieJar() {
        this(CookiePolicy.acceptOriginOnly());
    }

    DefaultCookieJar(CookiePolicy cookiePolicy) {
        this.cookiePolicy = cookiePolicy;
        store = new Object2LongOpenHashMap<>();
        filter = new HashMap<>();
        lock = new ReentrantLock();
    }

    @Override
    public Cookies get(URI uri) {
        requireNonNull(uri, "uri");
        if (store.isEmpty()) {
            return Cookies.of();
        }
        final String host = uri.getHost();
        final String path = uri.getPath().isEmpty() ? "/" : uri.getPath();
        final boolean secure = isSecure(uri.getScheme());
        final Set<Cookie> cookies = new HashSet<>();
        lock.lock();
        try {
            filterGet(cookies, host, path, secure);
        } finally {
            lock.unlock();
        }
        return Cookies.of(cookies);
    }

    @Override
    public void set(URI uri, Iterable<? extends Cookie> cookies, long createdTimeMillis) {
        requireNonNull(uri, "uri");
        requireNonNull(cookies, "cookies");
        lock.lock();
        try {
            for (Cookie cookie : cookies) {
                cookie = ensureDomainAndPath(cookie, uri);
                // remove similar cookie if present
                store.removeLong(cookie);
                if ((cookie.maxAge() == Cookie.UNDEFINED_MAX_AGE || cookie.maxAge() > 0) &&
                    cookiePolicy.accept(uri, cookie)) {
                    store.put(cookie, createdTimeMillis);
                    final Set<Cookie> cookieSet = filter.computeIfAbsent(cookie.domain(), s -> new HashSet<>());
                    // remove similar cookie if present
                    cookieSet.remove(cookie);
                    cookieSet.add(cookie);
                }
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public CookieState state(Cookie cookie, long currentTimeMillis) {
        requireNonNull(cookie, "cookie");
        lock.lock();
        final long createdTimeMillis = store.getOrDefault(cookie, Long.MIN_VALUE);
        lock.unlock();
        if (createdTimeMillis == Long.MIN_VALUE) {
            return CookieState.NON_EXISTENT;
        }
        return isExpired(cookie, createdTimeMillis, currentTimeMillis) ?
               CookieState.EXPIRED : CookieState.EXISTENT;
    }

    /**
     * Ensures this cookie has domain and path attributes, otherwise sets them to default values. If domain
     * is absent, the default is the request host, with {@code host-only} flag set to {@code true}. If path is
     * absent, the default is computed from the request path. See RFC 6265
     * 5.3 and
     * 5.1.4
     */
    @VisibleForTesting
    Cookie ensureDomainAndPath(Cookie cookie, URI uri) {
        final boolean validDomain = !Strings.isNullOrEmpty(cookie.domain());
        final String cookiePath = cookie.path();
        final boolean validPath = !Strings.isNullOrEmpty(cookiePath) && cookiePath.charAt(0) == '/';
        if (validDomain && validPath) {
            return cookie;
        }
        final CookieBuilder cb = cookie.toBuilder();
        if (!validDomain) {
            cb.domain(uri.getHost()).hostOnly(true);
        }
        if (!validPath) {
            String path = uri.getPath();
            if (path.isEmpty()) {
                path = "/";
            } else {
                final int i = path.lastIndexOf('/');
                if (i > 0) {
                    path = path.substring(0, i);
                }
            }
            cb.path(path);
        }
        return cb.build();
    }

    private void filterGet(Set<Cookie> cookies, String host, String path, boolean secure) {
        final long currentTimeMillis = System.currentTimeMillis();
        for (Map.Entry<String, Set<Cookie>> entry : filter.entrySet()) {
            if (domainMatches(entry.getKey(), host)) {
                final Iterator<Cookie> it = entry.getValue().iterator();
                while (it.hasNext()) {
                    final Cookie cookie = it.next();
                    final long createdTimeMillis = store.getOrDefault(cookie, Long.MIN_VALUE);
                    if (createdTimeMillis == Long.MIN_VALUE) {
                        // the cookie has been removed from the main store so remove it from filter also
                        it.remove();
                        break;
                    }
                    if (isExpired(cookie, createdTimeMillis, currentTimeMillis)) {
                        it.remove();
                        store.removeLong(cookie);
                        break;
                    }
                    if (cookieMatches(cookie, host, path, secure)) {
                        cookies.add(cookie);
                    }
                }
            }
        }
    }

    private static boolean isSecure(String scheme) {
        final SessionProtocol parsedProtocol;
        if (scheme.indexOf('+') >= 0) {
            final Scheme parsedScheme = Scheme.tryParse(scheme);
            parsedProtocol = parsedScheme != null ? parsedScheme.sessionProtocol() : null;
        } else {
            parsedProtocol = SessionProtocol.find(scheme);
        }
        return parsedProtocol != null && parsedProtocol.isTls();
    }

    private static boolean isExpired(Cookie cookie, long createdTimeMillis, long currentTimeMillis) {
        final long timePassed = currentTimeMillis - createdTimeMillis;
        return cookie.maxAge() != Cookie.UNDEFINED_MAX_AGE && timePassed > cookie.maxAge() * 1000;
    }

    private static boolean domainMatches(String domain, String host) {
        if (domain.equalsIgnoreCase(host)) {
            return true;
        }
        return host.endsWith(domain) && host.charAt(host.length() - domain.length() - 1) == '.' &&
               !NetUtil.isValidIpV4Address(host) && !NetUtil.isValidIpV6Address(host);
    }

    private static boolean cookieMatches(Cookie cookie, String host, String path, boolean secure) {
        // if a cookie is host-only, host and domain have to be identical
        final boolean satisfiedHostOnly = !cookie.isHostOnly() || host.equalsIgnoreCase(cookie.domain());
        final boolean satisfiedSecure = secure || !cookie.isSecure();
        final String cookiePath = cookie.path();
        assert cookiePath != null;
        final boolean pathMatched = path.startsWith(cookiePath);
        return satisfiedHostOnly && satisfiedSecure && pathMatched;
    }
}


text:
#ifndef _ALTERA_HPS_0_H_
#define _ALTERA_HPS_0_H_

/*
 * This file was automatically generated by the swinfo2header utility.
 *
 * Created from SOPC Builder system 'lab3' in
 * file './lab3.sopcinfo'.
 */

/*
 * This file contains macros for module 'hps_0' and devices
 * connected to the following masters:
 *   h2f_axi_master
 *   h2f_lw_axi_master
 *
 * Do not include this header file and another header file created for a
 * different module or master group at the same time.
 * Doing so may result in duplicate macro names.
 * Instead, use the system header file which has macros with unique names.
 */

/*
 * Macros for device 'ik_driver_0', class 'ik_driver'
 * The macros are prefixed with 'IK_DRIVER_0_'.
 * The prefix is the slave descriptor.
 */
#define IK_DRIVER_0_COMPONENT_TYPE ik_driver
#define IK_DRIVER_0_COMPONENT_NAME ik_driver_0
#define IK_DRIVER_0_BASE 0x0
#define IK_DRIVER_0_SPAN 8
#define IK_DRIVER_0_END 0x7

#endif /* _ALTERA_HPS_0_H_ */