text:
layout: post
title: Hello World!
---

Yes, I know, that wasn't very creative. But we are developers and I think you started coding with a simple "Hello World!" program in C, PHP, JAVA or another language. And, as this is my first post, I will name it like my first program too.

<!--more-->

Now, some things about me. My name is Óscar Vicente Pérez and I'm from Spain. I started my journey in development three years ago with a Hello World! written in Java. Since that, I end my studies and worked half and a year with C# and .Net, Java, Php, and other languages and tecnologies.

I difference between coding and develop. I define coding as write code, lines of code. And define develop as all the other things such design, think, maintain a project/program.

## What am I talk about in this blog?

Well, that's easy, about coding and develop.

More deeply, I will post about two main things and extras:

### Development

> Which includes design patters and other things such Object-Oriented-Programming, good practices, etc...

When I talk about this things I meant every thing about development whose main objective is not coding. These will be the **long** ones and, of course, they will got code. They can explain the strategy pattern, introduce de IoC or talk about wrappers.

### Smart code

> Classes, tricks, smart algorithms, code. Things that you can reuse.

**Short/medium** posts explaining some smart answer to a problem. Like a double indexed map, how to implement a simple cache or a simple API to do something.

### Extras

Of course, the blog will have many post about curiosities, tips about everything or just things I found interesting. Sometimes can be as simply as some games to learn coding, a project on a raspberry, etc...


text:
namespace GridDomain.Tests.Unit.EventsUpgrade.Events
{
    public class TestType {}
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "9. Treffen am 11. Juli 2018"
published: true
tags:
 - treffen
priority: 0.8
---
Hallo Pythonistas!

Die Python User Group lädt herzlich zum 9. Dresdner Meetup rund um die Programmiersprache Python ein.

Diesmal erarbeiten wir gemeinsam, wie man in Python nicht behandelte Exceptions über das einfache Loggen nach stderr hinaus im Auge behalten kann. Außerdem reden wir darüber, wie aufgetretene Exceptions gesammelt und automatisch verarbeitet werden können.

    >>> {
    ... 'Wann': '11. Juli 2018 um 19:00',
    ... 'Wo': 'ZENTRALWERK; im HQ des Chaos Computer Club Dresden',
    ... 'Adresse': 'Riesaer Straße 32, 01127 Dresden',
    ... 'Thema': '9. PyDresden Treffen'
    ... }

Willkommen sind alle selbstdenkenden Wesen und Schlangen.


text:
"""
Herald Core directory

:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.5
:status: Alpha

..

    Copyright 2014 isandlaTech

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

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

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

# Module version
import pelix.ipopo.decorators

__version_info__ = (0, 0, 5)
__version__ = ".".join(str(x) for x in __version_info__)

# Documentation strings format
__docformat__ = "restructuredtext en"

# ------------------------------------------------------------------------------

# Herald
import herald
import herald.beans as beans

# Pelix
from pelix.ipopo.decorators import ComponentFactory, Requires, RequiresMap, \
    Provides, BindField, UnbindField, Validate, Invalidate, Instantiate
from pelix.utilities import is_string
import pelix.constants

# Standard library
import logging
import threading

# ------------------------------------------------------------------------------

_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------

@ComponentFactory("herald-directory-factory")
@Provides(herald.SERVICE_DIRECTORY)
@RequiresMap('_directories', herald.SERVICE_TRANSPORT_DIRECTORY,
             herald.PROP_ACCESS_ID, False, False, True)
@Requires('_listeners', herald.SERVICE_DIRECTORY_LISTENER, True, True)
@Requires('_group_listeners', herald.SERVICE_DIRECTORY_GROUP_LISTENER,
          True, True)
@Instantiate("herald-directory")
class HeraldDirectory(object):
    """
    Core Directory for Herald
    """
    def __init__(self):
        """
        Sets up the transport
        """
        # Transport-specific directories
        self._directories = {}

        # Directory listeners
        self._listeners = []

        # Directory group listeners
        self._group_listeners = []

        # Local bean description
        self._local = None

        # UID -> Peer bean
        self._peers = {}

        # Name -> Set of Peer UIDs
        self._names = {}

        # Group name -> Set of Peers
        self._groups = {}

        # Thread safety
        self.__lock = threading.Lock()

    def __contains__(self, peer):
        """
        Adds support for the "in" keyword: checks if the given peer is
        registered in this directory

        :param peer: A peer UID or object
        :return: True if the peer is known
        """
        return peer in self._peers or peer in self._peers.values()

    def __make_local_peer(self, context):
        """
        Prepares a Peer bean with local configuration

        :param context: Bundle context
        """
        # Get local peer UID, node UID and application ID
        peer_uid = context.get_property(herald.FWPROP_PEER_UID) \
            or context.get_property(pelix.constants.FRAMEWORK_UID)
        node_uid = context.get_property(herald.FWPROP_NODE_UID)
        app_id = context.get_property(herald.FWPROP_APPLICATION_ID) \
            or herald.DEFAULT_APPLICATION_ID

        # Find configured groups
        groups = context.get_property(herald.FWPROP_PEER_GROUPS)
        if not groups:
            groups = []
        elif is_string(groups):
            groups = (group.strip() for group in groups.split(',')
                      if group.strip)
        groups = set(groups)

        # Add pre-configured group: node UID
        if node_uid:
            groups.add(node_uid)

        # Make the Peer bean
        peer = beans.Peer(peer_uid, node_uid, app_id, groups, self)

        # Setup node and name information
        peer.name = context.get_property(herald.FWPROP_PEER_NAME)
        peer.node_name = context.get_property(herald.FWPROP_NODE_NAME)
        return peer

    @Validate
    def _validate(self, context):
        """
        Component validated
        """
        # Clean up remaining data (if any)
        self._peers.clear()
        self._names.clear()
        self._groups.clear()

        # Prepare local peer
        self._local = self.__make_local_peer(context)
        for group in self._local.groups:
            # Create (empty) groups
            self._groups[group] = set()

    @Invalidate
    def _invalidate(self, _):
        """
        Component invalidated
        """
        # Clean all up
        self._peers.clear()
        self._names.clear()
        self._groups.clear()
        self._local = None

    @BindField('_directories')
    def _bind_directory(self, _, svc, svc_ref):
        """
        A transport directory has been bound
        """
        access_id = svc_ref.get_property(herald.PROP_ACCESS_ID)
        if not access_id:
            return

        with self.__lock:
            for peer in self._peers.values():
                try:
                    access = peer.get_access(access_id)
                except KeyError:
                    # No access of this kind
                    pass
                else:
                    if isinstance(access, beans.RawAccess):
                        # We need to convert a raw access bean
                        parsed = svc.load_access(access.dump())
                        peer.set_access(access_id, parsed)

    @UnbindField('_directories')
    def _unbind_directory(self, _, svc, svc_ref):
        """
        A transport directory has gone away
        """
        access_id = svc_ref.get_property(herald.PROP_ACCESS_ID)
        if not access_id:
            return

        with self.__lock:
            for peer in self._peers.values():
                try:
                    # Get the current access information
                    access = peer.get_access(access_id)
                except KeyError:
                    # No access of this kind
                    pass
                else:
                    # Convert to a RawAccess bean
                    peer.set_access(access_id,
                                    beans.RawAccess(access_id, access.dump()))

    @BindField('_listeners', if_valid=True)
    def _bind_listener(self, _, svc, svc_ref):
        """
        A directory listener has been bound
        """
        for peer in list(self._peers.values()):
            svc.peer_registered(peer)

    @BindField('_group_listeners', if_valid=True)
    def _bind_group_listener(self, _, svc, svc_ref):
        """
        A directory group listener has been bound
        """
        for group in self._groups:
            svc.group_set(group)

    def __notify_group_set(self, group):
        """
        Notify listeners about a new group of peers

        :param group: Name of the group
        """
        if self._group_listeners:
            for listener in self._group_listeners[:]:
                try:
                    # pylint: disable=W0703
                    listener.group_set(group)
                except Exception as ex:
                    _logger.exception("Error notifying listener: %s", ex)

    def __notify_group_unset(self, group):
        """
        Notify listeners about the removal of a group

        :param group: Name of the group
        """
        if self._group_listeners:
            for listener in self._group_listeners[:]:
                try:
                    # pylint: disable=W0703
                    listener.group_unset(group)
                except Exception as ex:
                    _logger.exception("Error notifying listener: %s", ex)

    def __notify_peer_registered(self, peer):
        """
        Notify listeners about a new peer

        :param peer: Bean of the new peer
        """
        if self._listeners:
            for listener in self._listeners[:]:
                try:
                    # pylint: disable=W0703
                    listener.peer_registered(peer)
                except Exception as ex:
                    _logger.exception("Error notifying listener: %s", ex)

    def __notify_peer_unregistered(self, peer):
        """
        Notify listeners about the loss of peer

        :param peer: Bean of the loss of peer
        """
        if self._listeners:
            for listener in self._listeners[:]:
                try:
                    # pylint: disable=W0703
                    listener.peer_unregistered(peer)
                except Exception as ex:
                    _logger.exception("Error notifying listener: %s", ex)

    def __notify_peer_updated(self, peer, access_id, data, previous=None):
        """
        Notifies listeners about the modification of a peer access

        :param peer: Bean of the modified peer
        :param access_id: ID of the modified access
        :param data: New access data (None of unset)
        :param previous: Previous access data (None for set)
        """
        if self._listeners:
            for listener in self._listeners[:]:
                try:
                    # pylint: disable=W0703
                    listener.peer_updated(peer, access_id, data, previous)
                except Exception as ex:
                    _logger.exception("Error notifying listener: %s", ex)

    @property
    def local_uid(self):
        """
        Returns the local peer UID
        """
        return self._local.uid

    def get_peer(self, uid):
        """
        Retrieves the peer with the given UID

        :param uid: The UID of a peer
        :return: A Peer bean
        :raise KeyError: Unknown peer
        """
        return self._peers[uid]

    def get_local_peer(self):
        """
        Returns the description of the local peer

        :return: The description of the local peer
        """
        return self._local

    def get_peers(self):
        """
        Returns the list of all known peers

        :return: A tuple containing all known peers
        """
        return tuple(self._peers.values())

    def get_uids_for_name(self, name):
        """
        Returns the UIDs of the peers having the given name

        :param name: The name used by some peers
        :return: A set of UIDs
        :raise KeyError: No peer has this name
        """
        try:
            return self._names[name].copy()
        except KeyError:
            return [self._peers[name].uid]

    def get_peers_for_name(self, name):
        """
        Returns the Peer beans of the peers having the given name

        :param name: The name used by some peers
        :return: A list of Peer beans
        :raise KeyError: No peer has this name
        """
        try:
            return [self._peers[uid] for uid in self._names[name]]
        except KeyError:
            return [self._peers[name]]

    def get_peers_for_group(self, group):
        """
        Returns the Peer beans of the peers belonging to the given group

        :param group: The name of a group
        :return: A list of Peer beans
        :raise KeyError: Unknown group
        """
        if group == 'all':
            # Special group: retrieve all peers
            return list(self._peers.values())

        return self._groups[group].copy()

    def get_peers_for_node(self, node_uid):
        """
        Returns the Peer beans of the peers associated to the given node UID

        :param node_uid: The UID of a node
        :return: A list of Peer beans
        """
        return [peer for peer in self._peers.values()
                if peer.node_uid == node_uid]

    def peer_access_set(self, peer, access_id, data):
        """
        A new peer access is available. Called by a Peer bean.

        :param peer: The modified Peer bean
        :param access_id: ID of the access
        :param data: Information of the peer access
        """
        try:
            # Get the handling directory
            directory = self._directories[access_id]
        except KeyError:
            # No handler for this directory
            pass
        else:
            try:
                # Notify it
                directory.peer_access_set(peer, data)
            except Exception as ex:
                _logger.exception("Error notifying a transport directory: %s",
                                  ex)

            # Notify listeners only if the peer is already/still registered
            if peer.uid in self._peers:
                # Notify directory listeners
                self.__notify_peer_updated(peer, access_id, data)

    def peer_access_unset(self, peer, access_id, data):
        """
        A peer access has been removed. Called by  a Peer bean.

        :param peer: The modified Peer bean
        :param access_id: ID of the removed access
        :param data: Previous information of the peer access
        """
        try:
            # Get the handling directory
            directory = self._directories[access_id]
        except KeyError:
            # No handler for this directory
            pass
        else:
            try:
                # Notify it
                directory.peer_access_unset(peer, data)
            except Exception as ex:
                _logger.exception("Error notifying a transport directory: %s",
                                  ex)

            # Notify directory listeners
            self.__notify_peer_updated(peer, access_id, None, data)

        if not peer.has_accesses():
            # Peer has no more access, unregister it
            self.unregister(peer.uid)

    def dump(self):
        """
        Dumps the content of the local directory in a dictionary

        :return: A UID -> description dictionary
        """
        return {peer.uid: peer.dump() for peer in self._peers.values()}

    def load(self, dump):
        """
        Loads the content of a dump

        :param dump: The result of a call to dump()
        """
        for uid, description in dump.items():
            if uid not in self._peers:
                try:
                    # Do not reload already known peer
                    self.register(description)
                except ValueError as ex:
                    _logger.warning("Error loading peer dump: %s", ex)

    def register(self, description):
        """
        Registers a peer

        :param description: Description of the peer, in the format of dump()
        :return: The registered Peer bean
        :raise ValueError: Invalid peer UID
        """
        notification = self.register_delayed(description)
        notification.notify()
        return notification.peer

    def register_delayed(self, description):
        """
        Registers a peer

        :param description: Description of the peer, in the format of dump()
        :return: A DelayedNotification bean
        :raise ValueError: Invalid peer UID
        """
        with self.__lock:
            uid = description['uid']
            if uid == self._local.uid:
                # Ignore local peer
                return beans.DelayedNotification(None, None)

            try:
                app_id = description['app_id']
            except KeyError:
                app_id = herald.DEFAULT_APPLICATION_ID

            if app_id != self._local.app_id:
                # Ignore foreign peers
                _logger.debug("Refused registration of %s from application %s",
                              uid, app_id)
                return beans.DelayedNotification(None, None)

            try:
                # Check if the peer is known
                peer = self._peers[uid]
                peer_update = True
            except KeyError:
                # Make a new bean
                peer_update = False
                peer = beans.Peer(uid, description['node_uid'], app_id,
                                  description['groups'], self)

                # Setup writable properties
                for name in ('name', 'node_name'):
                    setattr(peer, name, description[name])

            # In any case, parse and store (new/updated) accesses
            for access_id, data in description['accesses'].items():
                try:
                    data = self._directories[access_id].load_access(data)
                except KeyError:
                    # Access not available for parsing: keep a RawAccess bean
                    data = beans.RawAccess(access_id, data)

                # Store the parsed data: listeners will be notified IF the peer
                # was already stored
                peer.set_access(access_id, data)

            if not peer_update:
                # Store the peer after accesses have been set
                # (avoids to notify about update before registration)
                self._peers[uid] = peer

                # Store the peer
                self._names.setdefault(peer.name, set()).add(peer.uid)

                # Set up groups
                new_groups = set()
                for group in peer.groups:
                    try:
                        # Get the group
                        peers = self._groups[group]
                    except KeyError:
                        # Group must be created: notify about it
                        peers = self._groups[group] = set()
                        new_groups.add(group)

                    peers.add(peer)

                # Notify about new groups
                for group in new_groups:
                    self.__notify_group_set(group)

                return beans.DelayedNotification(peer,
                                                 self.__notify_peer_registered)
            else:
                return beans.DelayedNotification(peer, None)

    def unregister(self, uid):
        """
        Unregisters a peer from the directory

        :param uid: UID of the peer
        :return: The Peer bean if it was known, else None
        """
        with self.__lock:
            try:
                # Pop the peer bean
                peer = self._peers.pop(uid)
            except KeyError:
                # Unknown peer
                return
            else:
                # Remove it from other dictionaries
                try:
                    uids = self._names[peer.name]
                    uids.remove(uid)
                    if not uids:
                        del self._names[peer.name]
                except KeyError:
                    # Name wasn't registered...
                    pass

                for group in peer.groups:
                    try:
                        peers = self._groups[group]
                        peers.remove(peer)
                        if not peers:
                            # Remove the group and notify listeners
                            del self._groups[group]
                            self.__notify_group_unset(group)

                    except KeyError:
                        # Peer wasn't in that group
                        pass

        # Notify listeners
        self.__notify_peer_unregistered(peer)
        return peer


text:
@interface PodsDummy_Pods_TNKData : NSObject
@end
@implementation PodsDummy_Pods_TNKData
@end


text:
<?php

declare(strict_types = 1);

namespace Go\Aop\Support;

use Go\Aop\PointFilter;

/**
 * ModifierMatcherFilter performs checks on modifiers for reflection point
 */
class ModifierMatcherFilter implements PointFilter
{
    /**
     * Bit mask, that should be always match
     */
    protected int $andMask = 0;

    /**
     * Bit mask, that can be used for additional check
     */
    protected int $orMask = 0;

    /**
     * Bit mask to exclude specific value from matching, for example, !public
     */
    protected int $notMask = 0;

    /**
     * Initialize default filter with "and" mask
     *
     * @param int $initialMask Default mask for "and"
     */
    public function __construct(int $initialMask = 0)
    {
        $this->andMask = $initialMask;
    }

    /**
     * Performs matching of point of code
     *
     * @param mixed $point Specific part of code, can be any Reflection class
     * @param null|mixed $context Related context, can be class or namespace
     * @param null|string|object $instance Invocation instance or string for static calls
     * @param null|array $arguments Dynamic arguments for method
     */
    public function matches($point, $context = null, $instance = null, array $arguments = null): bool
    {
        $modifiers = $point->getModifiers();

        return !($this->notMask & $modifiers) &&
            (($this->andMask === ($this->andMask & $modifiers)) || ($this->orMask & $modifiers));
    }

    /**
     * Add "and" mask
     */
    public function andMatch(int $bitMask): self
    {
        $this->andMask |= $bitMask;

        return $this;
    }

    /**
     * Add "or" mask
     */
    public function orMatch(int $bitMask): self
    {
        $this->orMask |= $bitMask;

        return $this;
    }

    /**
     * Add "not" mask
     */
    public function notMatch(int $bitMask): self
    {
        $this->notMask |= $bitMask;

        return $this;
    }

    /**
     * Returns the kind of point filter
     */
    public function getKind(): int
    {
        return self::KIND_ALL;
    }
}


text:
package moe.feng.bilinyan.ui.adapter.list;

import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

import moe.feng.bilinyan.R;
import moe.feng.bilinyan.model.VideoItemInfo;
import moe.feng.bilinyan.ui.common.AbsRecyclerViewAdapter;

public class VideoItemRecyclerAdapter extends AbsRecyclerViewAdapter {

	private List<VideoItemInfo> items;

	public VideoItemRecyclerAdapter(RecyclerView recyclerView, List<VideoItemInfo> items) {
		super(recyclerView);
		this.items = items;
	}

	@Override
	public ClickableViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		bindContext(parent.getContext());
		return new ItemViewHolder(
				LayoutInflater.from(getContext())
						.inflate(R.layout.list_item_video_item, parent, false)
		);
	}

	@Override
	public void onBindViewHolder(ClickableViewHolder cvh, int pos) {
		super.onBindViewHolder(cvh, pos);
		if (cvh instanceof ItemViewHolder) {
			ItemViewHolder holder = (ItemViewHolder) cvh;
			holder.mTitleText.setText(items.get(pos).title);
			holder.mUperNameText.setText(
					String.format(
							getContext().getString(R.string.item_info_uper_format),
							items.get(pos).author
					)
			);
			holder.mNumber0Text.setText(items.get(pos).play);
			holder.mNumber1Text.setText(Integer.toString(items.get(pos).video_review));

			Picasso.with(getContext()).load(items.get(pos).pic).into(holder.mPreviewImage);
		}
	}

	@Override
	public int getItemCount() {
		return items.size();
	}

	public class ItemViewHolder extends ClickableViewHolder {

		private ImageView mPreviewImage;
		private AppCompatTextView mTitleText, mNumber0Text, mNumber1Text, mUperNameText;
		private ImageView mNumber0Icon, mNumber1Icon;

		public ItemViewHolder(View itemView) {
			super(itemView);

			mPreviewImage = $(R.id.iv_preview);
			mTitleText = $(R.id.tv_title);
			mUperNameText = $(R.id.tv_uper);
			mNumber0Text = $(R.id.tv_number_0);
			mNumber1Text = $(R.id.tv_number_1);
			mNumber0Icon = $(R.id.icon_number_0);
			mNumber1Icon = $(R.id.icon_number_1);
		}

	}

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.06 at 03:51:15 PM EAT
//

package org.akomantoso.schema.v3.csd07;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD07}inlinereqreq">
 *       <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD07}role"/>
 *       <attribute name="for" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *       <attribute name="empoweredBy" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "lawyer")
public class Lawyer
    extends Inlinereqreq
{

    @XmlAttribute(name = "for")
    @XmlSchemaType(name = "anyURI")
    protected String _for;
    @XmlAttribute(name = "empoweredBy")
    @XmlSchemaType(name = "anyURI")
    protected String empoweredBy;
    @XmlAttribute(name = "as")
    @XmlSchemaType(name = "anyURI")
    protected String as;

    /**
     * Gets the value of the for property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFor() {
        return _for;
    }

    /**
     * Sets the value of the for property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFor(String value) {
        this._for = value;
    }

    /**
     * Gets the value of the empoweredBy property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getEmpoweredBy() {
        return empoweredBy;
    }

    /**
     * Sets the value of the empoweredBy property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEmpoweredBy(String value) {
        this.empoweredBy = value;
    }

    /**
     * Gets the value of the as property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAs() {
        return as;
    }

    /**
     * Sets the value of the as property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAs(String value) {
        this.as = value;
    }

}


text:
class Cpulimit < Formula
  desc "CPU usage limiter"
  homepage "https://github.com/opsengine/cpulimit"
  url "https://github.com/opsengine/cpulimit/archive/v0.1.tar.gz"
  sha256 "6e653150aae18dd72f7dd93d92ee5f200eb8fef89e6c0bed28a2e3233dc29f23"

  head "https://github.com/opsengine/cpulimit.git"

  def install
    system "make"
    bin.install "src/cpulimit"
  end

  test do
    system *%W[#{bin}/cpulimit -l 10 ls]
  end
end


text:
package com.tweeddale.tweeter.contentstrategy;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

/**
 * Stores a collection of ContentFetchStrategies with methods for addding/removing/selecting them
 * Created by James on 8/2/2015.
 */
public class StrategyCollection {
    private static final Logger logger = LogManager.getLogger(StrategyCollection.class);

    private Map<String, ContentFetchStrategy> strategyMap = new HashMap();

    public void addStrategy(String name, ContentFetchStrategy strategy){
        strategyMap.put(name, strategy);
    }

    public void removeStrategy(String name){
        strategyMap.remove(name);
    }

    public ContentFetchStrategy getStrategy(String name){
        return strategyMap.get(name);
    }

    /**
     * @return a randomly selected contentFetchStrategy from this collection
     */
    public ContentFetchStrategy getRandomStrategy(){

        Set <String> strategyNames = strategyMap.keySet();

        int numStrategies = strategyMap.size();
        int randomNum = 0;
        if(numStrategies > 0){
            Random rand = new Random();
            randomNum = rand.nextInt(numStrategies);
        }

        return strategyMap.get(strategyNames.toArray()[randomNum]);
    }

}


text:
@interface BNGInstructionReportTest : XCTestCase

@end

@implementation BNGInstructionReportTest

- (void)testStringFromBNGInstructionReportStatus
{
    XCTAssertTrue([[BNGInstructionReport stringFromBNGInstructionReportStatus:BNGInstructionReportStatusSuccess] isEqualToString:@"SUCCESS"], @"stringFromBNGInstructionReportStatus should return the appropriate string for BNGInstructionReportStatusSuccess");
    XCTAssertTrue([[BNGInstructionReport stringFromBNGInstructionReportStatus:BNGInstructionReportStatusFailure] isEqualToString:@"FAILURE"], @"stringFromBNGInstructionReportStatus should return the appropriate string for BNGInstructionReportStatusFailure");
    XCTAssertTrue([[BNGInstructionReport stringFromBNGInstructionReportStatus:BNGInstructionReportStatusTimeout] isEqualToString:@"TIMEOUT"], @"stringFromBNGInstructionReportStatus should return the appropriate string for BNGInstructionReportStatusTimeout");
}

- (void)testInstructionReportStatusFromString
{
    XCTAssertTrue([BNGInstructionReport instructionReportStatusFromString:@"FAILURE"] == BNGInstructionReportStatusFailure, @"instructionReportStatusFromString should return the appropriate value for FAILURE");
    XCTAssertTrue([BNGInstructionReport instructionReportStatusFromString:@"SUCCESS"] == BNGInstructionReportStatusSuccess, @"instructionReportStatusFromString should return the appropriate value for SUCCESS");
    XCTAssertTrue([BNGInstructionReport instructionReportStatusFromString:@"TIMEOUT"] == BNGInstructionReportStatusTimeout, @"instructionReportStatusFromString should return the appropriate value for TIMEOUT");
}

- (void)testInstructionReportErrorCodeFromString
{
    XCTAssertTrue([BNGInstructionReport instructionReportErrorCodeFromString:@"INVALID_BET_SIZE"] == BNGInstructionReportErrorCodeInvalidBetSize, @"instructionReportErrorCodeFromString should return the correct BNGInstructionReportErrorCode for INVALID_BET_SIZE");
    XCTAssertTrue([BNGInstructionReport instructionReportErrorCodeFromString:@"INVALID_RUNNER"] == BNGInstructionReportErrorCodeInvalidRunner, @"instructionReportErrorCodeFromString should return the correct BNGInstructionReportErrorCode for INVALID_RUNNER");
}

- (void)testStringFromInstructionReportErrorCode
{
    XCTAssertTrue([[BNGInstructionReport stringFromBNGInstructionReportErrorCode:BNGInstructionReportErrorCodeInvalidBetSize] isEqualToString:@"INVALID_BET_SIZE"], @"stringFromBNGInstructionReportErrorCode should return the correct String for BNGInstructionReportErrorCodeInvalidBetSize");
    XCTAssertTrue([[BNGInstructionReport stringFromBNGInstructionReportErrorCode:BNGInstructionReportErrorCodeInvalidRunner] isEqualToString:@"INVALID_RUNNER"], @"stringFromBNGInstructionReportErrorCode should return the correct String for BNGInstructionReportErrorCodeInvalidRunner");
}

@end


text:
import template from './add-widget-dialog.html';

const AddWidgetDialog = {
  template,
  bindings: {
    resolve: '<',
    close: '&',
    dismiss: '&',
  },
  controller($sce, toastr, Query, Widget) {
    'ngInject';

    this.dashboard = this.resolve.dashboard;
    this.saveInProgress = false;
    this.widgetSize = 1;
    this.selectedVis = null;
    this.query = {};
    this.selected_query = undefined;
    this.text = '';
    this.widgetSizes = [{
      name: 'Regular',
      value: 1,
    }, {
      name: 'Double',
      value: 2,
    }];

    this.type = 'visualization';

    this.trustAsHtml = html => $sce.trustAsHtml(html);
    this.isVisualization = () => this.type === 'visualization';
    this.isTextBox = () => this.type === 'textbox';

    this.setType = (type) => {
      this.type = type;
      if (type === 'textbox') {
        this.widgetSizes.push({ name: 'Hidden', value: 0 });
      } else if (this.widgetSizes.length > 2) {
        this.widgetSizes.pop();
      }
    };

    this.onQuerySelect = () => {
      if (!this.query.selected) {
        return;
      }

      Query.get({ id: this.query.selected.id }, (query) => {
        if (query) {
          this.selected_query = query;
          if (query.visualizations.length) {
            this.selectedVis = query.visualizations[0];
          }
        }
      });
    };

    this.searchQueries = (term) => {
      if (!term || term.length < 3) {
        return;
      }

      Query.search({ q: term }, (results) => {
        this.queries = results;
      });
    };

    this.saveWidget = () => {
      this.saveInProgress = true;
      const widget = new Widget({
        visualization_id: this.selectedVis && this.selectedVis.id,
        dashboard_id: this.dashboard.id,
        options: {},
        width: this.widgetSize,
        text: this.text,
      });

      widget.$save().then((response) => {
        // update dashboard layout
        this.dashboard.layout = response.layout;
        this.dashboard.version = response.version;
        const newWidget = new Widget(response.widget);
        if (response.new_row) {
          this.dashboard.widgets.push([newWidget]);
        } else {
          this.dashboard.widgets[this.dashboard.widgets.length - 1].push(newWidget);
        }
        this.close();
      }).catch(() => {
        toastr.error('Widget can not be added');
      }).finally(() => {
        this.saveInProgress = false;
      });
    };
  },
};

export default function (ngModule) {
  ngModule.component('addWidgetDialog', AddWidgetDialog);
}


text:
package nodeobservatory

import (
	"sync"

	"k8s.io/client-go/tools/cache"

	v1 "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
)

type Controller interface {
	Run(threadiness int, stopCh <-chan struct{}, wg *sync.WaitGroup)

	GetStoreForKluster(*v1.Kluster) cache.Store
	GetIndexerForKluster(*v1.Kluster) cache.Indexer
	HasSyncedForKluster(*v1.Kluster) bool
	List() map[*v1.Kluster]cache.SharedIndexInformer
	AddEventHandlerFuncs(AddFunc, UpdateFunc, DeleteFunc)
}


text:
from django.db import models

class Quote(models.Model):
    slug = models.SlugField(max_length=255, unique=True, help_text='A shortname for the quote.')
    author = models.CharField(blank=True, max_length=255, help_text='The quote\'s author')
    circa = models.CharField(blank=True, max_length=100, help_text="When was the quote created?")
    quote = models.TextField()

    class Meta:
        verbose_name_plural = 'Quotes'

    def __unicode__(self):
        return self.slug

    def save(self):
        super(Quote, self).save()


text:
package analytics

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

type simpleTestStruct struct {
	Name             string `json:"name"`
	Address          string `json:"address,omitempty"`
	Age              int    `json:"age"`
	Happy            bool   `json:"happy"`
	NotJSONField     string
	IgnoredJSONField string `json:"-"`
}

type complexTestStruct struct {
	Name            string          `json:"name"`
	Address         string          `json:"address,omitempty"`
	City            string          `json:"city"`
	Age             int             `json:"age"`
	Happy           bool            `json:"happy"`
	Cars            []string        `json:"cars"`
	ColorCollection map[string]bool `json:"color_collection"`
}

type emptyTestStruct struct {
}

func TestNewProperty(t *testing.T) {
	tests := []struct {
		name string
		item interface{}
		want Properties
	}{
		{
			name: "Simple Test",
			item: simpleTestStruct{
				Name:         "John",
				Age:          42,
				Happy:        true,
				NotJSONField: "Not a json field",
			},
			want: Properties{
				"name":         "John",
				"age":          42,
				"happy":        true,
				"NotJSONField": "Not a json field",
			},
		},
		{
			name: "Complex Test",
			item: complexTestStruct{
				Name:            "John",
				Age:             42,
				Happy:           true,
				Cars:            []string{"Ford", "Chevy"},
				ColorCollection: map[string]bool{"red": true, "blue": false},
			},
			want: Properties{
				"name":             "John",
				"city":             "",
				"age":              42,
				"happy":            true,
				"cars":             []string{"Ford", "Chevy"},
				"color_collection": map[string]bool{"red": true, "blue": false},
			},
		},
		{
			name: "Empty Test",
			item: emptyTestStruct{},
			want: Properties{},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.Equalf(t, tt.want, NewProperty(tt.item), "NewProperty(%v)", tt.item)
		})
	}
}


text:
// An example configuration file.
exports.config = {
  allScriptsTimeout: 99999,
  // Do not start a Selenium Standalone sever - only run this using chrome.
  chromeOnly: true,
  chromeDriver: './node_modules/protractor/selenium/chromedriver',

  seleniumArgs: ['-browserTimeout=60'],

  // Capabilities to be passed to the webdriver instance.
  capabilities: {
    'browserName': 'chrome'
  },

  // Spec patterns are relative to the current working directly when
  // protractor is called.
  specs: ['test/e2e/**/*.spec.js'],

  // Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
  }
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util
		http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/cache
    	http://www.springframework.org/schema/cache/spring-cache.xsd">
	<import resource="support-auth-demo-datasource.xml"/>
	<import resource="support-auth-demo-repository.xml"/>
	<import resource="support-auth-demo-service.xml"/>
</beans>


text:
package resetpassword

import (
	"encoding/json"
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/gotk/ctx"
	"github.com/gotk/pg"

	"github.com/vonwenm/go-spa/backend/account/user"
)

func init() {
	ctx.Resource("/account/reset-password/complete", &Complete{}, true)
}

type Complete struct{}

func (r *Complete) POST(c *ctx.Context, rw http.ResponseWriter, req *http.Request) error {
	db := c.Vars["db"].(*pg.Session)

	// decode request data
	var form struct {
		Password      string   `json:"password"`
		PasswordAgain string   `json:"passwordAgain"`
		ValidKey      ValidKey `json:"validKey"`
	}
	err := json.NewDecoder(req.Body).Decode(&form)
	if err != nil {
		return ctx.BadRequest(rw, c.T("reset.complete.unable_to_change"))
	}

	// validate the passwords
	if form.Password != form.PasswordAgain {
		return ctx.BadRequest(rw, c.T("reset.complete.mismatch"))
	}

	// validate the key again
	resetToken, err := getToken(db, form.ValidKey.Key)
	if err != nil || !resetToken.Valid() {
		return ctx.BadRequest(rw, c.T("reset.token.invalid_key"))
	}

	// get user from db
	u, err := user.GetById(db, resetToken.UserId)
	if err != nil {
		return ctx.InternalServerError(rw, c.T("reset.complete.user_not_found"))
	}

	// encode user password
	err = u.Password.Encode(form.Password)
	if err != nil {
		return ctx.InternalServerError(rw, c.T("reset.complete.could_not_change_password"))
	}

	// change user data in database
	err = user.Update(db, u)
	if err != nil {
		return ctx.InternalServerError(rw, c.T("reset.complete.could_not_change_password"))
	}

	// invalidate token
	err = updateToken(db, resetToken)
	if err != nil {
		log.Errorf("Unable to invalidate token: %s", err)
	}

	return ctx.OK(rw, u)
}


text:
var routes = []

routes.push({
  path: '/deputies',
  handler: 'getDeputies'
})

routes.push({
  path: '/deputies/:idDep',
  handler: ['loadDeputy', 'getDeputy']
})

routes.push({
  path: '/deputies/:idDep/interventions',
  handler: ['loadDeputy', 'getDeputyInterventions']
})

routes.push({
  path: '/deputies/:idDep/interventions/:idInt',
  handler: ['loadDeputy', 'getDeputyIntervention']
})

module.exports = routes


text:
package org.lockss.plugin.atypon.aiaa;

import java.io.InputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.tags.LinkTag;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.AuUtil;
import org.lockss.plugin.atypon.BaseAtyponHtmlLinkRewriterFactory;
import org.lockss.rewriter.*;
import org.lockss.servlet.ServletUtil.LinkTransform;
import org.lockss.util.Logger;

/**
 * This custom link rewriter performs AIAA specific rewriting
 * for the special link extractor that generates the showCitFormats
 * url.  The javascript is incorrectly rewritten for servecontent
 * so create the desired link before applying the ServeContent
 * transformation.
 *
 *
 */
public class AIAAHtmlLinkRewriterFactory implements LinkRewriterFactory {

  private static final Logger log =
    Logger.getLogger(AIAAHtmlLinkRewriterFactory.class);

  /**
   * This link rewriter adds special processing to replace the showCit
   * javascript method with the link we would normally extract from it
   *
   */
  @Override
  public InputStream createLinkRewriter(String mimeType,
                                        ArchivalUnit au,
                                        InputStream in,
                                        String encoding,
                                        String url,
                                        LinkTransform xfm)
      throws PluginException, IOException {

//    NodeFilterHtmlLinkRewriterFactory fact =
//      new NodeFilterHtmlLinkRewriterFactory();

//    fact.addPreXform(new AIAAPreFilter(au,url));
//    return fact.createLinkRewriter(mimeType, au, in, encoding, url, xfm);
    return BaseAtyponHtmlLinkRewriterFactory.createLinkRewriter(mimeType, au, in, encoding, url, xfm, new AIAAPreFilter(au,url), null);

  }

  static class AIAAPreFilter implements NodeFilter {
    //<a
    // href="javascript:submitArticles(document.frmAbs, '/action/showCitFormats'
    // becomes
    // href =
    protected Pattern SUBMIT_ARTICLES_PATTERN = Pattern.compile("javascript:submitArticles\\(([^,]+),([^,]+),*", Pattern.CASE_INSENSITIVE);
    protected Pattern DOI_URL_PATTERN = Pattern.compile("^(https?://.*/)doi/(abs|full|book)/([.0-9]+)/([^/]+)$");
    private static final String CIT_FORMATS_ACTION = "action/showCitFormats";

    private String html_url = null;
    private ArchivalUnit thisau = null;

    public AIAAPreFilter(ArchivalUnit au, String url) {
      super();
      html_url = url;
      thisau = au;
    }

    public boolean accept(Node node) {
      // store the value of the PDF link arguments for later reassembly
      if (node instanceof LinkTag) {
          Matcher doiMat = DOI_URL_PATTERN.matcher(html_url);
          // Are we on a page for which this would be pertinent?
          if (doiMat.find()) {
            // now do we have a citation download href?
            String linkval = ((LinkTag) node).extractLink();
            if (linkval == null) {
              return false;
            }
            Matcher hrefMat = SUBMIT_ARTICLES_PATTERN.matcher(linkval);
            if ( (hrefMat.find() && hrefMat.group(2).contains(CIT_FORMATS_ACTION))) {
              String newUrl =  doiMat.group(1) + CIT_FORMATS_ACTION + "?doi=" + doiMat.group(3) + "/" + doiMat.group(4);
              newUrl = AuUtil.normalizeHttpHttpsFromBaseUrl(thisau, newUrl);
              ((LinkTag) node).setLink(newUrl);
            }
          }
        }
      return false;
      }
    }

}


text:
/**
 * @author Niko van Meurs <nikovanmeurs@gmail.com>
 * @author Sid Mijnders
 */
const
    browserify = require('browserify'),
    gulp       = require('gulp'),
    rename     = require('gulp-rename'),
    uglify     = require('gulp-uglify'),
    source     = require('vinyl-source-stream');

gulp.task('build', function () {

    var bundler,
        stream;

    bundler = browserify({
        entries: ['./js/wrapper.js']
    });

    stream = bundler.bundle();

    return stream
        .pipe(source('./dist/wrapper.js'))
        .pipe(rename('nodium-ui.js'))
        .pipe(gulp.dest('./dist'));
});

gulp.task('minify', function () {

    return gulp.src('./dist/nodium-ui.js')
        .pipe(uglify())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist'));
})


text:
var HeaderCell = Datagrid.HeaderCell = Cell.extend({
  initialize: function() {
    HeaderCell.__super__.initialize.apply(this, arguments);

    this.sorter = this.options.sorter;

    if (this.column.sortable) {
      this.delegateEvents({click: 'sort'});
    }
  },

  render: function() {
    this._prepareValue();
    var html = this.value, icon;

    if (this.column.sortable) {
      this.$el.addClass('sortable');
      if (this.sorter.sortedBy(this.column.sortedProperty || this.column.property) || this.sorter.sortedBy(this.column.index)) {
        if (this.sorter.sortedASC()) {
          icon = 'icon-chevron-up';
        } else {
          icon = 'icon-chevron-down';
        }
      } else {
        icon = 'icon-minus';
      }

      html += ' <i class="' + icon + ' pull-right"></i>';
    }

    this.$el.html(html);
    return this;
  },

  sort: function() {
    this.sorter.sort(this.column.sortedProperty || this.column.property);
  }
});


text:
<?php
/**
 * Additional Customer Details (plain)
 *
 * This is extra customer data which can be filtered by plugins. It outputs below the order item table.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/plain/email-addresses.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates/Emails/Plain
 * @version 3.4.0
 */

defined( 'ABSPATH' ) || exit;

echo esc_html( wc_strtoupper( esc_html__( 'Customer details', 'woocommerce' ) ) ) . "\n\n";

foreach ( $fields as $field ) {
	echo wp_kses_post( $field['label'] ) . ': ' . wp_kses_post( $field['value'] ) . "\n";
}


text:
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//

#include "cbase.h"
#include "ai_motor.h"
#include "ai_behavior_fear.h"
#include "ai_hint.h"
#include "ai_navigator.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

BEGIN_DATADESC( CAI_FearBehavior )
	DEFINE_FIELD( m_flTimeToSafety, FIELD_TIME ),
	DEFINE_FIELD( m_flTimePlayerLastVisible, FIELD_TIME ),
	DEFINE_FIELD( m_hSafePlaceHint, FIELD_EHANDLE ),
	DEFINE_FIELD( m_hMovingToHint, FIELD_EHANDLE ),
	DEFINE_EMBEDDED( m_SafePlaceMoveMonitor ),
	DEFINE_FIELD( m_flDeferUntil, FIELD_TIME ),
END_DATADESC();

#define BEHAVIOR_FEAR_SAFETY_TIME		5
#define FEAR_SAFE_PLACE_TOLERANCE		36.0f
#define FEAR_ENEMY_TOLERANCE_CLOSE_DIST_SQR		Square(300.0f) // (25 feet)
#define FEAR_ENEMY_TOLERANCE_TOO_CLOSE_DIST_SQR	Square( 60.0f ) // (5 Feet)

ConVar ai_enable_fear_behavior( "ai_enable_fear_behavior", "1" );

ConVar ai_fear_player_dist("ai_fear_player_dist", "720" );

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CAI_FearBehavior::CAI_FearBehavior()
{
	ReleaseAllHints();
	m_SafePlaceMoveMonitor.ClearMark();
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_FearBehavior::Precache( void )
{

}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *pTask -
//-----------------------------------------------------------------------------
void CAI_FearBehavior::StartTask( const Task_t *pTask )
{
	switch( pTask->iTask )
	{
	case TASK_FEAR_IN_SAFE_PLACE:
		// We've arrived! Lock the hint and set the marker. we're safe for now.
		m_hSafePlaceHint = m_hMovingToHint;
		m_hSafePlaceHint->Lock( GetOuter() );
		m_SafePlaceMoveMonitor.SetMark( GetOuter(), FEAR_SAFE_PLACE_TOLERANCE );
		TaskComplete();
		break;

	case TASK_FEAR_GET_PATH_TO_SAFETY_HINT:
		// Using TaskInterrupt() optimizations. See RunTask().
		break;

	case TASK_FEAR_WAIT_FOR_SAFETY:
		m_flTimeToSafety = gpGlobals->curtime + BEHAVIOR_FEAR_SAFETY_TIME;
		break;

	default:
		BaseClass::StartTask( pTask );
		break;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Input  : *pTask -
//-----------------------------------------------------------------------------
void CAI_FearBehavior::RunTask( const Task_t *pTask )
{
	switch( pTask->iTask )
	{
	case TASK_FEAR_WAIT_FOR_SAFETY:
		if( HasCondition(COND_SEE_ENEMY) )
		{
			m_flTimeToSafety = gpGlobals->curtime + BEHAVIOR_FEAR_SAFETY_TIME;
		}
		else
		{
			if( gpGlobals->curtime > m_flTimeToSafety )
			{
				TaskComplete();
			}
		}
		break;

	case TASK_FEAR_GET_PATH_TO_SAFETY_HINT:
		{
			switch( GetOuter()->GetTaskInterrupt() )
			{
			case 0:// Find the hint node
				{
					ReleaseAllHints();
					CAI_Hint *pHint = FindFearWithdrawalDest();

					if( pHint == NULL )
					{
						TaskFail("Fear: Couldn't find hint node\n");
						m_flDeferUntil = gpGlobals->curtime + 3.0f;// Don't bang the hell out of this behavior. If we don't find a node, take a short break and run regular AI.
					}
					else
					{
						m_hMovingToHint.Set( pHint );
						GetOuter()->TaskInterrupt();
					}
				}
				break;

			case 1:// Do the pathfinding.
				{
					Assert( m_hMovingToHint != NULL );

					AI_NavGoal_t goal(m_hMovingToHint->GetAbsOrigin());
					goal.pTarget = NULL;
					if( GetNavigator()->SetGoal( goal ) == false )
					{
						m_hMovingToHint.Set( NULL );
						// Do whatever we'd want to do if we can't find a path
						/*
						Msg("Can't path to the Fear Hint!\n");

						AI_NavGoal_t nearGoal( GOALTYPE_LOCATION_NEAREST_NODE, m_hRallyPoint->GetAbsOrigin(), AIN_DEF_ACTIVITY, 256 );
						if ( GetNavigator()->SetGoal( nearGoal, AIN_CLEAR_PREVIOUS_STATE ) )
						{
						//FIXME: HACK! The internal pathfinding is setting this without our consent, so override it!
						ClearCondition( COND_TASK_FAILED );
						GetNavigator()->SetArrivalDirection( m_hRallyPoint->GetAbsAngles() );
						TaskComplete();
						return;
						}
						*/
					}
					else
					{
						GetNavigator()->SetArrivalDirection( m_hMovingToHint->GetAbsAngles() );
					}
				}
				break;
			}
		}
		break;

	default:
		BaseClass::RunTask( pTask );
		break;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : TRUE if I have an enemy and that enemy would attack me if it could
// Notes  : Returns FALSE if the enemy is neutral or likes me.
//-----------------------------------------------------------------------------
bool CAI_FearBehavior::EnemyDislikesMe()
{
	CBaseEntity *pEnemy = GetEnemy();

	if( pEnemy == NULL )
		return false;

	if( pEnemy->MyNPCPointer() == NULL )
		return false;

	Disposition_t disposition = pEnemy->MyNPCPointer()->IRelationType(GetOuter());

	Assert(disposition != D_ER);

	if( disposition >= D_LI )
		return false;

	return true;
}

//-----------------------------------------------------------------------------
// This place is definitely no longer safe. Stop picking it for a while.
//-----------------------------------------------------------------------------
void CAI_FearBehavior::MarkAsUnsafe()
{
	Assert( m_hSafePlaceHint );

	// Disable the node to stop anyone from picking it for a while.
	m_hSafePlaceHint->DisableForSeconds( 5.0f );
}

//-----------------------------------------------------------------------------
// Am I in safe place from my enemy?
//-----------------------------------------------------------------------------
bool CAI_FearBehavior::IsInASafePlace()
{
	// No safe place in mind.
	if( !m_SafePlaceMoveMonitor.IsMarkSet() )
		return false;

	// I have a safe place, but I'm not there.
	if( m_SafePlaceMoveMonitor.TargetMoved(GetOuter()) )
		return false;

	return true;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::SpoilSafePlace()
{
	m_SafePlaceMoveMonitor.ClearMark();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::ReleaseAllHints()
{
	if( m_hSafePlaceHint )
	{
		// If I have a safe place, unlock it for others.
		m_hSafePlaceHint->Unlock();

		// Don't make it available right away. I probably left for a good reason.
		// We also don't want to oscillate
		m_hSafePlaceHint->DisableForSeconds( 4.0f );
		m_hSafePlaceHint = NULL;
	}

	if( m_hMovingToHint )
	{
		m_hMovingToHint->Unlock();
		m_hMovingToHint = NULL;
	}

	m_SafePlaceMoveMonitor.ClearMark();
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
// Notes  : This behavior runs when I have an enemy that I fear, but who
//			does NOT hate or fear me (meaning they aren't going to fight me)
//-----------------------------------------------------------------------------
bool CAI_FearBehavior::CanSelectSchedule()
{
	if( !GetOuter()->IsInterruptable() )
		return false;

	if( m_flDeferUntil > gpGlobals->curtime )
		return false;

	CBaseEntity *pEnemy = GetEnemy();

	if( pEnemy == NULL )
		return false;

	//if( !HasCondition(COND_SEE_PLAYER) )
	//	return false;

	if( !ai_enable_fear_behavior.GetBool() )
		return false;

	if( GetOuter()->IRelationType(pEnemy) != D_FR )
		return false;

	if( !pEnemy->ClassMatches("npc_hunter") )
		return false;

	return true;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::GatherConditions()
{
	BaseClass::GatherConditions();

	ClearCondition( COND_FEAR_ENEMY_CLOSE );
	ClearCondition( COND_FEAR_ENEMY_TOO_CLOSE );
	if( GetEnemy() )
	{
		float flEnemyDistSqr = GetAbsOrigin().DistToSqr(GetEnemy()->GetAbsOrigin());

		if( flEnemyDistSqr < FEAR_ENEMY_TOLERANCE_TOO_CLOSE_DIST_SQR )
		{
			SetCondition( COND_FEAR_ENEMY_TOO_CLOSE );
			if( IsInASafePlace() )
			{
				SpoilSafePlace();
			}
		}
		else if( flEnemyDistSqr < FEAR_ENEMY_TOLERANCE_CLOSE_DIST_SQR && GetEnemy()->GetEnemy() == GetOuter() )
		{
			// Only become scared of an enemy at this range if they're my enemy, too
			SetCondition( COND_FEAR_ENEMY_CLOSE );
			if( IsInASafePlace() )
			{
				SpoilSafePlace();
			}
		}
	}

	ClearCondition(COND_FEAR_SEPARATED_FROM_PLAYER);

	// Check for separation from the player
	//	-The player is farther away than 60 feet
	//  -I haven't seen the player in 2 seconds
	//
	// Here's the distance check:
	CBasePlayer *pPlayer = AI_GetSinglePlayer();
	if( pPlayer != NULL && GetAbsOrigin().DistToSqr(pPlayer->GetAbsOrigin()) >= Square( ai_fear_player_dist.GetFloat() * 1.5f )  )
	{
		SetCondition(COND_FEAR_SEPARATED_FROM_PLAYER);
	}

	// Here's the visibility check. We can't skip this because it's time-sensitive
	if( GetOuter()->FVisible(pPlayer) )
	{
		m_flTimePlayerLastVisible = gpGlobals->curtime;
	}
	else
	{
		if( gpGlobals->curtime - m_flTimePlayerLastVisible >= 2.0f )
		{
			SetCondition(COND_FEAR_SEPARATED_FROM_PLAYER);
		}
	}

	if( HasCondition(COND_FEAR_SEPARATED_FROM_PLAYER) )
	{
		//Msg("I am separated from player\n");

		if( IsInASafePlace() )
		{
			SpoilSafePlace();
		}
	}
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::BeginScheduleSelection()
{
	if( m_hSafePlaceHint )
	{
		// We think we're safe. Is it true?
		if( !IsInASafePlace() )
		{
			// no! So mark it so.
			ReleaseAllHints();
		}
	}

	m_flTimePlayerLastVisible = gpGlobals->curtime;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::EndScheduleSelection()
{
	// We don't have to release our hints or markers or anything here.
	// Just because we ran other AI for a while doesn't mean we aren't still in a safe place.
	//ReleaseAllHints();
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : int
// Notes  : If fear behavior is running at all, we know we're afraid of our enemy
//-----------------------------------------------------------------------------
int CAI_FearBehavior::SelectSchedule()
{
	bool bInSafePlace = IsInASafePlace();

	if( !HasCondition(COND_HEAR_DANGER) )
	{
		if( !bInSafePlace )
		{
			// Always move to a safe place if we're not running from a danger sound
			return SCHED_FEAR_MOVE_TO_SAFE_PLACE;
		}
		else
		{
			// We ARE in a safe place
			if( HasCondition(COND_CAN_RANGE_ATTACK1) )
				return SCHED_RANGE_ATTACK1;

			return SCHED_FEAR_STAY_IN_SAFE_PLACE;
		}
	}

	return BaseClass::SelectSchedule();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CAI_FearBehavior::BuildScheduleTestBits()
{
	BaseClass::BuildScheduleTestBits();

	if( GetOuter()->GetState() != NPC_STATE_SCRIPT )
	{
		// Stop doing ANYTHING if we get scared.
		//GetOuter()->SetCustomInterruptCondition( COND_HEAR_DANGER );

		if( !IsCurSchedule(SCHED_FEAR_MOVE_TO_SAFE_PLACE_RETRY, false) && !IsCurSchedule(SCHED_FEAR_MOVE_TO_SAFE_PLACE, false) )
		{
			GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal(COND_FEAR_SEPARATED_FROM_PLAYER) );
		}
	}
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CAI_FearBehavior::TranslateSchedule( int scheduleType )
{
	switch( scheduleType )
	{
	case SCHED_FEAR_MOVE_TO_SAFE_PLACE:
		if( HasCondition(COND_FEAR_ENEMY_TOO_CLOSE) )
		{
			// If I'm moving to a safe place AND have an enemy too close to me,
			// make the move to safety while ignoring the condition.
			// this stops an oscillation
			// IS THIS CODE EVER EVEN BEING CALLED? (sjb)
			return SCHED_FEAR_MOVE_TO_SAFE_PLACE_RETRY;
		}
		break;
	}

	return BaseClass::TranslateSchedule( scheduleType );
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CAI_Hint *CAI_FearBehavior::FindFearWithdrawalDest()
{
	CAI_Hint *pHint;
	CHintCriteria hintCriteria;
	CAI_BaseNPC *pOuter = GetOuter();

	Assert(pOuter != NULL);

	hintCriteria.AddHintType( HINT_PLAYER_ALLY_FEAR_DEST );
	hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE_TO_PLAYER | bits_HINT_NOT_CLOSE_TO_ENEMY /*| bits_HINT_NODE_IN_VIEWCONE | bits_HINT_NPC_IN_NODE_FOV*/ );
	hintCriteria.AddIncludePosition( AI_GetSinglePlayer()->GetAbsOrigin(), ( ai_fear_player_dist.GetFloat() ) );

	pHint = CAI_HintManager::FindHint( pOuter, hintCriteria );

	if( pHint )
	{
		// Reserve this node while I try to get to it. When I get there I will lock it.
		// Otherwise, if I fail to get there, the node will come available again soon.
		pHint->DisableForSeconds( 4.0f );
	}
#if 0
	else
	{
		Msg("DID NOT FIND HINT\n");
		NDebugOverlay::Cross3D( GetOuter()->WorldSpaceCenter(), 32, 255, 255, 0, false, 10.0f );
	}
#endif

	return pHint;
}

AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( CAI_FearBehavior )

	DECLARE_TASK( TASK_FEAR_GET_PATH_TO_SAFETY_HINT )
	DECLARE_TASK( TASK_FEAR_WAIT_FOR_SAFETY )
	DECLARE_TASK( TASK_FEAR_IN_SAFE_PLACE )

	DECLARE_CONDITION( COND_FEAR_ENEMY_CLOSE )
	DECLARE_CONDITION( COND_FEAR_ENEMY_TOO_CLOSE )
	DECLARE_CONDITION( COND_FEAR_SEPARATED_FROM_PLAYER )

	//===============================================
	//===============================================
	DEFINE_SCHEDULE
	(
		SCHED_FEAR_MOVE_TO_SAFE_PLACE,

		"	Tasks"
		"		TASK_SET_FAIL_SCHEDULE				SCHEDULE:SCHED_RUN_FROM_ENEMY"
		"		TASK_FEAR_GET_PATH_TO_SAFETY_HINT	0"
		"		TASK_RUN_PATH						0"
		"		TASK_WAIT_FOR_MOVEMENT				0"
		"		TASK_SET_ACTIVITY					ACTIVITY:ACT_IDLE"
		"		TASK_FEAR_IN_SAFE_PLACE				0"
		"		TASK_SET_SCHEDULE					SCHEDULE:SCHED_FEAR_STAY_IN_SAFE_PLACE"
		""
		"	Interrupts"
		""
		"		COND_HEAR_DANGER"
		"		COND_NEW_ENEMY"
		"		COND_FEAR_ENEMY_TOO_CLOSE"
	);

	DEFINE_SCHEDULE
		(
		SCHED_FEAR_MOVE_TO_SAFE_PLACE_RETRY,

		"	Tasks"
		"		TASK_SET_FAIL_SCHEDULE				SCHEDULE:SCHED_RUN_FROM_ENEMY"
		"		TASK_FEAR_GET_PATH_TO_SAFETY_HINT	0"
		"		TASK_RUN_PATH						0"
		"		TASK_WAIT_FOR_MOVEMENT				0"
		"		TASK_SET_ACTIVITY					ACTIVITY:ACT_IDLE"
		"		TASK_FEAR_IN_SAFE_PLACE				0"
		"		TASK_SET_SCHEDULE					SCHEDULE:SCHED_FEAR_STAY_IN_SAFE_PLACE"
		""
		"	Interrupts"
		""
		"		COND_HEAR_DANGER"
		"		COND_NEW_ENEMY"
		);

	//===============================================
	//===============================================
	DEFINE_SCHEDULE
		(
		SCHED_FEAR_STAY_IN_SAFE_PLACE,

		"	Tasks"
		"		TASK_FEAR_WAIT_FOR_SAFETY			0"
		""
		"	Interrupts"
		""
		"		COND_NEW_ENEMY"
		"		COND_HEAR_DANGER"
		"		COND_FEAR_ENEMY_CLOSE"
		"		COND_FEAR_ENEMY_TOO_CLOSE"
		"		COND_CAN_RANGE_ATTACK1"
		"		COND_FEAR_SEPARATED_FROM_PLAYER"
		);

AI_END_CUSTOM_SCHEDULE_PROVIDER()


text:
package com.navercorp.pinpoint.profiler.context.provider;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.rpc.client.PinpointClient;
import com.navercorp.pinpoint.rpc.client.PinpointClientFactory;
import com.navercorp.pinpoint.rpc.util.ClientFactoryUtils;

/**
 * @author Woonduk Kang(emeroad)
 */
public class PinpointClientProvider implements Provider<PinpointClient> {
    private final ProfilerConfig profilerConfig;
    private final Provider<PinpointClientFactory> clientFactory;

    @Inject
    public PinpointClientProvider(ProfilerConfig profilerConfig, Provider<PinpointClientFactory> clientFactory) {
        if (profilerConfig == null) {
            throw new NullPointerException("profilerConfig must not be null");
        }
        if (clientFactory == null) {
            throw new NullPointerException("clientFactory must not be null");
        }
        this.profilerConfig = profilerConfig;
        this.clientFactory = clientFactory;
    }

    @Override
    public PinpointClient get() {
        PinpointClientFactory pinpointClientFactory = clientFactory.get();
        PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(profilerConfig.getCollectorTcpServerIp(), profilerConfig.getCollectorTcpServerPort(), pinpointClientFactory);
        return pinpointClient;
    }
}


text:
var application = angular.module('CorlyWMT', [
		'ui.router',
        'angularFileUpload',
        'googlechart'
	]);

// Load foundation on every new page load
application.run(function($rootScope, $timeout)	{
	$rootScope.$on('$viewContentLoaded', function()	{
		$timeout(function()	{
			$(".button-collapse").sideNav();
			$('.collapsible').collapsible();
			$('.dropdown-button').dropdown();
			$('.tooltipped').tooltip({delay: 50});
			$('select').material_select();
		}, 500);
	})
});

// Keep track of routing and keep non authorized users away
application.run(['$rootScope', '$location', 'SessionService', function ($rootScope, $location, SessionService) {
    // Array of routes, that do require login
    var routesThatRequireAuth = ['/import', '/settings', '/project-settings', '/profile'];

    // Wait  for location to change
    $rootScope.$on('$stateChangeStart', function (event, next) {
        // Check route
        if (routesThatRequireAuth.indexOf($location.path()) < 0)   {
            return;
        }
        // If routes requires auth, than check current user
        else {
            // Check session
            SessionService.check().success(function (data, status, headers, config) {
                // Check result
                if (data === "false")
                    $location.path('/');
            });
        }
    });
}]);

/**
 * Configuration for routes
 */
application.config(function($stateProvider, $urlRouterProvider){

	// Set default page to login
	$urlRouterProvider.otherwise('/');

	// Define states
	$stateProvider
    // Installation page
	.state('installation', {
	    url: '/installation',
	    templateUrl: './views/home/installation.html',
	    controller: 'InstallationController'
	})
	// Home page
	.state('home', {
	    url: '/',
	    abstract: true,
	    templateUrl: './views/home/index.html',
	    controller: 'HomeController'
	})
	// Dashboard
	.state('home.dashboard', {
	    url: '',
	    templateUrl: './views/home/dashboard.html',
	    controller: 'DashboardController'
	})
    // Import
	.state('home.import', {
	    url: 'import',
	    templateUrl: './views/home/import.html',
	    controller: 'ImportController'
	})
    // Settings - users
	.state('home.settings-users', {
	    url: 'settings/users',
	    templateUrl: './views/home/settings/users.html',
	    controller: 'UsersController'
	})
	// Settings - release notes
	.state('home.settings-release-notes', {
	    url: 'settings/release-notes',
	    templateUrl: './views/home/settings/release.html',
	    controller: 'ReleaseNotesController'
	})
    // Plugin management
	.state('home.plugin-management', {
	    url: 'settings/plugin-management',
	    templateUrl: './views/home/pluginManagement.html',
	    controller: 'PluginManagementController'
	})
    // Data overview
	.state('home.data-overview', {
	    url: 'data-overview',
	    templateUrl: './views/home/dataOverview.html',
	    controller: 'DataOverviewController'
	})
    // Plugin detail
    .state('home.plugin', {
        url: 'plugin-overview/{pluginId}',
        templateUrl: './views/home/plugin.html',
        controller: 'PluginController'
    })
    // Project overview detail
    .state('home.project-overview', {
        url: 'project/{projectId}',
        templateUrl: './views/home/overview/project.html',
        controller: 'ProjectOverviewController'
    })
    // Project overview detail
    .state('home.project-settings', {
        url: 'project-settings/{projectId}',
        templateUrl: './views/home/projectSettings.html',
        controller: 'ProjectSettingsController'
    })
    // Submission overview detail
    .state('home.submission-overview', {
        url: 'project/{projectId}/submission/{submissionId}',
        templateUrl: './views/home/overview/submission.html',
        controller: 'SubmissionOverviewController'
    })
    // Difference overview detail
    .state('home.difference-overview', {
        url: 'project/{projectId}/difference/{differenceArray}',
        templateUrl: './views/home/overview/difference.html',
        controller: 'DifferenceOverviewController'
    })
    // Analyze overview detail
    .state('home.analyze-overview', {
        url: 'project/{projectId}/analyze/{submissionId}',
        templateUrl: './views/home/overview/analyze.html',
        controller: 'AnalyzeController'
    })
    // Profile
	.state('home.profile', {
	    url: 'profile',
	    templateUrl: './views/home/profile.html',
	    controller: 'ProfileController'
	})
});


text: INSERT INTO t11b VALUES(3,4)


text:
__license__= """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014

Golismero project site: https://github.com/golismero
Golismero project mail: contact@golismero-project.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
"""

__all__ = ["InvalidCertificate"]

from . import SSLVulnerability

#------------------------------------------------------------------------------
class InvalidCertificate(SSLVulnerability):
    """
    Invalid SSL/TLS Certificate.

    An invalid SSL/TLS certificate was found.
    This may allow a strategically located attacker
    to snoop on network traffic, or perform a
    Man-In-The-Middle attack against unsuspecting
    users connecting to this host.

    Create a new certificate.
    """

    DEFAULTS = SSLVulnerability.DEFAULTS.copy()
    DEFAULTS["level"]     = "low"
    DEFAULTS["cwe"]       = "CWE-327"
    DEFAULTS["cvss_base"] = "5.8"


text:
<?php

namespace yiiunit\framework\filters\stubs;

use yii\base\BaseObject;
use yii\filters\RateLimitInterface;

class RateLimit extends BaseObject implements RateLimitInterface
{
    private $_rateLimit;

    private $_allowance;

    public function getRateLimit($request, $action)
    {
        return $this->_rateLimit;
    }

    public function setRateLimit($rateLimit)
    {
        $this->_rateLimit = $rateLimit;

        return $this;
    }

    public function loadAllowance($request, $action)
    {
        return $this->_allowance;
    }

    public function setAllowance($allowance)
    {
        $this->_allowance = $allowance;

        return $this;
    }

    public function saveAllowance($request, $action, $allowance, $timestamp)
    {
        return [$action, $allowance, $timestamp];
    }
}


text:
const char* GetJitterName();

#endif


text:
from configobj import ConfigObj
from validate import Validator

import os, sys, subprocess, signal, tempfile, shutil, pipes, time, locale

from datetime import datetime

from PyQt4 import QtGui, QtCore
try:
    from gi.repository import Notify
except:
    Notify = None

dirname = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dirname, os.path.pardir))

from lib import wireutils
wireutils.color_printing_config.name  = "Perdyshot"
wireutils.color_printing_config.color = wireutils.ansi_colors.DARKCYAN

cwd = os.getcwd()

ICON = os.path.join(dirname, os.path.pardir, "icon_glow.png")
LOGO = os.path.join(dirname, os.path.pardir, "icon_plain.png")
VERSION = 'Perdyshot ' + open(os.path.join(dirname, os.path.pardir, '.version'), 'r').read()
URL = "https://github.com/Locercus/Perdyshot"

DATE = os.path.getmtime(os.path.join(dirname, os.path.pardir, ".version"))
DATE = datetime.fromtimestamp(DATE).strftime(locale.nl_langinfo(locale.D_T_FMT))

if Notify:
    Notify.init("Perdyshot")

config = ConfigObj(os.path.join(dirname, os.path.pardir, 'perdyshot.conf'), encoding = 'UTF8', configspec = os.path.join(dirname, os.path.pardir, 'perdyshot.conf.spec'))
validator = Validator()
if not config.validate(validator):
    wireutils.color_print("Invalid configuration file", color = wireutils.ansi_colors.DARKRED)
    sys.exit(1)

settings = {}

settings['modes'] = config['GUI']['CaptureModes']

app = QtGui.QApplication(sys.argv)

# Create about dialog
class AboutDialog(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setFixedSize(450, 240)
        self.setWindowTitle("About Perdyshot")

        image = QtGui.QLabel(self)
        image.setPixmap(QtGui.QPixmap(LOGO))
        image.move((450 - image.sizeHint().width()) / 2, 10)

        text = QtGui.QLabel(self)
        text.setText("%s © 2015 Jonatan Nordentoft. MIT License
Released on %s" % (VERSION, DATE))
        text.move((450 - text.sizeHint().width()) / 2, image.sizeHint().height() + 30)

        website = QtGui.QPushButton("Website", self)
        website.move((450 - website.sizeHint().width()) / 2, image.sizeHint().height() + text.sizeHint().height() + 45)
        website.clicked.connect(self.openWebsite)

    def closeEvent(self, event):
        event.ignore()
        self.hide()

    def openWebsite(self):
        subprocess.call(["xdg-open", URL])

# Create tray icon
# http://stackoverflow.com/a/895721/1248084
class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, icon, parent = None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)

        menu = QtGui.QMenu(parent)
        self.menu = menu

        # Add the options
        for key in settings['modes']:
            action = menu.addAction(key)
            action.triggered.connect(
                lambda x, key = key: self.onCapture(key)
                )

        menu.addSeparator()

        menu.addAction("About", self.onAbout)
        menu.addAction("Quit", self.onQuit)

        self.setContextMenu(menu)

    def onQuit(self):
        sys.exit(0)

    def onAbout(self):
        aboutDialog.show()

    def onCapture(self, item):
        options = settings['modes'][item]

        if options['type'] == 'script':
            subprocess.call([ options['file'] ])

        elif options['type'] == 'simple':
            filename = os.path.join(tempfile.gettempdir(), 'perdygui.png')
            if not os.path.exists(filename):
                open(filename, "w").close()

            args = [
                '/usr/bin/env', 'python2', os.path.join(dirname, os.path.pardir, 'cli', options['mode'] + '.py'),

                '-f', filename
            ]

            if options['mode'] == 'window':
                args.extend(['--delay', '0'])

            # Capture the screenshot
            subprocess.call(args)

            # Okay the screenshot has been captures. What do we do now?
            if options['file'] != None:
                newFilename = time.strftime(options['file'])
                shutil.copyfile(filename, newFilename)
                filename = newFilename

            if options['program'] != None:
                subprocess.call(options['program'] % filename, shell = True)

            if options['copy']:
                subprocess.call('xclip -i -sel clip < ' + pipes.quote(filename), shell = True)

            if options['notification'] and Notify:
                notification = Notify.Notification.new(
                    options['notificationTitle'],
                    options['notificationDescription'],
                    options['notificationImage'] if options['notificationImage'] != None else ICON
                    )
                notification.show()

aboutDialog = AboutDialog()

iconWidget = QtGui.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(ICON), iconWidget)
trayIcon.show()

signal.signal(signal.SIGINT, signal.SIG_DFL)
app.exec_()


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Boost.Locale: boost::locale::gnu_gettext Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Boost.Locale

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

Namespace List

Namespace Members

Classes |
Functions

boost::locale::gnu_gettext Namespace Reference
Message Formatting (translation)

This namespace holds classes that provide GNU Gettext message catalogs support.
More...

Classes

struct  	messages_info

 	This structure holds all information required for creating gnu-gettext message catalogs,.  More...

Functions

template<typename CharType >

message_format< CharType > * 	create_messages_facet (messages_info const &info)

Detailed Description

This namespace holds classes that provide GNU Gettext message catalogs support.

Function Documentation

template<typename CharType >

          message_format<CharType>* boost::locale::gnu_gettext::create_messages_facet
          (
          messages_info const &
          info	)

Create a message_format facet using GNU Gettext catalogs. It uses info structure to get information about where to read them from and uses it for character set conversion (if needed)

© Copyright 2009-2012 Artyom Beilis,  Distributed under the Boost Software License, Version 1.0.


text:
import { IChangeable } from './IChangeable';
/**
 * Interface for data objects that can track their changes including logical deletion
 */
export interface ITrackable extends IChangeable {
    /**
     * UTC time when the object was created
     */
    create_time: Date;
    /**
     * The last time when the object was changed (created, updated or deleted)
     */
    change_time: Date;
    /**
     * The logical deletion flag
     */
    deleted: boolean;
}


text:
angular.module("iso.directives", ["iso.config", "iso.services", "iso.controllers"]);

angular.module("iso.directives")
.directive("isotopeContainer", ["$injector", "$parse", function($injector, $parse) {
    "use strict";
    var options;
    options = {};
    return {
      controller: "angularIsotopeController",
      link: function(scope, element, attrs) {
        var isoInit, isoOptions, linkOptions;
        linkOptions = [];
        isoOptions = attrs.isoOptions;
        isoInit = {};
        if (isoOptions) {
          linkOptions = $parse(isoOptions)(scope);
          if (angular.isObject(linkOptions)) {
            scope.updateOptions(linkOptions);
          }
        }
        isoInit.element = element;
        isoInit.isoOptionsEvent = attrs.isoOptionsSubscribe;
        isoInit.isoMethodEvent = attrs.isoMethodSubscribe;
        isoInit.isoMode = attrs.isoMode;
        if (attrs.isoUseInitEvent === "true") {
          scope.delayInit(isoInit);
        } else {
          scope.init(isoInit);
        }
        return element;
      }
    };
  }
])
.directive("isotopeItem", [
  "$rootScope", "iso.config", "iso.topics", "$timeout", function($rootScope, config, topics, $timeout) {
    return {
      restrict: "A",
      require: "^isotopeContainer",
      link: function(scope, element, attrs) {

        scope.setIsoElement(element);
        scope.$on('$destroy', function(message) {
          $rootScope.$broadcast(topics.MSG_REMOVE, element);
        });
        if (attrs.ngRepeat && true === scope.$last && "addItems" === scope.isoMode) {
          element.ready(function() {
            return $timeout((function() {
              return scope.refreshIso();
            }), config.refreshDelay || 0);
          });
        }
        if (!attrs.ngRepeat) {
          element.ready(function() {
            return $timeout((function() {
              return scope.refreshIso();
            }), config.refreshDelay || 0);
          });
        }
        return element;
      }
    };
  }
])
.directive("isoSortbyData", function() {
    return {
      restrict: "A",
      controller: "isoSortByDataController",
      link: function(scope, element, attrs) {
        var methSet, methods, optEvent, optKey, optionSet, options;
        optionSet = $(element);
        optKey = optionSet.attr("ok-key");
        optEvent = "iso-opts";
        options = {};
        methSet = optionSet.find("[ok-sel]");
        methSet.each(function(index) {
          var $this;
          $this = $(this);
          return $this.attr("ok-sortby-key", scope.getHash($this.attr("ok-sel")));
        });
        methods = scope.createSortByDataMethods(methSet);
        return scope.storeMethods(methods);
      }
    };
  }
)
.directive("optKind", ['optionsStore', 'iso.topics', function(optionsStore, topics) {
  return {
    restrict: "A",
    controller: "isoSortByDataController",
    link: function(scope, element, attrs) {
      var createSortByDataMethods, createOptions, doOption, emitOption, optKey, optPublish, methPublish, optionSet, determineAciveClass, activeClass, activeSelector, active;
      optionSet = $(element);
      optPublish = attrs.okPublish || topics.MSG_OPTIONS;
      methPublish = attrs.okPublish || topics.MSG_METHOD;
      optKey = optionSet.attr("ok-key");

      determineActiveClass = function() {
        activeClass = attrs.okActiveClass;
        if (!activeClass) {
          activeClass = optionSet.find(".selected").length ? "selected" : "active";
        }
        activeSelector = "." + activeClass;
        active = optionSet.find(activeSelector);
      };

      createSortByDataMethods = function(optionSet) {
        var methSet, methods, optKey, options;
        optKey = optionSet.attr("ok-key");
        if (optKey !== "sortBy") {
          return;
        }
        options = {};
        methSet = optionSet.find("[ok-sel]");
        methSet.each(function(index) {
          var $this;
          $this = $(this);
          return $this.attr("ok-sortby-key", scope.getHash($this.attr("ok-sel")));
        });
        methods = scope.createSortByDataMethods(methSet);
        return scope.storeMethods(methods);
      };

      createOptions = function(item) {
        var ascAttr, key, option, virtualSortByKey;
        if (item) {
          option = {};
          virtualSortByKey = item.attr("ok-sortby-key");
          ascAttr = item.attr("opt-ascending");
          key = virtualSortByKey || item.attr("ok-sel");
          if (virtualSortByKey) {
            option.sortAscending = (ascAttr ? ascAttr === "true" : true);
          }
          option[optKey] = key;
          return option;
        }
      };

      emitOption = function(option) {
        optionsStore.store(option);
        return scope.$emit(optPublish, option);
      };

      doOption = function(event) {
        var selItem;
        event.preventDefault();
        selItem = $(event.target);
        if (selItem.hasClass(activeClass)) {
          return false;
        }
        optionSet.find(activeSelector).removeClass(activeClass);
        selItem.addClass(activeClass);
        emitOption(createOptions(selItem));
        return false;
      };

      determineActiveClass();

      createSortByDataMethods(optionSet);

      if (active.length) {
        var opts = createOptions(active);
        optionsStore.store(opts);
      }

      return optionSet.on("click", function(event) {
        return doOption(event);
      });
    }
  };
}]);


text:
module FacebookAccountsHelper
end