text:
module.exports = function(less) {

    var tree       = less.tree,
        Expression = tree.Expression,
        Anonymous  = tree.Anonymous,
        Value      = tree.Value,
        Node       = tree.Node,
        isArray    = Array.isArray;

    // ........................................................

    function newLessList(list, type) {
        var ReturnType = (type === "Expression")
            ? Expression : Value;
        return new ReturnType(list);
    }

    // ........................................................

    function toString(list, pre, post) {
        return !isArray(list.value) ? list.toCSS()
            : pre + list.value.map(function(a) {
                return toString(a, pre, post);
            }).join(list.type === "Expression"
                ? " " : ", ") + post;
    }

    // ........................................................

    function evalIndex(list, index, default_) {
        if (index && ((index.type !== "Dimension") ||
            !index.unit.isEmpty())) throw {
                type:    "Argument",
                message: "unexpected index `" + index.toCSS() + "`"
        };

        index = (index === undefined)
            ? default_ : index.value;
        return index + ((index < 1)
            ? list.value.length : -1);
    }

    // ........................................................

    function atKey(list, index) {
        if (!isArray(list.value))
            return;

        // see docs/impl-notes.md#at-1
        list = (!isArray(list.value[0].value) &&
            (list.type === "Expression"))
                ? [list] : list.value;

        var pair, type, key;
        for (var i = 0; i < list.length; i++) {
            pair = list[i];
            // return empty thing if value is missing but key matches:
            if (!isArray(pair) &&
                (Node.compare(index, pair) === 0))
                    return new Node();

            type = pair.type;
            pair = pair.value;
            key  = pair[0];
            if (Node.compare(index, key) === 0)
                return (pair.length < 2) ? pair[1]
                    : newLessList(pair.slice(1), type);
        }
    }

// ............................................................

    var functions = {

        // ....................................................

        at: function(list, index) {
            if ((index.type !== "Dimension") ||
                 !index.unit.isEmpty())
                    return atKey(list, index);

            list = isArray(list.value)
                ? list.value : [list];
            return list[index.value - 1];
        },

        /* Not yet.
        extract: function(list, index) {
            return functions.at(list, index);
        },
        */

        // ....................................................

        cat: function() {
            var returnType, list = [];
            for (var i = 0; i < arguments.length; i++) {
                var arg = arguments[i];
                if (isArray(arg.value)) {
                    returnType = returnType || arg.type;
                    arg = arg.value;
                }
                list = list.concat(arg);
            }

            return newLessList(list, returnType);
        },

        // ....................................................

        l: function() {
            if (arguments.length < 2)
                return;

            var list = new Array(arguments.length);
            for (var i = 0; i < arguments.length; i++)
                list[i] = arguments[i];
            return new Value(list);
        },

        // ....................................................

        slice: function(list, start, end) {
            if (list && isArray(list.value)) {
                start = evalIndex(list, start, 1);
                end   = evalIndex(list, end, 0);

                // see docs/impl-notes.md#slice-1
                return newLessList(list.value
                    .slice(start, end), list.type);
            }
        },

        // ....................................................

        splice: function(list, start, end, value) {
            if (list && isArray(list.value)) {
                start = evalIndex(list, start, 1);
                end   = evalIndex(list, end, start + 2) - start;

                var copy = list.value.slice();
                value // jshint expr: true
                    ? copy.splice(start, end, value)
                    : copy.splice(start, end);
                return newLessList(copy, list.type);
            }
        },

        // ....................................................

        flatten: function(list, type) {
            if (!isArray(list.value))
                return list;

            function flatten_(list) {
                return list.reduce(function(a, b) {
                    return a.concat(isArray(b.value)
                        ? flatten_(b.value) : b);
                }, []);
            }

            // TODO: should not it try to determine the default return type by the type
            // of the input list top dimension? (for consistency with `cat`?)

            var ReturnType = type ? {
                comma: Value,
                space: Expression,
                ",":   Value,
                " ":   Expression
            }[type.value] : Value;

            if (!ReturnType) throw {
                type:    "Argument",
                message: "invalid `" + type.toCSS()
                    + "` delimiter. Expected `comma`, `space`, `,` or ` `\n"
            };

            return new ReturnType(flatten_(list.value));
        },

        // ....................................................

        transpose: function(list) {
            if (!isArray(list.value))
                return list;

            var listType, row, rowType;
            rowType  = list.type;
            list     = list.value;
            listType = list[0].type;
            row      = list[0].value;

            list = (isArray(row) ? row : [row]).map(function(col, i) {
                return newLessList(list.map(function(row) {
                    return (isArray(row.value)
                        ? row.value : [row])[i]
                            || new Node();
                }), rowType);
            });

            return newLessList(list, listType);
        },

        // ....................................................

        join: function(list, delim) {
            return new Anonymous(!isArray(list.value)
                ? list.toCSS()
                : list.value.map(function(a) {
                    return toString(a, "", "");
                }).join(delim ? delim.value : ", "));
        },

        // ....................................................

        _inspect: function(list, prefix, postfix) {
            prefix  = prefix  ? prefix.value  : "[";
            postfix = postfix ? postfix.value : "]";
            return new Anonymous(toString(list, prefix, postfix));
        }

        // ....................................................

    };

    return functions;

// ............................................................

};


text:
package de.poeschl.apps.tryandremove.broadcastReciever;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import de.poeschl.apps.tryandremove.service.ApplicationDetectionService;
import timber.log.Timber;

public class AppDetectionReceiver extends BroadcastReceiver {

    private boolean registered;

    public AppDetectionReceiver() {
        registered = false;
    }

    public boolean isRegistered() {
        return registered;
    }

    public void setRegistered(boolean registered) {
        this.registered = registered;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentData = intent.toUri(Intent.URI_INTENT_SCHEME);
        Timber.v("intent: " + intentData);

        switch (intent.getAction()) {
            case Intent.ACTION_PACKAGE_ADDED:
                Timber.d("Package install received");
                ApplicationDetectionService.startAppInstall(context, intentData);
                break;
            case Intent.ACTION_PACKAGE_REMOVED:
                Timber.d("Package uninstall received");
                ApplicationDetectionService.startAppRemove(context, intentData);
                break;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation DEMOAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[DEMOViewController alloc] initWithNibName:@"DEMOViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

@end


text:
"""
Django settings for condobus project.

Generated by 'django-admin startproject' using Django 2.0b1.

For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""

import os

from decouple import config

from django.utils.translation import ugettext_lazy as _

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd$l+5x!wj)d#!fm2=x0bs9#s9=zf0+w7cpz#v(hdh98u*afc1&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['localhost', 'backend']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'org',
    'transport',
    'graphene_django',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'condobus.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'condobus.wsgi.application'

# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': config('DB_NAME', default='condobus'),
        'USER': config('DB_USER', default='condobus'),
        'PASSWORD': config('DB_PASS', default='condobus'),
        'HOST': config('DB_HOST', default='127.0.0.1'),
        'PORT': config('DB_PORT', default='5432'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'

LANGUAGES = (
    ('pt-br', _('Portuguese')),
    ('en', _('English')),
)

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

GRAPHENE = {
    'SCHEMA': 'condobus.schema.schema'
}


text:
using FluentAssertions;
using Xunit;

namespace SoftwarePassion.LogBridge.UmbracoLog4Net.Tests.Unit.UmbracoLog4NetWrapperTests
{
    public class When_logging_information_messages_with_null_parameters : SoftwarePassion.LogBridge.Tests.Shared.When_logging_information_messages_with_null_parameters
    {
        public When_logging_information_messages_with_null_parameters()
            : base(new LogDataVerifier())
        {}

        [Fact(Skip = "Dummy")]
        public void Dummy()
        {
            42.Should().Be(42);
        }
    }
}


text:
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using System;

namespace Castleroid.NPCs
{
	public class GuardianHornetY : ModNPC
	{
		int contador = 0;//canta os frams
		int segundos = 0;//conta os segundos
		int steps = 0;// conta os passos

		public override void SetDefaults()
		{
			npc.name = "GuardianHornetY";
			npc.displayName = "Guardian Hornet";
			Main.npcFrameCount[npc.type] = Main.npcFrameCount[NPCID.Hornet];
			// aiType = NPCID.Hornet;
			animationType = NPCID.Hornet;
			npc.lifeMax = 8;
			npc.width = 34;
			npc.height = 32;
			npc.damage = 8;
			npc.defense = 0;
			npc.soundHit = 1;
			npc.soundKilled = 16;
			npc.value = 60f;
			npc.knockBackResist = 0.0f;
			npc.aiStyle = -1;
			npc.noGravity = true;
			npc.noTileCollide = false;

		}
	/*
	Modifica a escala de HP/Dano de acordo com o tipo de mapa (EXPERT)
	Desisti de mudar esta questão, deixando o mapa como Normal Pré hardmode, devido problemas bizarros de multiplicação caso o HP e Dano seja muito baixo

	public override void ScaleExpertStats(int numPlayers, float bossLifeScale)
		{
			npc.lifeMax = (int)(npc.lifeMax / 2);
			npc.damage = (int)(npc.damage / 2);
		}
	*/
	public override void HitEffect(int hitDirection, double damage)
		{
			for (int i = 0; i < 10; i++)
			{
				int dustType = Main.rand.Next(139, 143);
				int dustIndex = Dust.NewDust(npc.position, npc.width, npc.height, dustType);
				Dust dust = Main.dust[dustIndex];
				dust.velocity.X = dust.velocity.X + Main.rand.Next(-50, 51) * 0.01f;
				dust.velocity.Y = dust.velocity.Y + Main.rand.Next(-50, 51) * 0.01f;
				dust.scale *= 1f + Main.rand.Next(-30, 31) * 0.01f;
			}
		}

	public override void AI()
	{
			if(steps == 0)
			{
				npc.velocity.Y = -1;//move para traz
			}else if(steps == 1)
			{
				npc.velocity.Y = 1;//move para frente
			}
			else
			{
				npc.velocity.Y = 0;
				steps = 0;
			}
			npc.collideX = true;
			npc.collideY = true;
			contador += 1;
			if(contador > 240)
			{//60 numero de fps do jogo 60quadros por segundo
				steps++;
				segundos++;
				contador = 0;
			}
				if(segundos > 3)
			{

            if (npc.target < 0 || npc.target == 255 || Main.player[npc.target].dead || !Main.player[npc.target].active)

            {
                npc.TargetClosest(true);
            }

		   npc.netUpdate = true;

		}

	}

	public override void FindFrame(int frameHeight)
{
    if ((double) npc.velocity.Y > 0.0)
    {
        npc.spriteDirection = 1;
        npc.rotation = (float) Math.Atan2((double) npc.velocity.Y, (double) npc.velocity.X);
    }
    if ((double) npc.velocity.Y < 0.0)
    {
        npc.spriteDirection = -1;
        npc.rotation = (float) Math.Atan2((double) npc.velocity.Y, (double) npc.velocity.X) + 3.14f;
    }
}

}	}


text:
#ifndef IC_LEXER_H
#define IC_LEXER_H

#include "data/lex_data.h"
#include "data/token_list.h"

/* takes a character array of the source program
 *
 * takes the filename for current source unit, this
 * is attached to each token
 *
 * returns a token_list on success
 * returns 0 on failure
 */
struct ic_token_list *ic_lex(char *filename, char *source);

#endif


text:
while sleep 1;
do (
  # current timestamp
  echo -n "timestamp: " >> /location/to/log/stats1.log;
  date +%s000 >> /location/to/log/stats1.log;
  # mem info
  cat /proc/meminfo >> /location/to/log/stats1.log;
  # cpu info
  cat /proc/stat | grep "cpu " >> /location/to/log/stats1.log;
  # disk info
  cat /proc/diskstats | grep "sda " >> /location/to/log/stats1.log;
);
done


text: This page does not have any help text.


text:
create or replace function build.start(
    _build_id          int,
    out repository_url text,
    out branch         text,
    out revision       text
) returns record as $$
    declare
        _commit_id  int;
        _project_id int;
    begin

        UPDATE postgres_ci.builds AS B
            SET
                status     = 'running',
                started_at = current_timestamp
        WHERE B.build_id = _build_id
        AND   B.status   = 'accepted'
        RETURNING B.commit_id INTO _commit_id;

        IF NOT FOUND THEN
            RAISE EXCEPTION 'NOT_FOUND' USING ERRCODE = 'no_data_found';
        END IF;

        SELECT
            P.project_id,
            P.repository_url,
            B.branch,
            C.commit_sha
                INTO
                    _project_id,
                    repository_url,
                    branch,
                    revision
        FROM postgres_ci.projects AS P
        JOIN postgres_ci.branches AS B USING(project_id)
        JOIN postgres_ci.commits  AS C ON C.branch_id = B.branch_id
        WHERE C.commit_id = _commit_id;

        UPDATE postgres_ci.projects SET last_build_id = _build_id  WHERE project_id = _project_id;
    end;
$$ language plpgsql security definer;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GtkToolItem</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.0">
<link rel="home" href="index.html" title="GTK+ 3 Reference Manual">
<link rel="up" href="MenusAndCombos.html" title="Menus, Combo Box, Toolbar">
<link rel="prev" href="GtkToolbar.html" title="GtkToolbar">
<link rel="next" href="GtkToolPalette.html" title="GtkToolPalette">
<meta name="generator" content="GTK-Doc V1.18.1 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GTK+ 3 Reference Manual

Top
                   |
                  Description
                   |
                  Object Hierarchy
                   |
                  Implemented Interfaces
                   |
                  Properties
                   |
                  Signals

GtkToolItem

GtkToolItem — The base class of widgets that can be added to GtkToolShell

Synopsis

#include <gtk/gtk.h>

struct              GtkToolItem;
GtkToolItem *       gtk_tool_item_new                   (void);
void                gtk_tool_item_set_homogeneous       (GtkToolItem *tool_item,
                                                         gboolean homogeneous);
gboolean            gtk_tool_item_get_homogeneous       (GtkToolItem *tool_item);
void                gtk_tool_item_set_expand            (GtkToolItem *tool_item,
                                                         gboolean expand);
gboolean            gtk_tool_item_get_expand            (GtkToolItem *tool_item);
void                gtk_tool_item_set_tooltip_text      (GtkToolItem *tool_item,
                                                         const gchar *text);
void                gtk_tool_item_set_tooltip_markup    (GtkToolItem *tool_item,
                                                         const gchar *markup);
void                gtk_tool_item_set_use_drag_window   (GtkToolItem *tool_item,
                                                         gboolean use_drag_window);
gboolean            gtk_tool_item_get_use_drag_window   (GtkToolItem *tool_item);
void                gtk_tool_item_set_visible_horizontal
                                                        (GtkToolItem *tool_item,
                                                         gboolean visible_horizontal);
gboolean            gtk_tool_item_get_visible_horizontal
                                                        (GtkToolItem *tool_item);
void                gtk_tool_item_set_visible_vertical  (GtkToolItem *tool_item,
                                                         gboolean visible_vertical);
gboolean            gtk_tool_item_get_visible_vertical  (GtkToolItem *tool_item);
void                gtk_tool_item_set_is_important      (GtkToolItem *tool_item,
                                                         gboolean is_important);
gboolean            gtk_tool_item_get_is_important      (GtkToolItem *tool_item);
PangoEllipsizeMode  gtk_tool_item_get_ellipsize_mode    (GtkToolItem *tool_item);
GtkIconSize         gtk_tool_item_get_icon_size         (GtkToolItem *tool_item);
GtkOrientation      gtk_tool_item_get_orientation       (GtkToolItem *tool_item);
GtkToolbarStyle     gtk_tool_item_get_toolbar_style     (GtkToolItem *tool_item);
GtkReliefStyle      gtk_tool_item_get_relief_style      (GtkToolItem *tool_item);
gfloat              gtk_tool_item_get_text_alignment    (GtkToolItem *tool_item);
GtkOrientation      gtk_tool_item_get_text_orientation  (GtkToolItem *tool_item);
GtkWidget *         gtk_tool_item_retrieve_proxy_menu_item
                                                        (GtkToolItem *tool_item);
GtkWidget *         gtk_tool_item_get_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id);
void                gtk_tool_item_set_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id,
                                                         GtkWidget *menu_item);
void                gtk_tool_item_rebuild_menu          (GtkToolItem *tool_item);
void                gtk_tool_item_toolbar_reconfigured  (GtkToolItem *tool_item);
GtkSizeGroup *      gtk_tool_item_get_text_size_group   (GtkToolItem *tool_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkWidget
               +----GtkContainer
                     +----GtkBin
                           +----GtkToolItem
                                 +----GtkToolButton
                                 +----GtkSeparatorToolItem

Implemented Interfaces

GtkToolItem implements
 AtkImplementorIface,  GtkBuildable and  GtkActivatable.

Properties

  "is-important"             gboolean              : Read / Write
  "visible-horizontal"       gboolean              : Read / Write
  "visible-vertical"         gboolean              : Read / Write

Signals

  "create-menu-proxy"                              : Run Last
  "toolbar-reconfigured"                           : Run Last

Description

GtkToolItems are widgets that can appear on a toolbar. To
create a toolbar item that contain something else than a button, use
gtk_tool_item_new(). Use gtk_container_add() to add a child
widget to the tool item.

For toolbar items that contain buttons, see the GtkToolButton,
GtkToggleToolButton and GtkRadioToolButton classes.

See the GtkToolbar class for a description of the toolbar widget, and
GtkToolShell for a description of the tool shell interface.

Details

struct GtkToolItem

struct GtkToolItem;

The GtkToolItem struct contains only private data.
It should only be accessed through the functions described below.

gtk_tool_item_new ()

GtkToolItem *       gtk_tool_item_new                   (void);

Creates a new GtkToolItem

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Returns :

the new GtkToolItem

Since 2.4

gtk_tool_item_set_homogeneous ()

void                gtk_tool_item_set_homogeneous       (GtkToolItem *tool_item,
                                                         gboolean homogeneous);

Sets whether tool_item is to be allocated the same size as other
homogeneous items. The effect is that all homogeneous items will have
the same width as the widest of the items.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

homogeneous :

whether tool_item is the same size as other homogeneous items

Since 2.4

gtk_tool_item_get_homogeneous ()

gboolean            gtk_tool_item_get_homogeneous       (GtkToolItem *tool_item);

Returns whether tool_item is the same size as other homogeneous
items. See gtk_tool_item_set_homogeneous().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

TRUE if the item is the same size as other homogeneous
items.

Since 2.4

gtk_tool_item_set_expand ()

void                gtk_tool_item_set_expand            (GtkToolItem *tool_item,
                                                         gboolean expand);

Sets whether tool_item is allocated extra space when there
is more room on the toolbar then needed for the items. The
effect is that the item gets bigger when the toolbar gets bigger
and smaller when the toolbar gets smaller.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

expand :

Whether tool_item is allocated extra space

Since 2.4

gtk_tool_item_get_expand ()

gboolean            gtk_tool_item_get_expand            (GtkToolItem *tool_item);

Returns whether tool_item is allocated extra space.
See gtk_tool_item_set_expand().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

TRUE if tool_item is allocated extra space.

Since 2.4

gtk_tool_item_set_tooltip_text ()

void                gtk_tool_item_set_tooltip_text      (GtkToolItem *tool_item,
                                                         const gchar *text);

Sets the text to be displayed as tooltip on the item.
See gtk_widget_set_tooltip_text().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

text :

text to be used as tooltip for tool_item

Since 2.12

gtk_tool_item_set_tooltip_markup ()

void                gtk_tool_item_set_tooltip_markup    (GtkToolItem *tool_item,
                                                         const gchar *markup);

Sets the markup text to be displayed as tooltip on the item.
See gtk_widget_set_tooltip_markup().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

markup :

markup text to be used as tooltip for tool_item

Since 2.12

gtk_tool_item_set_use_drag_window ()

void                gtk_tool_item_set_use_drag_window   (GtkToolItem *tool_item,
                                                         gboolean use_drag_window);

Sets whether tool_item has a drag window. When TRUE the
toolitem can be used as a drag source through gtk_drag_source_set().
When tool_item has a drag window it will intercept all events,
even those that would otherwise be sent to a child of tool_item.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

use_drag_window :

Whether tool_item has a drag window.

Since 2.4

gtk_tool_item_get_use_drag_window ()

gboolean            gtk_tool_item_get_use_drag_window   (GtkToolItem *tool_item);

Returns whether tool_item has a drag window. See
gtk_tool_item_set_use_drag_window().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

TRUE if tool_item uses a drag window.

Since 2.4

gtk_tool_item_set_visible_horizontal ()

void                gtk_tool_item_set_visible_horizontal
                                                        (GtkToolItem *tool_item,
                                                         gboolean visible_horizontal);

Sets whether tool_item is visible when the toolbar is docked horizontally.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

visible_horizontal :

Whether tool_item is visible when in horizontal mode

Since 2.4

gtk_tool_item_get_visible_horizontal ()

gboolean            gtk_tool_item_get_visible_horizontal
                                                        (GtkToolItem *tool_item);

Returns whether the tool_item is visible on toolbars that are
docked horizontally.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

TRUE if tool_item is visible on toolbars that are
docked horizontally.

Since 2.4

gtk_tool_item_set_visible_vertical ()

void                gtk_tool_item_set_visible_vertical  (GtkToolItem *tool_item,
                                                         gboolean visible_vertical);

Sets whether tool_item is visible when the toolbar is docked
vertically. Some tool items, such as text entries, are too wide to be
useful on a vertically docked toolbar. If visible_vertical is FALSE
tool_item will not appear on toolbars that are docked vertically.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

visible_vertical :

whether tool_item is visible when the toolbar
is in vertical mode

Since 2.4

gtk_tool_item_get_visible_vertical ()

gboolean            gtk_tool_item_get_visible_vertical  (GtkToolItem *tool_item);

Returns whether tool_item is visible when the toolbar is docked vertically.
See gtk_tool_item_set_visible_vertical().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

Whether tool_item is visible when the toolbar is docked vertically

Since 2.4

gtk_tool_item_set_is_important ()

void                gtk_tool_item_set_is_important      (GtkToolItem *tool_item,
                                                         gboolean is_important);

Sets whether tool_item should be considered important. The GtkToolButton
class uses this property to determine whether to show or hide its label
when the toolbar style is GTK_TOOLBAR_BOTH_HORIZ. The result is that
only tool buttons with the "is_important" property set have labels, an
effect known as "priority text"

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

is_important :

whether the tool item should be considered important

Since 2.4

gtk_tool_item_get_is_important ()

gboolean            gtk_tool_item_get_is_important      (GtkToolItem *tool_item);

Returns whether tool_item is considered important. See
gtk_tool_item_set_is_important()

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

TRUE if tool_item is considered important.

Since 2.4

gtk_tool_item_get_ellipsize_mode ()

PangoEllipsizeMode  gtk_tool_item_get_ellipsize_mode    (GtkToolItem *tool_item);

Returns the ellipsize mode used for tool_item. Custom subclasses of
GtkToolItem should call this function to find out how text should
be ellipsized.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a PangoEllipsizeMode indicating how text in tool_item
should be ellipsized.

Since 2.20

gtk_tool_item_get_icon_size ()

GtkIconSize         gtk_tool_item_get_icon_size         (GtkToolItem *tool_item);

Returns the icon size used for tool_item. Custom subclasses of
GtkToolItem should call this function to find out what size icons
they should use.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a GtkIconSize indicating the icon size
used for tool_item. [<acronym title="Override the parsed C type with given type.">type</acronym> int]

Since 2.4

gtk_tool_item_get_orientation ()

GtkOrientation      gtk_tool_item_get_orientation       (GtkToolItem *tool_item);

Returns the orientation used for tool_item. Custom subclasses of
GtkToolItem should call this function to find out what size icons
they should use.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a GtkOrientation indicating the orientation
used for tool_item

Since 2.4

gtk_tool_item_get_toolbar_style ()

GtkToolbarStyle     gtk_tool_item_get_toolbar_style     (GtkToolItem *tool_item);

Returns the toolbar style used for tool_item. Custom subclasses of
GtkToolItem should call this function in the handler of the
GtkToolItem::toolbar_reconfigured signal to find out in what style
the toolbar is displayed and change themselves accordingly

Possibilities are:

 GTK_TOOLBAR_BOTH, meaning the tool item should show
both an icon and a label, stacked vertically

 GTK_TOOLBAR_ICONS, meaning the toolbar shows
only icons

 GTK_TOOLBAR_TEXT, meaning the tool item should only
show text

 GTK_TOOLBAR_BOTH_HORIZ, meaning the tool item should show
both an icon and a label, arranged horizontally

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

A GtkToolbarStyle indicating the toolbar style used
for tool_item.

Since 2.4

gtk_tool_item_get_relief_style ()

GtkReliefStyle      gtk_tool_item_get_relief_style      (GtkToolItem *tool_item);

Returns the relief style of tool_item. See gtk_button_set_relief().
Custom subclasses of GtkToolItem should call this function in the handler
of the "toolbar_reconfigured" signal to find out the
relief style of buttons.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a GtkReliefStyle indicating the relief style used
for tool_item.

Since 2.4

gtk_tool_item_get_text_alignment ()

gfloat              gtk_tool_item_get_text_alignment    (GtkToolItem *tool_item);

Returns the text alignment used for tool_item. Custom subclasses of
GtkToolItem should call this function to find out how text should
be aligned.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem:

Returns :

a gfloat indicating the horizontal text alignment
used for tool_item

Since 2.20

gtk_tool_item_get_text_orientation ()

GtkOrientation      gtk_tool_item_get_text_orientation  (GtkToolItem *tool_item);

Returns the text orientation used for tool_item. Custom subclasses of
GtkToolItem should call this function to find out how text should
be orientated.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a GtkOrientation indicating the text orientation
used for tool_item

Since 2.20

gtk_tool_item_retrieve_proxy_menu_item ()

GtkWidget *         gtk_tool_item_retrieve_proxy_menu_item
                                                        (GtkToolItem *tool_item);

Returns the GtkMenuItem that was last set by
gtk_tool_item_set_proxy_menu_item(), ie. the GtkMenuItem
that is going to appear in the overflow menu.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

The GtkMenuItem that is going to appear in the
overflow menu for tool_item. [<acronym title="Don't free data after the code is done.">transfer none</acronym>]

Since 2.4

gtk_tool_item_get_proxy_menu_item ()

GtkWidget *         gtk_tool_item_get_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id);

If menu_item_id matches the string passed to
gtk_tool_item_set_proxy_menu_item() return the corresponding GtkMenuItem.

Custom subclasses of GtkToolItem should use this function to
update their menu item when the GtkToolItem changes. That the
menu_item_ids must match ensures that a GtkToolItem
will not inadvertently change a menu item that they did not create.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

menu_item_id :

a string used to identify the menu item

Returns :

The GtkMenuItem passed to
gtk_tool_item_set_proxy_menu_item(), if the menu_item_ids
match. [<acronym title="Don't free data after the code is done.">transfer none</acronym>]

Since 2.4

gtk_tool_item_set_proxy_menu_item ()

void                gtk_tool_item_set_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id,
                                                         GtkWidget *menu_item);

Sets the GtkMenuItem used in the toolbar overflow menu. The
menu_item_id is used to identify the caller of this function and
should also be used with gtk_tool_item_get_proxy_menu_item().

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

menu_item_id :

a string used to identify menu_item

menu_item :

a GtkMenuItem to be used in the overflow menu

Since 2.4

gtk_tool_item_rebuild_menu ()

void                gtk_tool_item_rebuild_menu          (GtkToolItem *tool_item);

Calling this function signals to the toolbar that the
overflow menu item for tool_item has changed. If the
overflow menu is visible when this function it called,
the menu will be rebuilt.

The function must be called when the tool item changes what it
will do in response to the "create-menu-proxy" signal.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Since 2.6

gtk_tool_item_toolbar_reconfigured ()

void                gtk_tool_item_toolbar_reconfigured  (GtkToolItem *tool_item);

Emits the signal "toolbar_reconfigured" on tool_item.
GtkToolbar and other GtkToolShell implementations use this function
to notify children, when some aspect of their configuration changes.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Since 2.14

gtk_tool_item_get_text_size_group ()

GtkSizeGroup *      gtk_tool_item_get_text_size_group   (GtkToolItem *tool_item);

Returns the size group used for labels in tool_item.
Custom subclasses of GtkToolItem should call this function
and use the size group for labels.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

a GtkToolItem

Returns :

a GtkSizeGroup. [<acronym title="Don't free data after the code is done.">transfer none</acronym>]

Since 2.20

Property Details

The "is-important" property

  "is-important"             gboolean              : Read / Write

Whether the toolbar item is considered important. When TRUE, toolbar buttons show text in GTK_TOOLBAR_BOTH_HORIZ mode.

Default value: FALSE

The "visible-horizontal" property

  "visible-horizontal"       gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a horizontal orientation.

Default value: TRUE

The "visible-vertical" property

  "visible-vertical"         gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a vertical orientation.

Default value: TRUE

Signal Details

The "create-menu-proxy" signal

gboolean            user_function                      (GtkToolItem *tool_item,
                                                        gpointer     user_data)      : Run Last

This signal is emitted when the toolbar needs information from tool_item
about whether the item should appear in the toolbar overflow menu. In
response the tool item should either

call gtk_tool_item_set_proxy_menu_item() with a NULL
pointer and return TRUE to indicate that the item should not appear
in the overflow menu

 call gtk_tool_item_set_proxy_menu_item() with a new menu
item and return TRUE, or

 return FALSE to indicate that the signal was not
handled by the item. This means that
the item will not appear in the overflow menu unless a later handler
installs a menu item.

The toolbar may cache the result of this signal. When the tool item changes
how it will respond to this signal it must call gtk_tool_item_rebuild_menu()
to invalidate the cache and ensure that the toolbar rebuilds its overflow
menu.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

the object the signal was emitted on

user_data :

user data set when the signal handler was connected.

Returns :

TRUE if the signal was handled, FALSE if not

The "toolbar-reconfigured" signal

void                user_function                      (GtkToolItem *tool_item,
                                                        gpointer     user_data)      : Run Last

This signal is emitted when some property of the toolbar that the
item is a child of changes. For custom subclasses of GtkToolItem,
the default handler of this signal use the functions

gtk_tool_shell_get_orientation()

gtk_tool_shell_get_style()

gtk_tool_shell_get_icon_size()

gtk_tool_shell_get_relief_style()

to find out what the toolbar should look like and change
themselves accordingly.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

tool_item :

the object the signal was emitted on

user_data :

user data set when the signal handler was connected.

See Also

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

GtkToolbar

The toolbar widget

GtkToolButton

A subclass of GtkToolItem that displays buttons on
        the toolbar

GtkSeparatorToolItem

A subclass of GtkToolItem that separates groups of
        items on a toolbar

          Generated by GTK-Doc V1.18.1


text:
body{ background-color: #DDA;}

.postform input[type="text"] {
    margin-bottom: -1px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    }
.postform .middle{
    margin-bottom: -1px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    }
.postform input[type="email"] {
    margin-bottom: -1px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    }
.postform .bottom {
    margin-bottom: 10px !important;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    }
.postform .form-control{
    position: relative;
    font-size: 16px;
    height: auto;
    padding: 10px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    }

textarea .form-control{height: 300px;}

.blog-masthead { background-color: #66A32D; line-height: 1.6;}

.blog-nav-item {color: blue;}
.blog-nav .active{color: #FF0;}


text:
import os
import socketserver

class ForkingEchoRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        # Echo the back to the client
        data = self.request.recv(1024)
        cur_pid = os.getpid()
        response = b'%d: %s' % (cur_pid, data)
        self.request.send(response)
        return

class ForkingEchoServer(socketserver.ForkingMixIn,
                        socketserver.TCPServer,
                        ):
    pass

if __name__ == '__main__':
    import socket
    import threading

    address = ('localhost', 0)  # let the kernel assign a port
    server = ForkingEchoServer(address,
                               ForkingEchoRequestHandler)
    ip, port = server.server_address  # what port was assigned?

    t = threading.Thread(target=server.serve_forever)
    t.setDaemon(True)  # don't hang on exit
    t.start()
    print('Server loop running in process:', os.getpid())

    # Connect to the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))

    # Send the data
    message = 'Hello, world'.encode()
    print('Sending : {!r}'.format(message))
    len_sent = s.send(message)

    # Receive a response
    response = s.recv(1024)
    print('Received: {!r}'.format(response))

    # Clean up
    server.shutdown()
    s.close()
    server.socket.close()


text:
class FilePath;
class GURL;

namespace google_apis {
class DriveUploaderInterface;
}

namespace drive {

class DriveCache;
class DriveEntryProto;

namespace file_system {

class OperationObserver;

// This class encapsulates the drive Update function.  It is responsible for
// sending the request to the drive API, then updating the local state and
// metadata to reflect the new state.
class UpdateOperation {
 public:
  UpdateOperation(DriveCache* cache,
                  DriveResourceMetadata* metadata,
                  google_apis::DriveUploaderInterface* uploader,
                  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner,
                  OperationObserver* observer);
  virtual ~UpdateOperation();

  // Updates a file by the given |resource_id| on the Drive server by
  // uploading an updated version. Used for uploading dirty files. The file
  // should already be present in the cache.
  //
  // TODO(satorux): As of now, the function only handles files with the dirty
  // bit committed. We should eliminate the restriction. crbug.com/134558.
  //
  // Can only be called from UI thread.  |callback| must not be null.
  virtual void UpdateFileByResourceId(
      const std::string& resource_id,
      const FileOperationCallback& callback);

 private:
  // Part of UpdateFileByResourceId(). Called when
  // DriveResourceMetadata::GetEntryInfoByResourceId() is complete.
  // |callback| must not be null.
  void UpdateFileByEntryInfo(
      const FileOperationCallback& callback,
      DriveFileError error,
      const FilePath& drive_file_path,
      scoped_ptr<DriveEntryProto> entry_proto);

  // Part of UpdateFileByResourceId().
  // Called when DriveCache::GetFileOnUIThread() is completed for
  // UpdateFileByResourceId().
  // |callback| must not be null.
  void OnGetFileCompleteForUpdateFile(const FileOperationCallback& callback,
                                      const FilePath& drive_file_path,
                                      scoped_ptr<DriveEntryProto> entry_proto,
                                      DriveFileError error,
                                      const FilePath& cache_file_path);

  // Part of UpdateFileByResourceId().
  // Called when DriveUploader::UploadUpdatedFile() is completed for
  // UpdateFileByResourceId().
  // |callback| must not be null.
  void OnUpdatedFileUploaded(
      const FileOperationCallback& callback,
      google_apis::DriveUploadError error,
      const FilePath& gdata_path,
      const FilePath& file_path,
      scoped_ptr<google_apis::ResourceEntry> resource_entry);

  // Part of UpdateFileByResourceId().
  // |callback| must not be null.
  void OnUpdatedFileRefreshed(const FileOperationCallback& callback,
                              DriveFileError error,
                              const FilePath& drive_file_path,
                              scoped_ptr<DriveEntryProto> entry_proto);

  DriveCache* cache_;
  DriveResourceMetadata* metadata_;
  google_apis::DriveUploaderInterface* uploader_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  OperationObserver* observer_;

  // WeakPtrFactory bound to the UI thread.
  // Note: This should remain the last member so it'll be destroyed and
  // invalidate the weak pointers before any other members are destroyed.
  base::WeakPtrFactory<UpdateOperation> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(UpdateOperation);
};

}  // namespace file_system
}  // namespace drive

#endif  // CHROME_BROWSER_CHROMEOS_DRIVE_FILE_SYSTEM_UPDATE_OPERATION_H_


text: This repository contain my dotfiles.


text:
* [zynq7000](zynq7000): Firmware for Zynq-7000 projects
* [vivado_repo](vivado_repo): Vivado IP repository


text:
import os

import pytest

from factors.utils import get_excel_filepath

def test_get_xlswb():
    tablename = "AEG2011"
    excel_filepath = get_excel_filepath(tablename)
    assert "{tablename}.xlsx".format(tablename=tablename) in excel_filepath
    assert os.path.isfile(excel_filepath)
    # It will raise a ValueError if the excel sheet doesn't exists
    with pytest.raises(ValueError):
        get_excel_filepath("AEG")


text:
    Tweets by
        @kennyfraser


text:
.class public Lcom/mediatek/simservs/client/TerminatingIdentityPresentation;
.super Lcom/mediatek/simservs/client/SimservType;
.source "TerminatingIdentityPresentation.java"

# static fields
.field public static final NODE_NAME:Ljava/lang/String; = "terminating-identity-presentation"

# direct methods
.method public constructor <init>(Lcom/mediatek/xcap/client/uri/XcapUri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
    .locals 0
    .param p1, "documentUri"    # Lcom/mediatek/xcap/client/uri/XcapUri;
    .param p2, "parentUri"    # Ljava/lang/String;
    .param p3, "intendedId"    # Ljava/lang/String;
    .param p4, "username"    # Ljava/lang/String;
    .param p5, "password"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/mediatek/simservs/xcap/XcapException;,
            Ljavax/xml/parsers/ParserConfigurationException;
        }
    .end annotation

    .prologue
    .line 19
    invoke-direct/range {p0 .. p5}, Lcom/mediatek/simservs/client/SimservType;-><init>(Lcom/mediatek/xcap/client/uri/XcapUri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    .line 20
    return-void
.end method

# virtual methods
.method protected getNodeName()Ljava/lang/String;
    .locals 1

    .prologue
    .line 29
    const-string v0, "terminating-identity-presentation"

    return-object v0
.end method

.method public initServiceInstance(Lorg/w3c/dom/Document;)V
    .locals 0
    .param p1, "domDoc"    # Lorg/w3c/dom/Document;

    .prologue
    .line 25
    return-void
.end method


text:
'use strict';

//OS/Versions service used to communicate OS/Versions REST endpoints
angular.module('os_versions').factory('OsVersions', ['$resource',
        function($resource) {
                return $resource('os_versions/:os_versionId', {
                        categoryId: '@_id'
                });
        }
]);


text:
package fr.mantal.wcdl;

import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;

class Downloader
{
	private String baseUrl;
	private String startPath;
	private String localPath;

	private Property content;
	private Property next;
	private Property title;
	private Property skipCondition;
	private Property keepCondition;

	private String fileFormat = null;
	private boolean internal = false;

	private final static String userAgent = " wcdl/0.1 (+https://github.com/mantal/wcdl/issues)";

	static Downloader fromConfig(String path)
	{
		String file = null;
		try {
			file = FileUtils.readFileToString(new File(path), "utf-8");
		} catch (IOException e) {
			Error.Fatal(Error.FILE_ERROR, "Could not open config file: " + e.getMessage());
		}
		Downloader res = new Gson().fromJson(file, Downloader.class);
		res.localPath = Paths.get(path).getParent().toString() + File.separator;
		return res;
	}

	void download()
	{
		URL url;

		try
		{
			url = new URL(baseUrl + startPath);
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
			return;
		}

		Document document = null;
		int i = 1;

		do
		{
			try
			{
				document = Jsoup.connect(url.toString())
						.userAgent(userAgent)
						.get();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String titleString = title.get(document);

			if (titleString == null || titleString.trim().isEmpty())
			{
				Error.Fatal(Error.CONFIG_ERROR, "Error: title not found or all whitespace");
			}

			if (skipContent(document))
			{
				System.out.println("Skipping: '" + titleString + "' from " + url.toString());
				continue;
			}

			if (fileFormat == null)
				fileFormat = getFileFormat(document);

			File file = Paths.get(localPath + i + " - " + escapePath(titleString) + fileFormat).toFile();

			i++;
			if (fileExist(file))
			{
				System.out.println("Skipping: '" + titleString + "' from " + url.toString() + " (file exist)");
				continue;
			}

			System.out.println("Downloading: '" + titleString + "' from " + url.toString());

			copyContentToFile(document, file);

		} while((url = getNextUrl(document)) != null);
	}

	private boolean skipContent(Document document)
	{
		if (skipCondition != null && skipCondition.get(document) != null)
			return true;
		if (keepCondition != null && keepCondition.get(document) == null)
			return true;
		return false;
	}

	private String getFileFormat(Document document)
	{
		String contentUrl = content.get(document);

		return contentUrl.substring(contentUrl.lastIndexOf('.'), contentUrl.length());
	}

	private String escapePath(String path)
	{
		HashMap<Character, Character> replacementMap = new HashMap();

		replacementMap.put('/', '⁄');
		replacementMap.put('\\', '⃥');
		replacementMap.put('?', '︖');
		replacementMap.put(':', '︰');
		replacementMap.put('<', '‹');
		replacementMap.put('>', '›');
		replacementMap.put(':', '꞉');
		replacementMap.put('*', '∗');
		replacementMap.put('"', '"');
		replacementMap.put('|', '∣');

		for (HashMap.Entry<Character, Character> entry : replacementMap.entrySet())
			path = path.replace(entry.getKey(), entry.getValue());

		return path;
	}

	private boolean copyContentToFile(Document document, File file)
	{
		String selectedContent = content.get(document);

		if (selectedContent == null || selectedContent.isEmpty())
			Error.Fatal(Error.CONFIG_ERROR, "Content not found or empty");

		if (internal)
			return downloadFromHTML(selectedContent, file);

		selectedContent = fixUrl(selectedContent);

		return downloadFromURL(selectedContent, file);
	}

	private boolean downloadFromURL(String url, File file)
	{
		try
		{
			byte[] buffer = Jsoup.connect(url)
					.userAgent(userAgent)
					.ignoreContentType(true)
					.execute()
					.bodyAsBytes();
			FileUtils.writeByteArrayToFile(file, buffer);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
		return true;

	}

	private boolean downloadFromHTML(String content, File file)
	{
		try
		{
			FileUtils.writeStringToFile(file, content, "UTF-16");
		}
		catch (IOException e)
		{
			Error.Fatal(Error.FILE_ERROR, "Could not write content to file");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private URL getNextUrl(Document document)
	{
		String url = next.get(document);

		if (url == null || url.isEmpty())
			return null;

		url = fixUrl(url);
		try
		{
			return new URL(url);
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	private String fixUrl(String url)
	{
		if (!url.startsWith("http"))
		{
			if (url.charAt(0) == '/')
				url = url.substring(1);
			url = baseUrl + url;
		}
		return url;
	}

	private static boolean fileExist(File file)
	{
		return file.isFile() && file.exists();//todo check
	}
}


text:
<div #ringLay class="progress_ring_lay">
  <img #ring class="progress_ring" width="40px" height="40px" src="assets/icons/progress.gif" alt="progress">
</div>


text:
package org.apache.coyote.http2;

import org.apache.coyote.ActionCode;
import org.apache.coyote.Response;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;

/**
 * Tracks whether the stream is waiting for an allocation to the stream flow
 * control window, to the connection flow control window or not waiting for an
 * allocation and only issues allocation notifications when the stream is known
 * to be waiting for the notification.
 *
 * It is possible for a stream to be waiting for a connection allocation when
 * a stream allocation is made. Therefore this class tracks the type of
 * allocation that the stream is waiting for to ensure that notifications are
 * correctly triggered.
 *
 * With the implementation at the time of writing, it is not possible for a
 * stream to receive an unexpected connection notification as these are only
 * issues to streams in the backlog and a stream must be waiting for a
 * connection allocation in order to be placed on the backlog. However, as a
 * precaution, this class protects against unexpected connection notifications.
 *
 * It is important for asynchronous processing not to notify unless a
 * notification is expected else a dispatch will be performed unnecessarily
 * which may lead to unexpected results.
 *
 * A previous implementation used separate locks for the stream and connection
 * notifications. However, correct handling of allocation waiting requires
 * holding the stream lock when making the decision to wait. Therefore both
 * allocations need to wait on the Stream.
 */
class WindowAllocationManager {

    private static final Log log = LogFactory.getLog(WindowAllocationManager.class);
    private static final StringManager sm = StringManager.getManager(WindowAllocationManager.class);

    private static final int NONE = 0;
    private static final int STREAM = 1;
    private static final int CONNECTION = 2;

    private final Stream stream;

    private int waitingFor = NONE;

    WindowAllocationManager(Stream stream) {
        this.stream = stream;
    }

    void waitForStream(long timeout) throws InterruptedException {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("windowAllocationManager.waitFor.stream",
                    stream.getConnectionId(), stream.getIdAsString(), Long.toString(timeout)));
        }

        waitFor(STREAM, timeout);
    }

    void waitForConnection(long timeout) throws InterruptedException {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("windowAllocationManager.waitFor.connection",
                    stream.getConnectionId(), stream.getIdAsString(),
                    Integer.toString(stream.getConnectionAllocationRequested()), Long.toString(timeout)));
        }

        waitFor(CONNECTION, timeout);
    }

    void waitForStreamNonBlocking() {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("windowAllocationManager.waitForNonBlocking.stream",
                    stream.getConnectionId(), stream.getIdAsString()));
        }

        waitForNonBlocking(STREAM);
    }

    void waitForConnectionNonBlocking() {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("windowAllocationManager.waitForNonBlocking.connection",
                    stream.getConnectionId(), stream.getIdAsString()));
        }

        waitForNonBlocking(CONNECTION);
    }

    void notifyStream() {
        notify(STREAM);
    }

    void notifyConnection() {
        notify(CONNECTION);
    }

    void notifyAny() {
        notify(STREAM | CONNECTION);
    }

    boolean isWaitingForStream() {
        return isWaitingFor(STREAM);
    }

    boolean isWaitingForConnection() {
        return isWaitingFor(CONNECTION);
    }

    private boolean isWaitingFor(int waitTarget) {
        synchronized (stream) {
            return (waitingFor & waitTarget) > 0;
        }
    }

    private void waitFor(int waitTarget, long timeout) throws InterruptedException {
        synchronized (stream) {
            if (waitingFor != NONE) {
                throw new IllegalStateException(sm.getString("windowAllocationManager.waitFor.ise",
                        stream.getConnectionId(), stream.getIdAsString()));
            }

            waitingFor = waitTarget;

            if (timeout < 0) {
                stream.wait();
            } else {
                stream.wait(timeout);
            }
        }
    }

    private void waitForNonBlocking(int waitTarget) {
        synchronized (stream) {
            if (waitingFor == NONE) {
                waitingFor = waitTarget;
            } else if (waitingFor == waitTarget) {
                // NO-OP
                // Non-blocking post-processing may attempt to flush
            } else {
                throw new IllegalStateException(sm.getString("windowAllocationManager.waitFor.ise",
                        stream.getConnectionId(), stream.getIdAsString()));
            }

        }
    }

    private void notify(int notifyTarget) {

        synchronized (stream) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("windowAllocationManager.notify", stream.getConnectionId(),
                        stream.getIdAsString(), Integer.toString(waitingFor), Integer.toString(notifyTarget)));
            }

            if ((notifyTarget & waitingFor) > NONE) {
                // Reset this here so multiple notifies (possible with a
                // backlog containing multiple streams and small window updates)
                // are handled correctly (only the first should trigger a call
                // to stream.notify(). Additional notify() calls may trigger
                // unexpected timeouts.
                waitingFor = NONE;
                Response response = stream.getCoyoteResponse();
                if (response != null) {
                    if (response.getWriteListener() == null) {
                        // Blocking, so use notify to release StreamOutputBuffer
                        if (log.isDebugEnabled()) {
                            log.debug(sm.getString("windowAllocationManager.notified",
                                    stream.getConnectionId(), stream.getIdAsString()));
                        }
                        stream.notify();
                    } else {
                        // Non-blocking so dispatch
                        if (log.isDebugEnabled()) {
                            log.debug(sm.getString("windowAllocationManager.dispatched",
                                    stream.getConnectionId(), stream.getIdAsString()));
                        }
                        response.action(ActionCode.DISPATCH_WRITE, null);
                        // Need to explicitly execute dispatches on the StreamProcessor
                        // as this thread is being processed by an UpgradeProcessor
                        // which won't see this dispatch
                        response.action(ActionCode.DISPATCH_EXECUTE, null);
                    }
                }
            }
        }
    }
}


text:
import os

import tornado.web

from mopidy import config, ext

__version__ = '1.1.0'

class VoteRequestHandler(tornado.web.RequestHandler):

    def initialize(self, core, data, config):
        self.core = core
        self.data = data
        self.requiredVotes = config["party"]["votes_to_skip"]

    def _getip(self):
        return self.request.headers.get("X-Forwarded-For", self.request.remote_ip)

    def get(self):
        currentTrack = self.core.playback.get_current_track().get()
        if (currentTrack == None): return
        currentTrackURI = currentTrack.uri

        # If the current track is different to the one stored, clear votes
        if (currentTrackURI != self.data["track"]):
            self.data["track"] = currentTrackURI
            self.data["votes"] = []

        if (self._getip() in self.data["votes"]): # User has already voted
            self.write("You have already voted to skip this song =)")
        else: # Valid vote
            self.data["votes"].append(self._getip())
            if (len(self.data["votes"]) == self.requiredVotes):
                self.core.playback.next()
                self.write("Skipping...")
            else:
                self.write("You have voted to skip this song. ("+str(self.requiredVotes-len(self.data["votes"]))+" more votes needed)")

class AddRequestHandler(tornado.web.RequestHandler):

    def initialize(self, core, data, config):
        self.core = core
        self.data = data

    def _getip(self):
        return self.request.headers.get("X-Forwarded-For", self.request.remote_ip)

    def post(self):
        # when the last n tracks were added by the same user, abort.
        if self.data["queue"] and all([e == self._getip() for e in self.data["queue"]]):
            self.write("You have requested too many songs")
            self.set_status(403)
            return

        track_uri = self.request.body.decode()
        if not track_uri:
            self.set_status(400)
            return

        self.data["queue"].append(self._getip())
        self.data["queue"].pop(0)

        pos = 0
        if self.data["last"]:
            queue = self.core.tracklist.index(self.data["last"]).get() or 0
            current = self.core.tracklist.index().get() or 0
            pos = max(queue, current) # after lastly enqueued and after current track

        try:
            self.data["last"] = self.core.tracklist.add(uris=[track_uri], at_position=pos+1).get()[0]
        except:
            self.write("Unable to add track, please try again...")
            self.set_status(400)
            return

        self.core.tracklist.set_consume(True)
        if self.core.playback.get_state().get() == "stopped":
            self.core.playback.play()

def party_factory(config, core):
    data = {'track':"", 'votes':[], 'queue': [None] * config["party"]["max_tracks"], 'last':None}
    return [
    ('/vote', VoteRequestHandler, {'core': core, 'data':data, 'config':config}),
    ('/add', AddRequestHandler, {'core': core, 'data':data, 'config':config})
    ]

class Extension(ext.Extension):

    dist_name = 'Mopidy-Party'
    ext_name = 'party'
    version = __version__

    def get_default_config(self):
        conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf')
        return config.read(conf_file)

    def get_config_schema(self):
        schema = super(Extension, self).get_config_schema()
        schema['votes_to_skip'] = config.Integer(minimum=0)
        schema['max_tracks'] = config.Integer(minimum=0)
        return schema

    def setup(self, registry):
        registry.add('http:static', {
            'name': self.ext_name,
            'path': os.path.join(os.path.dirname(__file__), 'static'),
        })
        registry.add('http:app', {
            'name': self.ext_name,
            'factory': party_factory,
        })


text:
package tobleminer.minefight.util.io.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import tobleminer.minefight.util.io.StreamUtil;

public class FileUtil
{
	public static byte[] getBytes(File f)
	{
		try
		{
			FileInputStream fis = new FileInputStream(f);
			byte[] data = new byte[fis.available()];
			fis.read(data);
			fis.close();
			return data;
		}
		catch(Exception ex){}
		return null;
	}

	public static String getAllTextUTF8(File f)
	{
		try
		{
			BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(f),"UTF8"));
			String s = StreamUtil.getDataAsUTF8(br);
			br.close();
			return s;
		}
		catch(Exception ex){ex.printStackTrace();}
		return null;
	}

	public static void copyFromInputStreamToFileUtf8(File f, InputStream is) throws IOException
	{
		if(!f.exists())
		{
			f.createNewFile();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF8"));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"UTF8"));
		while(true)
		{
			int i = br.read();
			if(i < 0) break;
			bw.write(i);
		}
		br.close();
		bw.close();
	}
}


text:
<?php

namespace spec\Pkracer\JsonApiDocuments;

use PhpSpec\ObjectBehavior;
use Pkracer\JsonApiDocuments\Exceptions\InvalidDocumentResourceException;
use Pkracer\JsonApiDocuments\JsonApiResource;
use Pkracer\JsonApiDocuments\Resource;
use Prophecy\Argument;

class RelationshipSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('relationship');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType(\Pkracer\JsonApiDocuments\Interfaces\RelationshipInterface::class);
    }

    function it_can_override_the_name()
    {
        $this->name('new_name')->shouldReturn($this);
    }

    function it_can_fetch_the_relationship_name()
    {
        $this->name('new_name');
        $this->getName()->shouldReturn('new_name');
    }

    function it_can_be_constructed_with_a_data_resource()
    {
        $resource = new Resource('type', '1', ['property' => 'value']);
        $this->beConstructedWith('relationship', $resource);
        $this->getData()->shouldReturn($resource);
    }

    function it_can_be_constructed_with_a_collection_of_resources()
    {
        $resource1 = new Resource('relation', 1, ['property' => 'value']);
        $resource2 = new Resource('relation', 2, ['property' => 'value']);
        $this->beConstructedWith('relationship', [$resource1, $resource2]);
        $this->getData()->shouldReturn([$resource1, $resource2]);
    }

    function it_throws_an_exception_for_an_invalid_collection()
    {
        $resource1 = new Resource('relation', 1, ['property' => 'value']);
        $this->beConstructedWith('relationship', [$resource1, 'relation']);
        $this->shouldThrow(InvalidDocumentResourceException::class)->duringInstantiation();
    }

    function it_be_constructed_with_an_array_of_links()
    {
        $resource = new Resource('relation', 1, ['property' => 'value']);
        $this->beConstructedWith('relationship', $resource, ['self' => 'default/1/relationships/relation']);
        $this->getLinks()->shouldReturn(['self' => 'default/1/relationships/relation']);
    }

    function it_can_have_an_array_of_links_set_after_instantiation()
    {
        $resource = new Resource('relation', 1, ['property' => 'value']);
        $this->beConstructedWith('relationship', $resource);
        $this->links(['self' => 'default/1/relationships/relation'])->shouldReturn($this);
        $this->getLinks()->shouldReturn(['self' => 'default/1/relationships/relation']);
    }

    function it_can_be_constructed_with_an_array_of_meta_information()
    {
        $this->beConstructedWith('relationship', null, null, ['count'=> 100]);
        $this->getMeta()->shouldReturn(['count'=> 100]);
    }

    function it_can_have_an_array_of_meta_information_set_after_instantiation()
    {
        $this->beConstructedWith('relationship', null);
        $this->meta(['count'=> 100])->shouldReturn($this);
        $this->getMeta()->shouldReturn(['count'=> 100]);
    }

    function it_detects_an_item_relation()
    {
        $resource1 = new Resource('relation', 1, ['property' => 'value']);
        $this->beConstructedWith('relationship', $resource1);
        $this->isCollection()->shouldReturn(false);
    }

    function it_detects_a_collection_relation()
    {
        $resource1 = new Resource('relation', 1, ['property' => 'value']);
        $resource2 = new Resource('relation', 2, ['property' => 'value']);
        $this->beConstructedWith('relationship', [$resource1, $resource2]);
        $this->isCollection()->shouldReturn(true);
    }

    function it_can_be_converted_to_an_array()
    {
        $resource1 = new Resource('relation', 1);
        $resource2 = new Resource('relation', 2);
        $this->beConstructedWith(
            // relationship name
            'relationship',

            // json api resources
            [
                $resource1,
                $resource2
            ],

            // links
            [
                'self' => 'default/1/relationships/relation'
            ],

            // meta
            [
                'count'=> 100
            ]);

        $this->toArray()->shouldReturn([
            'relationship' => [
                'data' => [
                    [
                        'type' => 'relation',
                        'id' => '1'
                    ],
                    [
                        'type' => 'relation',
                        'id' => '2'
                    ]
                ],
                'links' => [
                    'self' => 'default/1/relationships/relation'
                ],
                'meta' => [
                    'count'=> 100
                ]
            ]
        ]);
    }
}


text:
package tk.djcrazy.MyCC98.template;

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

import tk.djcrazy.MyCC98.util.StreamUtils;
import tk.djcrazy.libCC98.data.PostContentEntity;
import tk.djcrazy.libCC98.util.DateFormatUtil;
import android.content.Context;
import android.util.Log;

import org.apache.commons.lang3.StringEscapeUtils;

public class DefaultPostContentTemplate implements PostcontentTemplate {

	private static PostcontentTemplate template = new DefaultPostContentTemplate();
	private static String mContent;
	private static String start;
	private static String middle ;
	private static String last ;
	public static PostcontentTemplate getInstance() {
		return template;
	}

	@Override
	public String genContent(Context context, List<PostContentEntity> list ,int page) {
		prepareContent(context);
		StringBuilder builder= new StringBuilder();
		builder.append(start);
		for (int i = 1; i < list.size(); i++) {
			PostContentEntity entity = list.get(i);
			builder.append(middle);
 			replaceVariable("${title}", builder, entity.getPostTitle());
			replaceVariable("${avatar}", builder,  entity.getUserAvatarLink());
			replaceVariable("${author}", builder,  entity.getUserName());
			replaceVariable("${floor}", builder, ((page - 1) * 10 + i)+" 楼");
			replaceVariable("${gender}", builder, entity.getGender().getName());
			replaceVariable("${time}", builder,DateFormatUtil.convertDateToString(entity.getPostTime(), true));
			replaceVariable("${face}", builder, entity.getPostFace());
			replaceVariable("${content}", builder, StringEscapeUtils.unescapeHtml4(entity.getPostContent())		);
			replaceVariable("${i}", builder,  String.valueOf(i));
 		}
		builder.append(last);
		return builder.toString();
	}

 	private void replaceVariable(String var, StringBuilder builder, String newContent) {
		int offset = builder.indexOf(var);
		builder.replace(offset, offset+var.length(), newContent);
	}

	/**
	 * @param context
	 */
	private void prepareContent(Context context) {
		if (mContent==null) {
			try {
				mContent = StreamUtils.Stream2String(context.getAssets().open("template/default_post_content_template.html"));
				start = mContent.substring(0, mContent.indexOf("$foreach$"));
				middle = mContent.substring(mContent.indexOf("$foreach$")+9, mContent.indexOf("$endeach$"));
				last = mContent.substring(mContent.indexOf("$endeach$")+9);
			} catch (IOException e) {
				e.printStackTrace();
	 			throw new RuntimeException(e.getMessage());
			}

		}
	}
}


text:
public class NumberOfWays {
    public static int numberOfWays(int m, int n) {
        return numberOfWaysCounter(m - 1, n - 1, new int[m][n]);
    }

    private static numberOfWaysCounter(int row, int col, int[][] record) {
        if (row == 0 || col == 0) {
            return 1;
        }
        if (record[row][col] == 0) {
            int waysUp = row == 0 ? 0 : numberOfWaysCounter(row - 1, col, record);
            int waysLeft = col == 0 ? 0 : numberOfWaysCounter(row, col - 1, record);
            record[row][col] = waysUp + waysLeft;
        }
        return record[row][col];
    }
}


text:
package banking;

import banking.model.Identifiable;

import java.math.BigDecimal;
import java.util.UUID;

public class Account implements Identifiable {

  private UUID id = UUID.randomUUID();
  private Money balance;

  public Account(Money startingBalance) {
    balance = startingBalance;
  }

  public Account() {
    this(new Money(BigDecimal.ZERO));
  }

  @Override
  public UUID getId() {
    return id;
  }

  public Money getBalance() {
    return balance;
  }

  public void deposit(Money amount) {
    balance = balance.plus(amount);
  }

  public void withdraw(Money amount) {
    balance = balance.minus(amount);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2" >

    <Button
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="Button1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="Button2" />

</LinearLayout>


text:
package de.bytefish.elasticutils.elasticsearch2.client.bulk.options;

import de.bytefish.elasticutils.elasticsearch2.client.bulk.options.BulkProcessingOptions;
import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.junit.Assert;
import org.junit.Test;

public class BulkProcessingOptionsTest {

    @Test
    public void get_methods_return_correct_values_when_initialized() {

        BulkProcessingOptions options = new BulkProcessingOptions("Name", 1, 2, new ByteSizeValue(10), new TimeValue(10), BackoffPolicy.exponentialBackoff());

        Assert.assertEquals("Name", options.getName());
        Assert.assertEquals(1, options.getConcurrentRequests());
        Assert.assertEquals(2, options.getBulkActions());
        Assert.assertEquals(10, options.getBulkSize().bytes());
        Assert.assertEquals(10, options.getFlushInterval().getMillis());
        Assert.assertEquals(BackoffPolicy.exponentialBackoff().getClass(), options.getBackoffPolicy().getClass());
    }
}


text:
package net.jimblackler.yourphotoswatch;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.webkit.WebView;

import java.io.IOException;
import java.io.InputStream;

public class AboutActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.about_activity);

    WebView webView = (WebView) findViewById(R.id.webView1);

    try {
      InputStream summary = getAssets().open("about.html");
      String text = convertStreamToString(summary);
      PackageManager manager = getPackageManager();
      PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
      text = text.replace("$app", getResources().getText(
          getResources().getIdentifier("app_name", "string", getPackageName())));
      text = text.replace("$ver", info.versionName);
      webView.loadData(text, "text/html", null);
    } catch (IOException | PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
  }

  static String convertStreamToString(InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
  }

}


text:
var fs = require('fs');
var vm = require('vm');
var path = require('path');

// Initializing FOAM_BOOT_DIR.
global.FOAM_BOOT_DIR = __dirname;

// Needed so that scripts run through runInThisContext can require other nodejs
// modules.
global.require = require;

var foamLoader = fs.readFileSync(
    path.join(global.FOAM_BOOT_DIR, 'FOAMContextLoader.js'));
vm.runInThisContext(foamLoader);


text:
package org.jmxdatamart.Extractor;

import java.util.*;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.slf4j.LoggerFactory;

/**
 * This class contains data related to any MBean such as name, alias and its
 * attributes
 * @author Binh Tran <mynameisbinh@gmail.com>
 */
public class MBeanData {
    private String name;
    private String alias;
    private List<Attribute> attributes;
    private boolean enable;
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @return the name
     */

    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the alias
     */

    public String getAlias() {
        return alias;
    }

    /**
     * @param alias the alias to set
     */
    public void setAlias(String alias) {
        this.alias = alias;
    }

    /**
     * @return the attributes
     */
    public List<Attribute> getAttributes() {
        return attributes;
    }

    /**
     * @param attributes the attributes to set
     */
    public void setAttributes(List<Attribute> attributes) {
        this.attributes = attributes;
    }

    public MBeanData(String name, String alias, List<Attribute> attributes, boolean enable) {
        this.name = name;
        this.alias = alias;
        this.attributes = attributes;
        this.enable = enable;
    }

    public MBeanData() {
        name = "";
        alias = "";
        enable = true;
        attributes = new ArrayList<Attribute>();
    }

    @Override
    public String toString() {
        String nl = System.getProperty("line.separator");
        return  this.name + " -> " + this.alias + nl +
                attributes.toString() + nl;
    }

    /**
     * @return the enable
     */

    public boolean isEnable() {
        return enable;
    }

    /**
     * @param enable the enable to set
     */
    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    /**
     * Check if the MBeanData object's alias is correctly formated
     * @return true if correctly formated, false if not
     */
    // Task 3041
    public boolean checkForValidAlias() {
        for (Attribute a : this.attributes) {
            if (!a.checkForValidAlias()) {
                return false;
            }
        }

        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Check if the MBeanData represent a pattern or a single MBean
     * @return true if MBeanData's name is a valid JMX pattern, false if not
     * @throws MalformedObjectNameException if MBeanData's name is not a valid
     * ObjectName's name
     */
    public boolean isPattern() {
      try {
        return (new ObjectName(this.name)).isPattern();
      } catch (MalformedObjectNameException ex) {
        logger.error("MBean name malformed in " + this.name, ex);
        return false;
      }
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + (this.alias != null ? this.alias.hashCode() : 0);
        hash = 53 * hash + (this.attributes != null ? this.attributes.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final MBeanData other = (MBeanData) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if ((this.alias == null) ? (other.alias != null) : !this.alias.equals(other.alias)) {
            return false;
        }
        if (this.attributes != other.attributes && (this.attributes == null || !this.attributes.equals(other.attributes))) {
            return false;
        }
        return true;
    }

}