text:
Formats: Manifest Files

Every extension, installable web app, and theme has a
JSON-formatted manifest file,
named manifest.json,
that provides important information.

 Field summary

The following code shows the supported manifest fields,
with links to the page that discusses each field.
The only fields that are always required
are name and version.

{
  // Required
  "name": "My Extension",
  "version": "versionString",
  "manifest_version": 2,

  // Recommended
  "description": "A plain text description",
  "icons": { ... },
  "default_locale": "en",

  // Pick one (or none)
  "browser_action": {...},
  "page_action": {...},
  "theme": {...},
  "app": {...},

  // Add any of these that you need
  "background": {"persistent": false, ...},
  "background": {"persistent": true, ...},
  "chrome_url_overrides": {...},
  "content_scripts": [...],
  "content_security_policy": "policyString",
  "file_browser_handlers": [...],
  "homepage_url": "http://path/to/homepage",
  "incognito": "spanning" or "split",
  "intents": {...}
  "key": "publicKey",
  "minimum_chrome_version": "versionString",

  "nacl_modules": [...],
  "offline_enabled": true,
  "omnibox": { "keyword": "aString" },
  "options_page": "aFile.html",
  "permissions": [...],
  "plugins": [...],
  "requirements": {...},
  "update_url": "http://path/to/updateInfo.xml",
  "web_accessible_resources": [...],
  "sandbox": [...]
}

Field details

This section covers fields that aren't described in another page.
For a complete list of fields,
with links to where they're described in detail,
see the Field summary.

app

Used by packaged apps
to specify the app's background scripts.
Also used by hosted apps
to specify the URLs that the app uses.

default_locale

Specifies the subdirectory of _locales
that contains the default strings for this extension.
This field is required in extensions
that have a _locales directory;
it must be absent in extensions
that have no _locales directory.
For details, see
Internationalization.

description

A plain text string
(no HTML or other formatting;
no more than 132 characters)
that describes the extension.
The description should be suitable for both
the browser's extension management UI
and the Chrome Web Store.
You can specify locale-specific strings for this field;
see Internationalization for details.

homepage_url

The URL of the homepage for this extension. The extensions management page (chrome://extensions)
will contain a link to this URL.  This field is particularly useful if you
host the extension on your own site. If you distribute your
extension using the Chrome Web Store,
the homepage URL defaults to the extension's own page.

icons

One or more icons that represent the extension, app, or theme.
You should always provide a 128x128 icon;
it's used during installation and by the Chrome Web Store.
Extensions should also provide a 48x48 icon,
which is used in the extensions management page
(chrome://extensions).
You can also specify a 16x16 icon to be used as the favicon
for an extension's pages.
The 16x16 icon is also displayed in the experimental extension
infobar
feature.

Icons should generally be in PNG format,
because PNG has the best support for transparency.
They can, however, be in any format supported by WebKit,
including BMP, GIF, ICO, and JPEG.
Here's an example of specifying the icons:

"icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },

Important:
Use only the documented icon sizes.

You might notice that Chrome sometimes resizes these icons down to smaller
sizes. For example, the install dialog might shrink the 128-pixel
icon down to 69 pixels.

However, the details of
Chrome's UI may change between versions, and these changes assume that
developers are using the documented sizes. If you use other sizes,
your icon may look bad in future versions of the browser.

If you upload your extension, app, or theme using the
Chrome Developer Dashboard,
you'll need to upload additional images,
including at least one screenshot of your extension.
For more information,
see the
Chrome Web Store
developer documentation.

incognito

Either "spanning" or "split", to specify how this extension will
behave if allowed to run in incognito mode.

The default for extensions is "spanning", which means that the extension
will run in a single shared process. Any events or messages from an incognito
tab will be sent to the shared process, with an incognito flag
indicating where it came from. Because incognito tabs cannot use this shared
process, an extension using the "spanning" incognito mode will not be able to
load pages from its extension package into the main frame of an incognito tab.

The default for installable web apps is "split",
which means that all app pages in
an incognito window will run in their own incognito process. If the app or extension contains a background page, that will also run in the incognito process.
This incognito process runs along side the regular process, but has a separate
memory-only cookie store. Each process sees events and messages only from its
own context (for example, the incognito process will see only incognito tab updates).
The processes are unable to communicate with each other.

As a rule of thumb, if your extension or app needs to load a tab in an incognito browser, use
split incognito behavior. If your extension or app needs to be logged
into a remote server or persist settings locally, use spanning
incognito behavior.

intents

A dictionary that specifies all intent handlers provided by this extension or app. Each key in the dictionary specifies an action verb that is handled by this extension. The following example specifies two handlers for the action verb "http://webintents.org/share".

{
  "name": "test",
  "version": "1",
  "intents": {
    "http://webintents.org/share": [
      {
        "type": ["text/uri-list"],
        "href": "/services/sharelink.html",
        "title" : "Sample Link Sharing Intent",
        "disposition" : "inline"
      },
      {
        "type": ["image/*"],
        "href": "/services/shareimage.html",
        "title" : "Sample Image Sharing Intent",
        "disposition" : "window"
      }
    ]
  }
}

The value of "type" is an array of mime types that is supported by this handler. The "href" indicates the URL of the page that handles the intent. For hosted apps, these URLs must be within the allowed set of URLs. For extensions, all URLs are inside the extension and considered relative to the extension root URL.

The "title" is displayed in the intent picker UI when the user initiates the action specific to the handler.

The "disposition" is either "inline" or "window". Intents with "window" disposition will open a new tab when invoked. Intents with "inline" disposition will be displayed inside the intent picker when invoked.

For more information on intents, refer to the Web Intents specification and webintents.org.

Handling content types via intents

Web Intents can be registered as content type viewers. To do that, the action verb must be "http://webintents.org/view", and the content type must be a white-listed MIME type.

    Whitelisted MIME types

application/rss+xml

application/atom+xml

key

This value can be used to control
the unique ID of an extension, app, or theme when
it is loaded during development.

Note: You don't usually need to
use this value. Instead, write your
code so that the key value doesn't matter
by using relative paths
and chrome.extension.getURL().

To get a suitable key value, first
install your extension from a .crx file
(you may need to
upload your extension
or package it manually).
Then, in your
user
data directory, look in the file
Default/Extensions/<extensionId>/<versionString>/manifest.json.
You will see the key value filled in there.

minimum_chrome_version

The version of Chrome that your extension, app, or theme requires, if any.
The format for this string is the same as for the
version field.

name

A short, plain text string
(no more than 45 characters)
that identifies the extension.
The name is used in the install dialog,
extension management UI,
and the store.
You can specify locale-specific strings for this field;
see Internationalization for details.

nacl_modules

One or more mappings from MIME types to the Native Client module
that handles each type.
For example, the bold code in the following snippet
registers a Native Client module as the content handler
for the OpenOffice spreadsheet MIME type.

{
  "name": "Native Client OpenOffice Spreadsheet Viewer",
  "version": "0.1",
  "description": "Open OpenOffice spreadsheets, right in your browser.",
  "nacl_modules": [{
    "path": "OpenOfficeViewer.nmf",
    "mime_type": "application/vnd.oasis.opendocument.spreadsheet"
  }]
}

The value of "path" is the location of a Native Client manifest
(a .nmf file)
within the extension directory.
For more information on Native Client and .nmf files, see the
Native Client Technical Overview.

Each MIME type can be associated with only one .nmf file,
but a single .nmf file might handle multiple MIME types.
The following example shows an extension
with two .nmf files
that handle three MIME types.

{
  "name": "Spreadsheet Viewer",
  "version": "0.1",
  "description": "Open OpenOffice and Excel spreadsheets, right in your browser.",
  "nacl_modules": [{
    "path": "OpenOfficeViewer.nmf",
    "mime_type": "application/vnd.oasis.opendocument.spreadsheet"
  },
  {
    "path": "OpenOfficeViewer.nmf",
    "mime_type": "application/vnd.oasis.opendocument.spreadsheet-template"
  },
  {
    "path": "ExcelViewer.nmf",
    "mime_type": "application/excel"
  }]
}

Note:
You can use Native Client modules in extensions
without specifying "nacl_modules".
Use "nacl_modules" only if you want the browser
to use your Native Client module
to display a particular type of content.

offline_enabled

Whether the app or extension is expected to work offline. When Chrome detects
that it is offline, apps with this field set to true will be highlighted
on the New Tab page.

requirements

Technologies required by the app or extension.
Hosting sites such as the Chrome Web Store may use this list
to dissuade users from installing apps or extensions
that will not work on their computer.
Supported requirements currently include "3D" and "plugins";
additional requirements checks may be added in the future.

The "3D" requirement denotes GPU hardware acceleration.
The "webgl" requirement refers to the
WebGL API.
For more information on Chrome 3D graphics support,
see the help article on
WebGL and 3D graphics.
You can list the 3D-related features your app requires,
as demonstrated in the following example:

"requirements": {
  "3D": {
    "features": ["webgl"]
  }
}

The "plugins" requirement indicates
if an app or extension requires NPAPI to run.
This requirement is enabled by default
when the manifest includes the
"plugins" field.
For apps and extensions that still work when plugins aren't available,
you can disable this requirement
by setting NPAPI to false.
You can also enable this requirement manually,
by setting NPAPI to true,
as shown in this example:

"requirements": {
  "plugins": {
    "npapi": true
  }
}

version

One to four dot-separated integers
identifying the version of this extension.
A couple of rules apply to the integers:
they must be between 0 and 65535, inclusive,
and non-zero integers can't start with 0.
For example, 99999 and 032 are both invalid.

Here are some examples of valid versions:

 "version": "1"

 "version": "1.0"

 "version": "2.10.2"

 "version": "3.1.2.4567"

The autoupdate system compares versions
to determine whether an installed extension
needs to be updated.
If the published extension has a newer version string
than the installed extension,
then the extension is automatically updated.

The comparison starts with the leftmost integers.
If those integers are equal,
the integers to the right are compared,
and so on.
For example, 1.2.0 is a newer version than 1.1.9.9999.

A missing integer is equal to zero.
For example, 1.1.9.9999 is newer than 1.1.

For more information, see
Autoupdating.

manifest_version

One integer specifying the version of the manifest file format your package
requires. As of Chrome 18, developers should specify 2
(without quotes) to use the format as described by this document:

"manifest_version": 2

Consider manifest version 1 deprecated as of Chrome 18. Version 2 is
not yet required, but we will, at some point in the not-too-distant
future, stop supporting packages using deprecated manifest versions. Extensions,
applications, and themes that aren't ready to make the jump to the new manifest
version in Chrome 18 can either explicitly specify version 1, or
leave the key off entirely.

The changes between version 1 and version 2 of the manifest file format are
described in detail in the
manifest_version documentation.

  Setting manifest_version 2 in Chrome 17 or lower is not
  recommended. If your extension needs to work in older versions of Chrome,
  stick with version 1 for the moment. We'll give you ample warning before
  version 1 stops working.

web_accessible_resources

An array of strings specifying the paths (relative to the package root) of
packaged resources that are expected to be usable in the context of a web page.
For example, an extension that injects a content script with the intention of
building up some custom interface for example.com would whitelist
any resources that interface requires (images, icons, stylesheets, scripts,
etc.) as follows:

{
  ...
  "web_accessible_resources": [
    "images/my-awesome-image1.png",
    "images/my-amazing-icon1.png",
    "style/double-rainbow.css",
    "script/double-rainbow.js"
  ],
  ...
}

These resources would then be available in a webpage via the URL
chrome-extension://[PACKAGE ID]/[PATH], which can be generated with
the
  chrome.extension.getURL
 method. Whitelisted resources are served with appropriate
CORS headers, so they're available via
mechanisms like XHR.

Injected content scripts themselves do not need to be whitelisted.

Prior to manifest version 2 all resources within an extension could be accessed
from any page on the web. This allowed a malicious website to
fingerprint the
extensions that a user has installed or exploit vulnerabilities (for example
XSS bugs)within
installed extensions. Limiting availability to only resources which are
explicitly intended to be web accessible serves to both minimize the available
attack surface and protect the privacy of users.

Default Availability

Resources inside of packages using manifest_version
2 or above are blocked by default, and must be whitelisted
for use via this property.

Resources inside of packages using manifest_version 1 are available
by default, but if you do set this property, then it will be treated as
a complete list of all whitelisted resources. Resources not listed will be
blocked.

sandbox

Defines an collection of app or extension pages that are to be served
in a sandboxed unique origin, and optionally a Content Security Policy to use
with them. Being in a sandbox has two implications:

A sandboxed page will not have access to extension or app APIs, or
direct access to non-sandboxed pages (it may communicate with them via
postMessage()).

A sandboxed page is not subject to the
  Content Security Policy
  (CSP) used by the rest of the app or extension (it has its own separate
  CSP value). This means that, for example, it can use inline script and
  eval.

For example, here's how to specify that two extension pages are to be
  served in a sandbox with a custom CSP:

{
  ...
  "sandbox": {
    "pages": [
      "page1.html",
      "directory/page2.html"
    ]
    // content_security_policy is optional.
    "content_security_policy":
        "sandbox allow-scripts; script-src https://www.google.com"
  ],
  ...
}

  If not specified, the default content_security_policy value is
  sandbox allow-scripts allow-forms. You can specify your CSP
  value to restrict the sandbox even further, but it must have the sandbox
  directive and may not have the allow-same-origin token (see
  the
  HTML5 specification for possible sandbox tokens).

Note that you only need to list pages that you expected to be loaded in
windows or frames. Resources used by sandboxed pages (e.g. stylesheets or
JavaScript source files) do not need to appear in the
sandboxed_page list, they will use the sandbox of the page
that embeds them.

"Using eval in Chrome Extensions. Safely."
goes into more detail about implementing a sandboxing workflow that enables use
of libraries that would otherwise have issues executing under extension's
default Content Security
Policy.

Sandboxed page may only be specified when using
manifest_version 2 or above.


text:
package org.kie.workbench.common.stunner.bpmn.client.marshall.converters.tostunner;

import java.util.Collections;

import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.eclipse.bpmn2.di.BPMNPlane;
import org.eclipse.bpmn2.di.BPMNShape;
import org.eclipse.emf.common.util.ECollections;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.BPMNDefinitionSet;
import org.kie.workbench.common.stunner.bpmn.BPMNTestDefinitionFactory;
import org.kie.workbench.common.stunner.bpmn.client.marshall.converters.TypedFactoryManager;
import org.kie.workbench.common.stunner.bpmn.client.marshall.converters.tostunner.properties.BasePropertyReader;
import org.kie.workbench.common.stunner.bpmn.definition.BPMNDiagramImpl;
import org.kie.workbench.common.stunner.bpmn.definition.BPMNViewDefinition;
import org.kie.workbench.common.stunner.bpmn.definition.EmbeddedSubprocess;
import org.kie.workbench.common.stunner.core.backend.StunnerTestingGraphBackendAPI;
import org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.kie.workbench.common.stunner.core.diagram.MetadataImpl;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.Bounds;
import org.kie.workbench.common.stunner.core.graph.content.definition.DefinitionSet;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.content.view.ViewImpl;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.kie.workbench.common.stunner.bpmn.client.marshall.converters.fromstunner.Factories.dc;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.Silent.class)
public class GraphBuilderTest {

    private static final String BPMN_ID = BindableAdapterUtils.getDefinitionSetId(BPMNDefinitionSet.class);
    private static final String DIAGRAM_UUID = "DIAGRAM_UUID";
    private static final String SUBPROCESS1_ID = "SUBPROCESS1_ID";
    private static final String SUBPROCESS2_ID = "SUBPROCESS2_ID";
    private static final String SUBPROCESS3_ID = "SUBPROCESS3_ID";

    private DefinitionResolver definitionResolver;

    @Mock
    private org.eclipse.bpmn2.Process process;

    @Mock
    private BPMNDiagram diagram;

    @Mock
    private BPMNPlane plane;

    @Mock
    private Definitions definitions;

    private Graph<DefinitionSet, Node> graph;

    private GraphBuilder graphBuilder;

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() throws Exception {
        when(diagram.getPlane()).thenReturn(plane);
        when(definitions.getId()).thenReturn(DIAGRAM_UUID);
        when(definitions.getRootElements()).thenReturn(ECollections.singletonEList(process));
        when(definitions.getDiagrams()).thenReturn(ECollections.singletonEList(diagram));
        when(definitions.getRelationships()).thenReturn(ECollections.emptyEList());
        definitionResolver = new DefinitionResolver(definitions, Collections.emptyList());
        StunnerTestingGraphBackendAPI api = StunnerTestingGraphBackendAPI.build(BPMNDefinitionSet.class,
                                                                                new BPMNTestDefinitionFactory());
        TypedFactoryManager typedFactoryManager = new TypedFactoryManager(api.getFactoryManager());
        Metadata metadata =
                new MetadataImpl.MetadataImplBuilder(
                        BindableAdapterUtils.getDefinitionSetId(BPMNDefinitionSet.class)).build();
        Diagram<Graph<DefinitionSet, Node>, Metadata> diagram =
                api.getFactoryManager().newDiagram(
                        definitionResolver.getDefinitions().getId(),
                        BPMN_ID,
                        metadata);
        graph = diagram.getGraph();
        graphBuilder = new GraphBuilder(graph,
                                        api.getDefinitionManager(),
                                        typedFactoryManager,
                                        api.getRuleManager(),
                                        api.commandFactory,
                                        api.commandManager);
    }

    @Test
    public void testBoundsCalculation() {
        //subprocess1
        double subprocess1X = 10;
        double subprocess1Y = 10;
        double subprocess1Width = 100;
        double subprocess1Height = 200;
        EmbeddedSubprocess subprocess1Definition = mock(EmbeddedSubprocess.class);
        Node<? extends View<? extends BPMNViewDefinition>, ?> subprocess1 = mockNode(subprocess1Definition,
                                                                                subprocess1X,
                                                                                subprocess1Y,
                                                                                subprocess1Width,
                                                                                subprocess1Height);
        when(subprocess1.getUUID()).thenReturn(SUBPROCESS1_ID);
        BpmnNode subprocess1Node = mockBpmnNode(subprocess1);

        //subprocess2
        double subprocess2X = 20;
        double subprocess2Y = 20;
        double subprocess2Width = 70;
        double subprocess2Height = 170;
        EmbeddedSubprocess subprocess2Definition = mock(EmbeddedSubprocess.class);
        //subprocess1 -> subprocess2
        //absolute coordinates in eclipse model
        Node<? extends View<? extends BPMNViewDefinition>, ?> subprocess2 = mockNode(subprocess2Definition,
                                                                                subprocess1X + subprocess2X,
                                                                                subprocess1Y + subprocess2Y,
                                                                                subprocess2Width,
                                                                                subprocess2Height);
        when(subprocess2.getUUID()).thenReturn(SUBPROCESS2_ID);
        BpmnNode subprocess2Node = mockBpmnNode(subprocess2);

        //subprocess3
        double subprocess3X = 30;
        double subprocess3Y = 30;
        double subprocess3Width = 30;
        double subprocess3Height = 120;
        EmbeddedSubprocess subprocess3Definition = mock(EmbeddedSubprocess.class);
        //subprocess1 -> subprocess2 -> subprocess3
        //absolute coordinates in eclipse model
        Node<? extends View<? extends BPMNViewDefinition>, ?> subprocess3 = mockNode(subprocess3Definition,
                                                                                subprocess1X + subprocess2X + subprocess3X,
                                                                                subprocess1Y + subprocess2Y + subprocess3Y,
                                                                                subprocess3Width, subprocess3Height);
        when(subprocess3.getUUID()).thenReturn(SUBPROCESS3_ID);
        BpmnNode subprocess3Node = mockBpmnNode(subprocess3);

        //subprocess1 -> subprocess2 -> subprocess3
        Node<? extends View<? extends BPMNViewDefinition>, ?> rootDiagram = mockNode(mock(BPMNDiagramImpl.class), 0, 0, 1000, 1000);
        when(rootDiagram.getUUID()).thenReturn(DIAGRAM_UUID);
        BpmnNode rootNode = mockBpmnNode(rootDiagram);

        subprocess1Node.setParent(rootNode);
        subprocess2Node.setParent(subprocess1Node);
        subprocess3Node.setParent(subprocess2Node);
        graphBuilder.buildGraph(rootNode);

        //stunner model must have the relative coordinates
        assertNodePosition(SUBPROCESS1_ID, subprocess1X, subprocess1Y);
        assertNodePosition(SUBPROCESS2_ID, subprocess2X, subprocess2Y);
        assertNodePosition(SUBPROCESS3_ID, subprocess3X, subprocess3Y);
    }

    @SuppressWarnings("unchecked")
    private void assertNodePosition(String uuid, double x, double y) {
        Node<? extends View<? extends BPMNViewDefinition>, ?> node = graph.getNode(uuid);
        assertNotNull(node);
        Bounds bounds = node.getContent().getBounds();
        assertEquals(x, bounds.getUpperLeft().getX(), 0);
        assertEquals(y, bounds.getUpperLeft().getY(), 0);
    }

    public static BpmnNode mockBpmnNode(Node<? extends View<? extends BPMNViewDefinition>, ?> node) {
        Bounds nodeBounds = node.getContent().getBounds();
        BasePropertyReader propertyReader = mock(BasePropertyReader.class);
        BPMNShape shape = mock(BPMNShape.class);
        org.eclipse.dd.dc.Bounds bounds = dc.createBounds();
        bounds.setX(nodeBounds.getUpperLeft().getX().floatValue());
        bounds.setY(nodeBounds.getUpperLeft().getY().floatValue());
        bounds.setWidth(Double.valueOf(nodeBounds.getWidth()).floatValue());
        bounds.setHeight(Double.valueOf(nodeBounds.getHeight()).floatValue());
        Bounds readerBounds = Bounds.create(nodeBounds.getUpperLeft().getX(),
                                            nodeBounds.getUpperLeft().getY(),
                                            nodeBounds.getLowerRight().getX(),
                                            nodeBounds.getLowerRight().getY());
        when(propertyReader.getBounds()).thenReturn(readerBounds);
        when(shape.getBounds()).thenReturn(bounds);
        when(propertyReader.getShape()).thenReturn(shape);
        return BpmnNode.of(node, propertyReader);
    }

    public static Node<? extends View<? extends BPMNViewDefinition>, ?> mockNode(BPMNViewDefinition definition, double x, double y, double width, double height) {
        return mockNode(definition, Bounds.create(x, y, x + width, y + height));
    }

    @SuppressWarnings("unchecked")
    private static Node<? extends View<? extends BPMNViewDefinition>, ?> mockNode(BPMNViewDefinition definition, Bounds bounds) {
        Node<View<BPMNViewDefinition>, ?> node = mock(Node.class);
        View<BPMNViewDefinition> view = new ViewImpl<>(definition, bounds);
        when(node.getContent()).thenReturn(view);
        return node;
    }
}

redpajama_set_name: RedPajamaGithub


text:
MeanStack Multivision Demo
--------------------------
This code in this project is experimental and for study purposes.

(It is my step-by-step implementation of the https://github.com/joeeames/multivision-demo course by Joe Eames.
Can be seen in this link http://borntorun-mean-multivision.herokuapp.com/)


text:
import axios from 'axios';

export function Link(repo) {
  return `https://github.com/${repo}`;
};

export function ApiLink(repo) {
  return `https://api.github.com/repos/${repo}`;
};

export function FetchData(repo) {
  return axios.get(ApiLink(repo));
};


text:
package Finance::Quote::IndiaMutual;
require 5.004;

use strict;

use vars qw($VERSION $AMFI_URL $AMFI_NAV_LIST $AMFI_MAIN_URL);

use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Status;
use HTML::TableExtract;

$VERSION = '0.1';

# URLs of where to obtain information.

#$AMFI_MAIN_URL = ("http://localhost/");
$AMFI_MAIN_URL = ("http://amfiindia.com/");
$AMFI_URL = ("${AMFI_MAIN_URL}downloadnavopen.asp");
$AMFI_NAV_LIST = "/tmp/amfinavlist.txt";

sub methods { return (indiamutual => \&amfiindia,
		      amfiindia => \&amfiindia); }

{
    my @labels = qw/method source link name currency date isodate nav rprice sprice/;
    sub labels { return (indiamutual => \@labels,
			 amfiindia => \@labels); }
}

#
# =======================================================================

sub amfiindia   {
    my $quoter = shift;
    my @symbols = @_;

    # Make sure symbols are requested
    ##CAN exit more gracefully - add later##

    return unless @symbols;

    # Local Variables
    my(%fundquote, %allquotes);
    my($ua, $url, $reply);

    $ua = $quoter->user_agent;

    $url = "$AMFI_URL";

    $reply = $ua->mirror($url, $AMFI_NAV_LIST);

    # Make sure something is returned
    unless ($reply->is_success or $reply->code == RC_NOT_MODIFIED) {
	foreach my $symbol (@symbols) {
	    $fundquote{$symbol,"success"} = 0;
	    $fundquote{$symbol,"errormsg"} = "HTTP failure";
	}
	return wantarray ? %fundquote : \%fundquote;
    }

    open NAV, $AMFI_NAV_LIST or die "Unexpected error in opening file: $!\n";

    # Scheme Code;Scheme Name;Net Asset Value;Repurchase Price;Sale Price;Date
    while (<NAV>) {
	next if !/\;/;
	chomp;
	s/\r//;
	my ($symbol, @data) = split /\;/;
	$allquotes{$symbol} = \@data;
    }
    close(NAV);

    foreach my $symbol (@symbols) {
	$fundquote{$symbol, "currency"} = "INR";
	$fundquote{$symbol, "source"} = $AMFI_MAIN_URL;
	$fundquote{$symbol, "link"} = $url;
	$fundquote{$symbol, "method"} = "amfitable";

	my $data = $allquotes{$symbol};
	if ($data) {
	    $fundquote{$symbol, "name"} = $data->[0];
	    $fundquote{$symbol, "nav"} = $data->[1];
	    $fundquote{$symbol, "rprice"} = $data->[2];
	    $fundquote{$symbol, "sprice"} = $data->[3];
	    $quoter->store_date(\%fundquote, $symbol, {eurodate => $data->[4]});
	    $fundquote{$symbol, "success"} = 1;
	} else {
	    $fundquote{$symbol, "success"} = 0;
	    $fundquote{$symbol, "errormsg"} = "Fund not found";
	}
    }

    return wantarray ? %fundquote : \%fundquote;
}

1;

=head1 NAME

Finance::Quote::IndiaMutual  - Obtain Indian mutual fund prices from amfiindia.com

=head1 SYNOPSIS

    use Finance::Quote;

    $q = Finance::Quote->new;

    %stockinfo = $q->fetch("indiamutual", "amfiindia-code"); # Can
failover to other methods
    %stockinfo = $q->fetch("amfiindia", "amfiindia-code"); # Use this
module only.

    # NOTE: currently no failover methods exist for indiamutual

=head1 DESCRIPTION

This module obtains information about Indian Mutual Fund prices from the
Association of Mutual Funds India website amfiindia.com.
The information source "indiamutual" can be used
if the source of prices is irrelevant, and "amfiindia" if you
specifically want to use information downloaded from amfiindia.com.

=head1 AMFIINDIA-CODE

In India a mutual fund does not have a unique global symbol identifier.

This module uses an id that represents the mutual fund on an id used by
amfiindia.com.  You can the fund is from the AMFI web site
http://amfiindia.com/downloadnavopen.asp.

=head1 LABELS RETURNED

Information available from amfiindia may include the following labels:

method link source name currency nav rprice sprice.  The link
label will be a url location for the NAV list table for all funds.

=head1 NOTES

amfiindia.com provides a link to download a text file containing all the
NAVs. This file is mirrored in a local file /tmp/amfinavlist.txt. The local
mirror serves only as a cache and can be safely removed.

Currently NAVs of Open-Ended funds are supported.

=head1 SEE ALSO

AMFI india website - http://amfiindia.com/

Finance::Quote

=cut


text:
A collection of Swift utilities

# Attributions

- https://gist.github.com/natecook1000/59bb0c9117b555f5d40d
- https://github.com/soffes/ISO8601


text:
//  Utility class for testing

#import "SBTUtilsTest.h"
#import "SBTCredentialStore.h"
#import "SBTConstants.h"
#import "SBTConstantsTest.h"

@implementation SBTUtilsTest

+ (void) executeAsyncBlock:(void (^)(void (^completionBlock)(void))) testBlock {

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    void (^completionBlock)(void) = ^ {
        dispatch_semaphore_signal(semaphore);
    };
    testBlock(completionBlock);
    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:30]];
    }
}

+ (void) setCredentials {
    [SBTCredentialStore storeWithKey:IBM_CREDENTIAL_CONNECTIONS_URL value:TEST_BASE_URL];
    [SBTCredentialStore storeWithKey:@"IBM_CREDENTIAL_ACME_URL" value:TEST_ACME_BASE_URL];
    [SBTCredentialStore storeWithKey:IBM_CREDENTIAL_USERNAME value:TEST_ACCOUNT_EMAIL];
    [SBTCredentialStore storeWithKey:IBM_CREDENTIAL_PASSWORD value:TEST_ACCOUNT_PASSWORD];
}

@end


text:
package org.smartdata.hdfs.metric.fetcher;

import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.hdfs.CompatibilityHelperLoader;
import org.smartdata.metastore.MetaStoreException;
import org.smartdata.model.ErasureCodingPolicyInfo;
import org.smartdata.model.FileInfo;
import org.smartdata.metastore.MetaStore;
import org.smartdata.metastore.ingestion.IngestionTask;
import org.smartdata.model.FileInfoBatch;
import org.smartdata.metastore.ingestion.FileStatusIngester;
import org.smartdata.protocol.message.StatusReport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import static org.smartdata.hdfs.CompatibilityHelperLoader.getHelper;

public class NamespaceFetcher {
  private static final Long DEFAULT_INTERVAL = 1L;

  private final ScheduledExecutorService scheduledExecutorService;
  private final long fetchInterval;
  private ScheduledFuture[] fetchTaskFutures;
  private ScheduledFuture[] consumerFutures;
  private FileStatusIngester[] consumers;
  private IngestionTask[] ingestionTasks;
  private DFSClient client;
  private MetaStore metaStore;
  private SmartConf conf;

  public static final Logger LOG =
      LoggerFactory.getLogger(NamespaceFetcher.class);

  public NamespaceFetcher(DFSClient client, MetaStore metaStore, ScheduledExecutorService service) {
    this(client, metaStore, DEFAULT_INTERVAL, service, new SmartConf());
  }

  public NamespaceFetcher(DFSClient client, MetaStore metaStore, ScheduledExecutorService service, SmartConf conf) {
    this(client, metaStore, DEFAULT_INTERVAL, service, conf);
  }

  public NamespaceFetcher(DFSClient client, MetaStore metaStore, long fetchInterval) {
    this(client, metaStore, fetchInterval, null, new SmartConf());
  }

  public NamespaceFetcher(DFSClient client, MetaStore metaStore, long fetchInterval,
      ScheduledExecutorService service, SmartConf conf) {
    int numProducers = conf.getInt(SmartConfKeys.SMART_NAMESPACE_FETCHER_PRODUCERS_NUM_KEY,
        SmartConfKeys.SMART_NAMESPACE_FETCHER_PRODUCERS_NUM_DEFAULT);
    numProducers = numProducers <= 0 ? 1 : numProducers;
    this.ingestionTasks = new IngestionTask[numProducers];
    for (int i = 0; i < numProducers; i++) {
      ingestionTasks[i] = new HdfsFetchTask(ingestionTasks, client, conf);
    }

    int numConsumers = conf.getInt(SmartConfKeys.SMART_NAMESPACE_FETCHER_CONSUMERS_NUM_KEY,
        SmartConfKeys.SMART_NAMESPACE_FETCHER_CONSUMERS_NUM_DEFAULT);
    numConsumers = numConsumers <= 0 ? 1 : numConsumers;
    consumers = new FileStatusIngester[numConsumers];
    for (int i = 0; i < numConsumers; i++) {
      consumers[i] = new FileStatusIngester(metaStore);
    }
    this.fetchInterval = fetchInterval;
    if (service != null) {
      this.scheduledExecutorService = service;
    } else {
      scheduledExecutorService = Executors.newScheduledThreadPool(numProducers + numConsumers);
    }
    this.client = client;
    this.metaStore = metaStore;
    this.conf = conf;
  }

  public void startFetch() throws IOException {
    try {
      metaStore.deleteAllEcPolicies();
      Map<Byte, String> idToPolicyName =
          CompatibilityHelperLoader.getHelper().getErasureCodingPolicies(client);
      if (idToPolicyName != null) {
        ArrayList<ErasureCodingPolicyInfo> ecInfos = new ArrayList<>();
        for (Byte id : idToPolicyName.keySet()) {
          ecInfos.add(new ErasureCodingPolicyInfo(id, idToPolicyName.get(id)));
        }
        metaStore.insertEcPolicies(ecInfos);
        LOG.info("Finished fetching all EC policies!");
      }
    } catch (MetaStoreException e) {
      throw new IOException("Failed to clean and fetch EC policies!");
    }

    try {
      metaStore.deleteAllFileInfo();
    } catch (MetaStoreException e) {
      throw new IOException("Error while reset files", e);
    }
    this.fetchTaskFutures = new ScheduledFuture[ingestionTasks.length];
    for (int i = 0; i < ingestionTasks.length; i++) {
      fetchTaskFutures[i] = this.scheduledExecutorService.scheduleAtFixedRate(
          ingestionTasks[i], 0, fetchInterval, TimeUnit.MILLISECONDS);
    }

    this.consumerFutures = new ScheduledFuture[consumers.length];
    for (int i = 0; i < consumers.length; i++) {
      consumerFutures[i] = this.scheduledExecutorService.scheduleAtFixedRate(
          consumers[i], 0, fetchInterval, TimeUnit.MILLISECONDS);
    }
    LOG.info("Started.");
  }

  public boolean fetchFinished() {
    return IngestionTask.finished();
  }

  public void stop() {
    if (fetchTaskFutures != null) {
      for (ScheduledFuture f: fetchTaskFutures) {
        if (f != null) {
          f.cancel(false);
        }
      }
    }
    if (consumerFutures != null) {
      for (ScheduledFuture f : consumerFutures) {
        if (f != null) {
          f.cancel(false);
        }
      }
    }
  }

  private static class HdfsFetchTask extends IngestionTask {
    private final HdfsFileStatus[] EMPTY_STATUS = new HdfsFileStatus[0];
    private final DFSClient client;
    private final SmartConf conf;
    private byte[] startAfter = null;
    private final byte[] empty = HdfsFileStatus.EMPTY_NAME;
    private String parent = "";
    private String pendingParent;
    private IngestionTask[] ingestionTasks;
    private static List<String> ignoreList;
    private static int idCounter = 0;
    private int id;

    public HdfsFetchTask(IngestionTask[] ingestionTasks, DFSClient client, SmartConf conf) {
      super();
      id = idCounter++;
      this.ingestionTasks = ingestionTasks;
      this.client = client;
      this.conf = conf;
      defaultBatchSize = conf.getInt(SmartConfKeys
              .SMART_NAMESPACE_FETCHER_BATCH_KEY,
          SmartConfKeys.SMART_NAMESPACE_FETCHER_BATCH_DEFAULT);

      Collection<String> ignoreDirs =
          this.conf.getTrimmedStringCollection(SmartConfKeys.SMART_IGNORE_DIRS_KEY);
      ignoreList = new ArrayList<>(ignoreDirs.size());
      for (String dir : ignoreDirs) {
        ignoreList.add(dir.endsWith("/") ? dir : dir + "/");
      }
    }

    // BFS finished
    public boolean isDequeEmpty() {
      for (IngestionTask ingestionTask: ingestionTasks) {
        if (((HdfsFetchTask)ingestionTask).parent != null) {
          return false;
        }
      }
      return true;
    }

    @Override
    public void run() {
      if (LOG.isDebugEnabled()) {
        long curr = System.currentTimeMillis();
        if (curr - lastUpdateTime >= 2000) {
          LOG.debug(String.format(
              "%d sec, numDirectories = %d, numFiles = %d, batchsInqueue = %d",
              (curr - startTime) / 1000,
              numDirectoriesFetched.get(), numFilesFetched.get(), batches.size()));
          lastUpdateTime = curr;
        }
      }

      if (batches.size() >= maxPendingBatches) {
        return;
      }

      if (this.pendingParent != null) {
        this.parent = pendingParent;
        this.pendingParent = null;
      } else {
        this.parent = deque.pollFirst();
      }
      if (parent == null) {
        if (currentBatch.actualSize() > 0) {
          try {
            this.batches.put(currentBatch);
          } catch (InterruptedException e) {
            LOG.error("Current batch actual size = "
                + currentBatch.actualSize(), e);
          }
          this.currentBatch = new FileInfoBatch(defaultBatchSize);
        }

        if (this.id == 0 && isDequeEmpty() && this.batches.isEmpty()) {
          if (!IngestionTask.isFinished) {
            IngestionTask.isFinished = true;
            long curr = System.currentTimeMillis();
            LOG.info(String.format(
                "Finished fetch Namespace! %ds, %dms used, numDirs = %d, numFiles = %d",
                (curr - startTime) / 1000, (curr -  startTime) % 1000,
                numDirectoriesFetched.get(), numFilesFetched.get()));
          }
        }
        return;
      }

      if (startAfter == null) {
        String tmpParent = parent.endsWith("/") ? parent : parent + "/";
        for (String dir : ignoreList) {
          if (tmpParent.startsWith(dir)) {
            return;
          }
        }
      }

      try {
        HdfsFileStatus status = client.getFileInfo(parent);
        if (status != null && status.isDir()) {
          if (startAfter == null) {
            FileInfo internal = convertToFileInfo(status, "");
            internal.setPath(parent);
            this.addFileStatus(internal);
            numDirectoriesFetched.incrementAndGet();
          }

          HdfsFileStatus[] children;
          do {
            children = listStatus(parent);
            if (children == null || children.length == 0) {
              break;
            }
            for (HdfsFileStatus child : children) {
              if (child.isDir()) {
                this.deque.add(child.getFullName(parent));
              } else {
                this.addFileStatus(convertToFileInfo(child, parent));
                numFilesFetched.incrementAndGet();
              }
            }
          } while (startAfter != null && batches.size() < maxPendingBatches);
          if (startAfter != null) {
            pendingParent = parent;
          }
        }
      } catch (IOException | InterruptedException e) {
        startAfter = null;
        LOG.error("Totally, numDirectoriesFetched = " + numDirectoriesFetched
            + ", numFilesFetched = " + numFilesFetched
            + ". Parent = " + parent, e);
      }

    }

    /**
     *  Code copy form {@link org.apache.hadoop.fs.Hdfs}
     */
    private HdfsFileStatus[] listStatus(String src) throws IOException {
      DirectoryListing thisListing = client.listPaths(
        src, startAfter == null ? empty : startAfter);
      if (thisListing == null) {
        // the directory does not exist
        startAfter = null;
        return EMPTY_STATUS;
      }
      HdfsFileStatus[] partialListing = thisListing.getPartialListing();
      if (!thisListing.hasMore()) {
        // got all entries of the directory
        startAfter = null;
      } else {
        startAfter = thisListing.getLastName();
      }
      return partialListing;
    }

    private FileInfo convertToFileInfo(HdfsFileStatus status, String parent) {
      FileInfo fileInfo = new FileInfo(
          status.getFullName(parent),
          status.getFileId(),
          status.getLen(),
          status.isDir(),
          status.getReplication(),
          status.getBlockSize(),
          status.getModificationTime(),
          status.getAccessTime(),
          status.getPermission().toShort(),
          status.getOwner(),
          status.getGroup(),
          status.getStoragePolicy(),
          getHelper().getErasureCodingPolicy(status));
      return fileInfo;
    }
  }
}


text:
package me.spyboat.human_interface;

import me.spyboat.interfaces.PlayerInterface;

import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.RowConstraints;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;

public class HumanInterface extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  public void start(Stage primaryStage) {
    AnchorPane pane = new AnchorPane();
    pane.setPrefSize(650, 420);
    pane.setId("pane");

    GridPane boardPane = new GridPane();

    Region[] cells = new Region[16*13];
    Rectangle[] floors = new Rectangle[16*13];
    Random r = new Random();
    for(int i=0;i<16*13;i++) {
      Region cell = new Region();
      cell.setPrefSize(32, 32);
      cell.getStyleClass().add("cell");
      if (r.nextBoolean()) {
        cell.getStyleClass().add("has-cell-floor");
      }
      boardPane.getChildren().add(cell);
      boardPane.setConstraints(cell, i % 16, i / 16);
      cells[i] = cell;
    }

    List<ColumnConstraints> boardPaneColumnConstraints =
      boardPane.getColumnConstraints();
    ColumnConstraints fixedSizeColumn = new ColumnConstraints(32);
    for(int i=0;i<16;i++) {
      boardPaneColumnConstraints.add(fixedSizeColumn);
    }

    List<RowConstraints> boardPaneRowConstraints =
      boardPane.getRowConstraints();
    RowConstraints fixedSizeRow = new RowConstraints(32);
    for(int i=0;i<13;i++) {
      boardPaneRowConstraints.add(fixedSizeRow);
    }

    pane.getChildren().add(boardPane);
    pane.setTopAnchor(boardPane, 2.0);
    pane.setLeftAnchor(boardPane, 136.0);

    Scene scene = new Scene(pane);
    scene.getStylesheets().add(
    HumanInterface.class.getResource("human-interface.css").toExternalForm());

    primaryStage.setTitle("Spybot");
    primaryStage.setScene(scene);
    primaryStage.sizeToScene();
    primaryStage.show();
  }
}


text:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@android:color/white"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.CardView
                android:id="@+id/detail_header_card"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:cardCornerRadius="0dp"
                android:fitsSystemWindows="true"
                app:layout_scrollFlags="scroll|enterAlways"
                app:layout_collapseMode="parallax"
                app:cardBackgroundColor="@color/greenLight"
                app:cardElevation="4dp"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <com.behealthy.gincos.utils.MyTextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        tools:text="Water Fighter"
                        android:textColor="@android:color/black"
                        android:textSize="20sp"
                        app:layout_constraintLeft_toLeftOf="parent"
                        app:layout_constraintTop_toTopOf="parent"
                        android:layout_marginTop="16dp"
                        android:id="@+id/detail_task_title"
                        app:layout_constraintBottom_toBottomOf="parent"
                        android:layout_marginBottom="8dp"
                        android:layout_marginRight="24dp"
                        android:layout_marginEnd="24dp"
                        app:layout_constraintHorizontal_chainStyle="packed"
                        app:layout_constraintRight_toLeftOf="@+id/detail_task_img" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        tools:src="@drawable/water_fighter_icon"
                        app:layout_constraintRight_toRightOf="parent"
                        android:id="@+id/detail_task_img"
                        app:layout_constraintBottom_toBottomOf="parent"
                        android:layout_marginBottom="16dp"
                        app:layout_constraintTop_toTopOf="parent"
                        android:layout_marginTop="16dp"
                        app:layout_constraintLeft_toRightOf="@+id/detail_task_title" />

                </android.support.constraint.ConstraintLayout>

            </android.support.v7.widget.CardView>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center_horizontal">

            <com.behealthy.gincos.utils.MyTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:text="This is the first description"
                android:textSize="16sp"
                android:id="@+id/detail_task_desc_1"
                android:layout_marginTop="24dp"
                app:layout_constraintTop_toBottomOf="@+id/detail_header_card"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                android:layout_marginRight="8dp"
                android:gravity="center"
                app:layout_constraintRight_toRightOf="parent" />

            <com.behealthy.gincos.utils.MyTextView
                android:id="@+id/detail_task_desc_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:gravity="center"
                android:layout_marginBottom="16dp"
                android:layout_marginTop="16dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/detail_task_desc_1"
                tools:text="This speaks about Bayer's medicines" />

            <com.behealthy.gincos.utils.MyTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/greenDark"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:gravity="center"
                android:layout_marginBottom="24dp"
                android:id="@+id/detail_curious_fact"
                tools:text="Human beings need about 7 to 8 cups of water daily in order to live a healthy lifestyle. "/>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>


text:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> // include the boolean library
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include <ctype.h>

// global variables nicely grouped
struct {
    int port; // listening port
    char buffer[16]; // temporary buffer for input
    char password[32]; // required password
    char secret[1024]; // the secret to reveal
} globals;

// report error message & exit
void die( const char * errorMessage, ...) {
    fprintf( stderr, "Error: ");
    va_list args;
    va_start( args, errorMessage);
    vfprintf( stderr, errorMessage, args);
    fprintf( stderr, "\n");
    va_end( args);
    exit(-1);
}

/*read a line of text from file descriptor into provided buffer
* This function now returns an output of "true" if the input was of a valid size and false otherwise.
* This function now accepts size of the buffer as the argument "buff_size"
*/
bool readLineFromFd( int fd, char * buff, int buff_size) {
    char * ptr = buff;
    char * end_buff = &buff[buff_size - 1]; //pointer to the end of the buffer

    //SOLUTION to exploit: Add a condition to the while loop so it stops reading in data once it hits the size of the buffer.
    while(ptr <= end_buff) {
        // try to read in the next character from fd, exit loop on failure
        if( read( fd, ptr, 1) < 1) break;
        // character stored, now advance ptr
        ptr ++;

        //if the ptr is past the last position in the inut buffer and the previous character is not a newline
        //then this input password must be wrong (i.e. too long)
        if((ptr > end_buff) && (*(ptr - 1) != '\n'))
        {
            ptr--; // move back to the last spot in the input buffer
            *ptr = '\0'; // terminate the input buffer to avoid data overflow
            return false; //return false (i.e. data exceeded # of input characters allowed)
        }

        // if last character read was a newline, exit loop
        if( * (ptr - 1) == '\n') break;
    }

    // rewind ptr to the last read character
    ptr --;
    // trim trailing spaces (including new lines, telnet's \r's)
    while(ptr > buff && isspace(* ptr)) ptr --;
    // terminate the string
    * (ptr + 1) = '\0';

    return true; //indicate a successful read
}

// write a string to file descriptor
int writeStrToFd( int fd, char * str) {
   return write( fd, str, strlen( str));
}

int main( int argc, char ** argv)
{
    // parse command line arguments
    if( argc != 4) die( "Usage: server port password secret");
    //reject a password >= 32 chars
    if(strlen(argv[2]) >= (sizeof(globals.password) - 1))
    die("Input password is too long, must be %d or less.", sizeof(globals.password) - 1);
    char * end = NULL;
    globals.port = strtol( argv[1], & end, 10);
    if( * end != 0) die( "bad port %s", argv[1]);
    strncpy( globals.password, argv[2], sizeof( globals.password));
    globals.password[ sizeof(globals.password)-1] = 0;
    strncpy( globals.secret, argv[3], sizeof( globals.secret));
    globals.secret[sizeof(globals.secret)-1] = 0;

    // create a listenning socket on a given port
    struct sockaddr_in servaddr;
    int listenSockFd = socket(AF_INET, SOCK_STREAM, 0);
    if( listenSockFd < 0) die("socket() failed");
    bzero( (char *) & servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htons(INADDR_ANY);
    servaddr.sin_port = htons(globals.port);
    if( bind(listenSockFd, (struct sockaddr *) & servaddr, sizeof(servaddr)) < 0)
        die( "Could not bind listening socket: %s", strerror( errno));

    // listen for a new connection
    if( listen(listenSockFd, 3) != 0)
        die( "Could not listen for incoming connections.");

    //Store the size of the buffer before passing it into the function
    int buffer_size = sizeof(globals.buffer);

    while(1) {
        printf( "Waiting for a new connection...\n");
        // accept a new connection
        int connSockFd = accept(listenSockFd, NULL, NULL);
        if( connSockFd < 0) die( "accept() failed: %s", strerror(errno));
        printf( "Talking to someone.\n");
        // sey hello to the other side
        writeStrToFd( connSockFd, "Secret Server 1.0\n");

        // read response from socket
        // read output from the readlinefromfd function into boolean variable named "success"
        bool success = readLineFromFd( connSockFd, globals.buffer, buffer_size);

        // check if it was a correct password and revised to check that the input read was successful
        if(strcmp( globals.buffer, globals.password) == 0 && success) {
            // password was correct, reveal the secret
            printf( "Someone used the correct password.\n");
            writeStrToFd( connSockFd, "The secret is: ");
            writeStrToFd( connSockFd, globals.secret);
            writeStrToFd( connSockFd, "\n");
        }
        else {
            // password was incorrect, don't reveal the secret
            printf( "Someone used an incorrect password.\n");
            writeStrToFd( connSockFd, "I am not talking to you, bye!\n");
        }
        // close the connection
        close( connSockFd);
    }

    // this will never be called
    close( listenSockFd);
    return 0;
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Document</title>

   www.google.com
    <input type="button" value="b1" onclick="f1()">


text:
![Terminal animation](./docs/terminal.gif)

:white_check_mark: **Detects pods and containers as they come and go**. If you run `ktail foo` and later start a pod or container named `foo`, then it will be picked up automatically. `kubectl` only works on a running pod/container.

:white_check_mark: **Tails multiple pods and containers in multiple namespaces** at the same time, based on names and labels. `kubectl` can only tail a single pod and container. ktail will match the pattern or patterns you specify against both the pod name and the container name.

:white_check_mark: **All containers in a pod are tailed by default**, not just a specific one. With `kubectl`, you have to use `-c`. With ktail, just do `ktail foo` and all its containers are automatically tailed.

:white_check_mark: **Recovers from failure**. ktail will keep retrying forever. `kubectl` often just gives up.

:white_check_mark: **Better formatting**. ktail will show log lines in different colours, and has syntax highlighting of JSON payloads.

# Usage

ktail makes it super easy to tail by pod or container name. The following will match all containers whose pod name or container name contains the substring `foo`:

```shell
$ ktail foo
```

The arguments are regular expressions, so this is possible:

```shell
$ ktail '^foo'
```

If no filters are specified, _all_ pods in the current namespace are tailed.

Tailing supports the usual things like labels:

```shell
$ ktail -l app=myapp
```

This will tail all containers in all pods matching the label `app=myapp`. As new pods are created, it will also automatically tail those, too.

To abort tailing, hit `Ctrl+C`.

## Options

Run `ktail -h` for usage.

## Templating

ktail has a basic output format. To override, you can use a simple Go template. For example:

```shell
$ ktail -t "{{.Container.Name}} {{.Message}}"
```

The following variables are available:

* `Timestamp`: The time of the log event.
* `Message`: The log message.
* `Pod`: The pod object. It has properties such as `Name`, `Namspace`, `Status`, etc.
* `Container`: The container object. It properties such as `Name`.

# Installation

## Homebrew

```shell
$ brew tap atombender/ktail
$ brew install atombender/ktail/ktail
```

## Binary installation

Precompiled binaries for Windows, macOS, Linux (x64 and ARM) are available on the [GitHub release page](https://github.com/atombender/ktail/releases).

## From source

This requires Go >= 1.10, as we use Go modules.

```shell
$ mkdir -p $GOPATH/src/github.com/atombender
$ cd $GOPATH/src/github.com/atombender
$ git clone https://github.com/atombender/ktail
$ cd ktail
$ go install .
```

# Acknowledgements

Some setup code was borrowed from [k8stail](https://github.com/dtan4/k8stail).

# License

MIT license. See `LICENSE` file.


text:
using Kirinji.LightWands;
using Kirinji.LinqToObservableCollection.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kirinji.LinqToObservableCollection.Impl
{
    sealed class InitialState<T> : IInitialState<T>
    {
        public InitialState(IReadOnlyList<T> items)
        {
            Contract.Requires<ArgumentNullException>(items != null);

            this.Items = items;
        }

        public IReadOnlyList<T> Items { get; private set; }

        public override string ToString()
        {
            return NotifyCollectionChangedEventAction.InitialState.ToString()
                + " (items: "
                + Converters.ListToString(Items, 4)
                + ")";
        }
    }
}


text:
using System;
using System.Linq;
using System.Media;
using System.Threading;

static class Tetris
{
    // 20x10 is the standart field size

    private const int FieldCols = 11; // Prefer odd numbers of cols for perfect centering
    private const int AsideCols = 15;

    private const int Rows = 20;
    private const int Cols = 1 + FieldCols + 1 + AsideCols; // "#...Field...# Aside "

    private static readonly KeyboardUserInterface userInterface = null;
    private static readonly ConsoleRenderer renderer = null;

    private static readonly Engine engine = null;

    static Tetris()
    {
        userInterface = new KeyboardUserInterface();
        renderer = new ConsoleRenderer(Tetris.Rows, Tetris.Cols);

        engine = new Engine(renderer, userInterface);

        engine.InitializeField(1, Tetris.FieldCols);
    }

    private static void ShowIntro()
    {
        PrintMessage(
            "Best viewed in bold Lucida Console with size 28." + Environment.NewLine,
            "Play music? Y/N"
        );

        if (Console.ReadKey(true).Key == ConsoleKey.Y)
        {
            try { new SoundPlayer("../../Music.wav").PlayLooping(); }
            catch { }
        }

        Console.Clear();
    }

    private static void InitializeField()
    {
        // Bottom border
        for (int i = 1; i < Tetris.FieldCols + 1; i++)
            engine.Add(new Block(new Coordinates(Tetris.Rows - 1, i)));

        // Starts from negative number to avoid moving
        // the tetromino outside the borders when created.
        //
        //       xx
        //        xx            xx
        // #             #  ->  #xx           #
        // #             #      #             #
        // ###############      ###############

        // Left border
        for (int i = -5; i < Tetris.Rows; i++)
            engine.Add(new Block(new Coordinates(i, 0)));

        // Right border
        for (int i = -5; i < Tetris.Rows; i++)
            engine.Add(new Block(new Coordinates(i, Tetris.FieldCols + 1)));
    }

    private static void InitializeAside()
    {
        int numberOfLines = 4;

        int row = (Tetris.Rows - numberOfLines) / 2;
        int col = 1 + Tetris.FieldCols + 1 + 1;

        engine.Add(
            new TextLine("Move left:  \u2190", new Coordinates(row++, col)),
            new TextLine("Move right: \u2192", new Coordinates(row++, col)),
            new TextLine("Rotate:     \u2191", new Coordinates(row++, col)),
            new TextLine("Drop:       \u2193", new Coordinates(row++, col))
        );
    }

    private static void AttachEvents()
    {
        userInterface.OnLeft   += engine.MoveLeft;
        userInterface.OnRight  += engine.MoveRight;
        userInterface.OnRotate += engine.Rotate;
        userInterface.OnDrop   += engine.Drop;

        engine.OnMoveEnd += (sender, e) =>
            Console.Beep(100, 125); // Not async

        //engine.OnMoveEnd += (sender, e) =>
        //    engine.Add(new MovingObject(new char[,] { { 'o' } }, Color.Red,
        //        new Coordinates(Rows / 2, FieldCols / 2), Coordinates.Random));

        engine.OnClearedRows += (sender, numberOfClearedRows) =>
        {
            for (int i = 0; i < numberOfClearedRows; i++)
            {
                Console.Beep(1000, 300);

                Thread.Sleep(50);
            }
        };

        engine.OnGameOver += (sender, e) =>
        {
            Console.ForegroundColor = ConsoleColor.White;

            string message = "Thank you for playing...";

            Console.SetCursorPosition((Cols - message.Length) / 2, Rows / 2);

            Console.WriteLine(message);

            Console.ReadKey(true);
        };
    }

    private static void AddControlled()
    {
        Action addControlled = () =>
            engine.AddControlled(Tetromino.Get(new Coordinates(0, Tetris.FieldCols / 2)));

        addControlled();

        engine.OnMoveEnd += (sender, e) =>
            addControlled();
    }

    public static void PrintMessage(params string[] messages)
    {
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.Clear();

        foreach (string message in messages)
            Console.WriteLine(message);
    }

    public static void Main()
    {
        Console.Title = "Tetris";

        //ShowIntro();

        InitializeField();
        InitializeAside();

        AttachEvents();

        AddControlled();

        try { engine.Run(); }

        catch (OTetrominoRotatedException ex)
        {
            PrintMessage(ex.Message);
        }
    }
}


text:
package yanagishima;

import java.net.InetAddress;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

import lombok.extern.slf4j.Slf4j;
import yanagishima.util.DefaultProfileUtil;

@Slf4j
@SpringBootApplication
public class YanagishimaApplication {
  public static void main(String[] args) throws Exception {
    SpringApplication app = new SpringApplication(YanagishimaApplication.class);
    DefaultProfileUtil.addDefaultProfile(app);
    Environment env = app.run(args).getEnvironment();

    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
      protocol = "https";
    }

    log.info("\n----------------------------------------------------------\n\t"
             + "Application '{}' is running! Access URLs:\n\t"
             + "Local: \t\t{}://localhost:{}\n\t"
             + "External: \t{}://{}:{}\n\t"
             + "Profile(s): \t{}\n----------------------------------------------------------",
             env.getProperty("spring.application.name"),
             protocol,
             env.getProperty("server.port"),
             protocol,
             InetAddress.getLocalHost().getHostAddress(),
             env.getProperty("server.port"),
             env.getActiveProfiles());

  }
}


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.1/docs/user-guide/kubectl/kubectl.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

## kubectl

kubectl controls the Kubernetes cluster manager

### Synopsis

kubectl controls the Kubernetes cluster manager.

Find more information at https://github.com/kubernetes/kubernetes.

```
kubectl
```

### Options

```
      --alsologtostderr[=false]: log to standard error as well as files
      --api-version="": The API version to use when talking to the server
      --certificate-authority="": Path to a cert. file for the certificate authority.
      --client-certificate="": Path to a client certificate file for TLS.
      --client-key="": Path to a client key file for TLS.
      --cluster="": The name of the kubeconfig cluster to use
      --context="": The name of the kubeconfig context to use
      --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.
      --kubeconfig="": Path to the kubeconfig file to use for CLI requests.
      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace
      --log-dir="": If non-empty, write log files in this directory
      --log-flush-frequency=5s: Maximum number of seconds between log flushes
      --logtostderr[=true]: log to standard error instead of files
      --match-server-version[=false]: Require server version to match client version
      --namespace="": If present, the namespace scope for this CLI request.
      --password="": Password for basic authentication to the API server.
  -s, --server="": The address and port of the Kubernetes API server
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --token="": Bearer token for authentication to the API server.
      --user="": The name of the kubeconfig user to use
      --username="": Username for basic authentication to the API server.
      --v=0: log level for V logs
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO

* [kubectl annotate](kubectl_annotate.md)	 - Update the annotations on a resource
* [kubectl api-versions](kubectl_api-versions.md)	 - Print the supported API versions on the server, in the form of "group/version".
* [kubectl apply](kubectl_apply.md)	 - Apply a configuration to a resource by filename or stdin
* [kubectl attach](kubectl_attach.md)	 - Attach to a running container.
* [kubectl autoscale](kubectl_autoscale.md)	 - Auto-scale a deployment or replication controller
* [kubectl cluster-info](kubectl_cluster-info.md)	 - Display cluster info
* [kubectl config](kubectl_config.md)	 - config modifies kubeconfig files
* [kubectl convert](kubectl_convert.md)	 - Convert config files between different API versions
* [kubectl cordon](kubectl_cordon.md)	 - Mark node as unschedulable
* [kubectl create](kubectl_create.md)	 - Create a resource by filename or stdin
* [kubectl delete](kubectl_delete.md)	 - Delete resources by filenames, stdin, resources and names, or by resources and label selector.
* [kubectl describe](kubectl_describe.md)	 - Show details of a specific resource or group of resources
* [kubectl drain](kubectl_drain.md)	 - Drain node in preparation for maintenance
* [kubectl edit](kubectl_edit.md)	 - Edit a resource on the server
* [kubectl exec](kubectl_exec.md)	 - Execute a command in a container.
* [kubectl explain](kubectl_explain.md)	 - Documentation of resources.
* [kubectl expose](kubectl_expose.md)	 - Take a replication controller, service or pod and expose it as a new Kubernetes Service
* [kubectl get](kubectl_get.md)	 - Display one or many resources
* [kubectl label](kubectl_label.md)	 - Update the labels on a resource
* [kubectl logs](kubectl_logs.md)	 - Print the logs for a container in a pod.
* [kubectl namespace](kubectl_namespace.md)	 - SUPERSEDED: Set and view the current Kubernetes namespace
* [kubectl patch](kubectl_patch.md)	 - Update field(s) of a resource using strategic merge patch.
* [kubectl port-forward](kubectl_port-forward.md)	 - Forward one or more local ports to a pod.
* [kubectl proxy](kubectl_proxy.md)	 - Run a proxy to the Kubernetes API server
* [kubectl replace](kubectl_replace.md)	 - Replace a resource by filename or stdin.
* [kubectl rolling-update](kubectl_rolling-update.md)	 - Perform a rolling update of the given ReplicationController.
* [kubectl rollout](kubectl_rollout.md)	 - rollout manages a deployment
* [kubectl run](kubectl_run.md)	 - Run a particular image on the cluster.
* [kubectl scale](kubectl_scale.md)	 - Set a new size for a Replication Controller, Job, or Deployment.
* [kubectl uncordon](kubectl_uncordon.md)	 - Mark node as schedulable
* [kubectl version](kubectl_version.md)	 - Print the client and server version information.

###### Auto generated by spf13/cobra on 19-Jan-2016

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl.md?pixel)]()


text:
import _ from 'underscore';
import Bb from 'backbone';
import BaseRouter from 'backbone.base-router';
import Route from './route';

var PremiumRouter = BaseRouter.extend({

  // The PremiumRouter provides the ability for a Route
  // to cancel a navigation if it is not fit to be exited.
  // This is useful to ensure that a user does not, for instance,
  // leave a model unsaved.
  navigate: function(fragment, options) {

    // If there is a current route, then we are
    // given the opportunity to cancel the navigation
    if (_.result(this.currentRoute, 'preventNavigation') !== true) {
      Bb.history.navigate(fragment, options);
    }

    return this;
  },

  // The BaseRouter provides us a single point of
  // entry anytime a route is matched by BB.history
  onNavigate(routeData) {

    // Create a new route each time we navigate
    var newRoute = new routeData.linked({
      router: this
    });

    // Remove unnecessary pieces from the routeData
    routeData = _.pick(routeData, 'params', 'query', 'uriFragment');

    // Store the route we're trying to transition to. This lets
    // us know if the user transitions away at a later time.
    this._transitioningTo = newRoute;

    newRoute.trigger('before:fetch', routeData);

    // Coerce the fetch method to a promise, so that it can be sync or async.
    return Promise.resolve(newRoute.fetch(routeData))

      // If it's successful, then we move along to the `_onFetch` callback.
      .then(fetchData => {
        this._onFetch(newRoute, fetchData, routeData);
      })

      // If there are errors at any time, then we look for an `onError`
      // method of the Route. If it exists, we execute it; otherwise, we
      // use the Router's `onError` callback.
      .catch(e => {
        if (newRoute.onError) {
          newRoute.onError(e, routeData);
        } else {
          this.onError(e, routeData);
        }
      });
  },

  _onFetch(newRoute, fetchData, routeData) {

    // Anytime the developer has an opportunity to navigate again,
    // we need to check if they have. If they have, then we stop.
    // As you can see below, we must do this check multiple times in
    // this callback.
    if (this._transitioningTo !== newRoute) { return; }

    // Trigger the fetch method on the route
    newRoute.trigger('fetch', routeData, fetchData);
    if (this._transitioningTo !== newRoute) { return; }

    // Trigger the exit method on the current route,
    // if it exists
    if (this.currentRoute) {
      this.currentRoute.trigger('exit');
    }
    if (this._transitioningTo !== newRoute) { return; }

    this.currentRoute = newRoute;
    this.currentRoute.trigger('enter', routeData, fetchData);

    // We can now delete the internal reference to this transition,
    // if we still have it, as the transition is complete.
    if (this._transitioningTo === newRoute) {
      delete this._transitioningTo;
    }
  },

  // The error callback is executed whenever there
  // is an unhandled exception in your Route.
  // You can specify an `onError` callback in a
  // route for per-route handling, or override this method
  // to modify the default handling of errors.
  onError(e, routeData) {
    if (typeof console === 'object') {
      console.error(e, e.stack);
    }
    return this;
  }
});

PremiumRouter.Route = Route;

Bb.PremiumRouter = PremiumRouter;

export default PremiumRouter;


text:
require 'ipaddr'
require 'forwardable'
require 'puppet/parser'
require 'puppet/parser/templatewrapper'
require 'puppet/resource/type_collection_helper'
require 'puppet/util/methodhelper'

begin
  require 'puppet/parser/functions/lib/l23network_scheme.rb'
rescue LoadError => e
  # puppet apply does not add module lib directories to the $LOAD_PATH (See
  # #4248). It should (in the future) but for the time being we need to be
  # defensive which is what this rescue block is doing.
  rb_file = File.join(File.dirname(__FILE__),'lib','l23network_scheme.rb')
  load rb_file if File.exists?(rb_file) or raise e
end

module L23network
  def self.sanitize_transformation(trans)
    action = trans[:action].downcase()
    # Setup defaults
    rv = case action
      when "add-br" then {
        :name => nil,
        #:stp_enable => true,
        :skip_existing => true
      }
      when "add-port" then {
        :name => nil,
        :bridge => nil,
        #:type => "internal",
        :tag => 0,
        :trunks => [],
        :port_properties => [],
        :interface_properties => [],
        :skip_existing => true
      }
      when "add-bond" then {
        :name => nil,
        :bridge => nil,
        :interfaces => [],
        :tag => 0,
        :trunks => [],
        :properties => [],
        #:port_properties => [],
        #:interface_properties => [],
        :skip_existing => true
      }
      when "add-patch" then {
        :name => "unnamed", # calculated later
        :peers => [nil, nil],
        :bridges => [],
        :tags => [0, 0],
        :trunks => [],
      }
      else
        raise(Puppet::ParseError, "Unknown transformation: '#{action}'.")
    end
    # replace defaults to real parameters
    rv[:action] = action
    rv.each do |k,v|
      if trans[k]
        rv[k] = trans[k]
      end
    end
    # Check for incorrect parameters
    if not rv[:name].is_a? String
      raise(Puppet::ParseError, "Unnamed transformation: '#{action}'.")
    end
    name = rv[:name]
    if not rv[:bridge].is_a? String and !["add-patch", "add-br"].index(action)
      raise(Puppet::ParseError, "Undefined bridge for transformation '#{action}' with name '#{name}'.")
    end
    if action == "add-patch"
      if not rv[:bridges].is_a? Array  and  rv[:bridges].size() != 2
        raise(Puppet::ParseError, "Transformation patch have wrong 'bridges' parameter.")
      end
      name = "patch__#{rv[:bridges][0]}__#{rv[:bridges][1]}"
      if not rv[:peers].is_a? Array  and  rv[:peers].size() != 2
        raise(Puppet::ParseError, "Transformation patch '#{name}' have wrong 'peers' parameter.")
      end
      rv[:name] = name
    end
    if action == "add-bond"
      if not (rv[:interfaces].is_a?(Array) and rv[:interfaces].size() >= 2)
        raise(Puppet::ParseError, "Transformation bond '#{name}' have wrong 'interfaces' parameter.")
      end
    end
    return rv
  end
end

Puppet::Parser::Functions::newfunction(:generate_network_config, :type => :rvalue, :doc => <<-EOS
    This function get Hash of network interfaces and endpoints configuration
    and realized it.

    EOS
  ) do |argv|

    def default_netmask()
      "/24"
    end

    def create_endpoint()
      {
        :properties => {},
        :IP => []
      }
    end

    if argv.size != 0
      raise(Puppet::ParseError, "generate_network_config(): Wrong number of arguments.")
    end

    config_hash = L23network::Scheme.get_config(lookupvar('l3_fqdn_hostname'))
    if config_hash.nil?
      raise(Puppet::ParseError, "get_network_role_property(...): You must call prepare_network_config(...) first!")
    end

    # define internal puppet parameters for creating resources
    res_factory = {
      :br      => { :name_of_resource => 'l23network::l2::bridge' },
      :port    => { :name_of_resource => 'l23network::l2::port' },
      :bond    => { :name_of_resource => 'l23network::l2::bond' },
      :patch   => { :name_of_resource => 'l23network::l2::patch' },
      :ifconfig=> { :name_of_resource => 'l23network::l3::ifconfig' }
    }
    res_factory.each do |k, v|
      if v[:name_of_resource].index('::')
        # operate by Define
        res_factory[k][:resource] = lookuptype(v[:name_of_resource].downcase())  # may be find_definition(k.downcase())
        res_factory[k][:type_of_resource] = :define
      else
        # operate by custom Type
        res_factory[k][:resource] = Puppet::Type.type(v[:name_of_resource].to_sym())
        res_factory[k][:type_of_resource] = :type
      end
    end

    # collect interfaces and endpoints
    endpoints = {}
    born_ports = []
    config_hash[:interfaces].each do |int_name, int_properties|
      int_name = int_name.to_sym()
      endpoints[int_name] = create_endpoint()
      born_ports.insert(-1, int_name)
    end
    config_hash[:endpoints].each do |e_name, e_properties|
      e_name = e_name.to_sym()
      if not endpoints[e_name]
        endpoints[e_name] = create_endpoint()
      end
      e_properties.each do |k,v|
        if k.to_sym() == :IP
          if !(v.is_a?(Array) || ['none','dhcp',nil].include?(v))
            raise(Puppet::ParseError, "generate_network_config(): IP field for endpoint '#{e_name}' must be array of IP addresses, 'dhcp' or 'none'.")
          elsif ['none','dhcp',nil].include?(v)
            endpoints[e_name][:IP].insert(-1, v ? v : 'none')
          else
            v.each do |ip|
              begin
                iip = IPAddr.new(ip)
                endpoints[e_name][:IP].insert(-1, ip)
              rescue
                raise(Puppet::ParseError, "generate_network_config(): IP address '#{ip}' for endpoint '#{e_name}' wrong!.")
              end
            end
          end
        else
          endpoints[e_name][:properties][k.to_sym()] = v
        end
      end
    end

    # execute transformations
    # todo: if provider="lnx" execute transformations for LNX bridges
    transformation_success = []
    previous = nil
    config_hash[:transformations].each do |t|
      action = t[:action].strip()
      if action.start_with?('add-')
        action = t[:action][4..-1].to_sym()
      else
        action = t[:action].to_sym()
      end

      trans = L23network.sanitize_transformation(t)
      resource = res_factory[action][:resource]
      p_resource = Puppet::Parser::Resource.new(
          res_factory[action][:name_of_resource],
          trans[:name],
          :scope => self,
          :source => resource
      )

      # setup trunks and vlan_splinters for phys.NIC
      if (action == :port) and config_hash[:interfaces][trans[:name].to_sym] and  # does adding phys.interface?
         config_hash[:interfaces][trans[:name].to_sym][:L2] and                   # does this interface have L2 section
         config_hash[:interfaces][trans[:name].to_sym][:L2][:trunks] and          # does this interface have TRUNKS section
         config_hash[:interfaces][trans[:name].to_sym][:L2][:trunks].is_a?(Array) and
         config_hash[:interfaces][trans[:name].to_sym][:L2][:trunks].size() > 0   # does trunks section non empty?
            Puppet.debug("Configure trunks and vlan_splinters for #{trans[:name]} (value is '#{config_hash[:interfaces][trans[:name].to_sym][:L2][:vlan_splinters]}')")
            _do_trunks = true
            if config_hash[:interfaces][trans[:name].to_sym][:L2][:vlan_splinters]
              if config_hash[:interfaces][trans[:name].to_sym][:L2][:vlan_splinters] == 'on'
                trans[:vlan_splinters] = true
              elsif config_hash[:interfaces][trans[:name].to_sym][:L2][:vlan_splinters] == 'auto'
                sp_nics = lookupvar('l2_ovs_vlan_splinters_need_for')
                Puppet.debug("l2_ovs_vlan_splinters_need_for: #{sp_nics}")
                if sp_nics and sp_nics != :undefined and sp_nics.split(',').index(trans[:name].to_s)
                  Puppet.debug("enable vlan_splinters for: #{trans[:name].to_s}")
                  trans[:vlan_splinters] = true
                else
                  trans[:vlan_splinters] = false
                  if trans[:trunks] and trans[:trunks].size() >0
                    Puppet.debug("disable vlan_splinters for: #{trans[:name].to_s}. Trunks will be set to '#{trans[:trunks].join(',')}'")
                    config_hash[:interfaces][trans[:name].to_sym][:L2][:trunks] = []
                  else
                    Puppet.debug("disable vlan_splinters for: #{trans[:name].to_s}. Trunks for this interface also disabled.")
                    _do_trunks = false
                  end
                end
              else
                trans[:vlan_splinters] = false
              end
            else
              trans[:vlan_splinters] = false
            end
            # add trunks list to the interface if it given
            if _do_trunks
              _trunks = [0] + trans[:trunks] + config_hash[:interfaces][trans[:name].to_sym][:L2][:trunks]  # zero for pass untagged traffic
              _trunks.sort!().uniq!()
              trans[:trunks] = _trunks
            end
            Puppet.debug("Configure trunks and vlan_splinters for #{trans[:name]} done.")
      end

      trans.select{|k,v| k != :action}.each do |k,v|
        p_resource.set_parameter(k,v)
      end

      p_resource.set_parameter(:require, [previous]) if previous
      resource.instantiate_resource(self, p_resource)
      compiler.add_resource(self, p_resource)
      transformation_success.insert(-1, "#{t[:action].strip()}(#{trans[:name]})")
      born_ports.insert(-1, trans[:name].to_sym()) if action != :patch
      previous = p_resource.to_s
    end

    # check for all in endpoints are in interfaces or born by transformation
    config_hash[:endpoints].each do |e_name, e_properties|
      if not born_ports.index(e_name.to_sym())
        raise(Puppet::ParseError, "generate_network_config(): Endpoint '#{e_name}' not found in interfaces or transformations result.")
      end
    end
    # execute interfaces and endpoints
    # may be in future we will move interfaces before transformations
    endpoints.each do |endpoint_name, endpoint_body|
      # create resource
      resource = res_factory[:ifconfig][:resource]
      p_resource = Puppet::Parser::Resource.new(
          res_factory[:ifconfig][:name_of_resource],
          endpoint_name,
          :scope => self,
          :source => resource
      )
      p_resource.set_parameter(:interface, endpoint_name)
      # set ipaddresses
      if endpoint_body[:IP].empty?
        p_resource.set_parameter(:ipaddr, 'none')
      elsif ['none','dhcp'].index(endpoint_body[:IP][0])
        p_resource.set_parameter(:ipaddr, endpoint_body[:IP][0])
      else
        ipaddrs = []
        endpoint_body[:IP].each do |i|
          if i =~ /\/\d+$/
            ipaddrs.insert(-1, i)
          else
            ipaddrs.insert(-1, "#{i}#{default_netmask()}")
          end
        end
        p_resource.set_parameter(:ipaddr, ipaddrs)
      end
      #set another (see L23network::l3::ifconfig DOC) parametres
      endpoint_body[:properties].each do |k,v|
        p_resource.set_parameter(k,v)
      end
      p_resource.set_parameter(:require, [previous]) if previous
      resource.instantiate_resource(self, p_resource)
      compiler.add_resource(self, p_resource)
      transformation_success.insert(-1, "endpoint(#{endpoint_name})")
      previous = p_resource.to_s
    end

    return transformation_success.join(" -> ")
end
# vim: set ts=2 sw=2 et :


text:
using System;
using System.Collections.Generic;
using System.Threading;

using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;

namespace Microsoft.Build.BuildEngine
{
    /// <summary>
    /// This class implements the in-proc (engine process) logging services, provided by the engine for
    /// internal logging purposes.
    /// </summary>
    internal class EngineLoggingServicesInProc : EngineLoggingServices
    {
        #region Constructors

        /// <summary>
        /// Private default constructor -- do not allow instantation w/o parameters.
        /// </summary>
        private EngineLoggingServicesInProc()
        {
            // do nothing
        }

        /// <summary>
        /// Creates an instance of this class for the given engine event source.
        /// </summary>
        /// <param name="eventSource"></param>
        /// <param name="onlyLogCriticalEvents"></param>
        internal EngineLoggingServicesInProc(EventSource eventSource, bool onlyLogCriticalEvents, ManualResetEvent flushRequestEvent)
        {
            this.onlyLogCriticalEvents = onlyLogCriticalEvents;
            this.engineEventSource = eventSource;

            // Allocate the table mapping logger ids to event sources
            this.eventSources = new Dictionary<int, EventSource>();
            RegisterEventSource(CENTRAL_ENGINE_EVENTSOURCE, eventSource);

            base.Initialize(flushRequestEvent);
        }

        #endregion

        #region Methods

        /// <summary>
        /// This function logs out all the messages currently posted to the queue. The active queue is swapped
        /// with the secondary queue to enable posting of messages while this function is running
        /// </summary>
        override internal bool ProcessPostedLoggingEvents()
        {
            bool processedEvents = false;
            lastFlushTime = DateTime.Now.Ticks;

            // Process all the events posted with a logger Id
            NodeLoggingEvent nodeLoggingEvent;

            // We may get a single event for multiple messages
            while ((nodeLoggingEvent = loggingQueueOfNodeEvents.Dequeue()) != null)
            {
                int loggerId = nodeLoggingEvent.LoggerId;
                if (loggerId != ALL_PRIVATE_EVENTSOURCES)
                {
                    ErrorUtilities.VerifyThrow(eventSources.ContainsKey(loggerId), "Logger Id should be registered");
                    ErrorUtilities.VerifyThrow(loggerId != LOCAL_FORWARDING_EVENTSOURCE, "Should not use FWD loggers");
                    eventSources[loggerId].RaiseStronglyTypedEvent(nodeLoggingEvent.BuildEvent);
                }
                else
                {
                    // Post event to all central loggers
                    foreach (KeyValuePair<int, EventSource> eventSource in eventSources)
                    {
                        if (eventSource.Key >= FIRST_AVAILABLE_LOGGERID)
                        {
                            eventSource.Value.RaiseStronglyTypedEvent(nodeLoggingEvent.BuildEvent);
                        }
                    }
                }
                processedEvents = true;
            }

            // Process all the events in that have been already posted
            BuildEventArgs buildEventArgs;

            // We may get a single event for multiple messages
            while ((buildEventArgs = loggingQueueOfBuildEvents.Dequeue()) != null)
            {
                ProcessBuildEvent(buildEventArgs);
                processedEvents = true;
            }

            requestedQueueFlush = false;
            return processedEvents;
        }

        /// <summary>
        /// This method process a single BuildEvent argument, it will raise the event to registered loggers and
        /// check to see if the there are forwarding loggers who need to see the event also, if so the message will
        /// be posted to another logger
        /// </summary>
        /// <param name="buildEventArgs"></param>
        override internal void ProcessBuildEvent(BuildEventArgs buildEventArgs)
        {
            engineEventSource.RaiseStronglyTypedEvent(buildEventArgs);

            // Check if there are local forwarding loggers that should see this event
            if (eventSources.ContainsKey(LOCAL_FORWARDING_EVENTSOURCE))
            {
                eventSources[LOCAL_FORWARDING_EVENTSOURCE].RaiseStronglyTypedEvent(buildEventArgs);
            }

            // Check if it necessary to forward the event to another logging service
            forwardingService?.PostLoggingEvent(buildEventArgs);
        }

        internal void RegisterEventSource(int loggerId, EventSource eventSource)
        {
            ErrorUtilities.VerifyThrow(!eventSources.ContainsKey(loggerId), "Should not see duplicate logger ids");
            eventSources[loggerId] = eventSource;
        }

        internal void UnregisterEventSource(int loggerId)
        {
            if (eventSources.ContainsKey(loggerId))
            {
                eventSources[loggerId].UnregisterAllLoggers();
                eventSources.Remove(loggerId);
            }
        }

        /// <summary>
        /// Shutdown the logging service as appropriate
        /// </summary>
        override internal void Shutdown()
        {
            foreach (EventSource eventSource in eventSources.Values)
            {
                eventSource.UnregisterAllLoggers();
            }
        }

        #endregion

        #region Data

        // A table mapping logger ids to event sources
        private Dictionary<int, EventSource> eventSources;
        // cached pointer to the engines main event source (also available in eventSources[0])
        private readonly EventSource engineEventSource;

        internal const int CENTRAL_ENGINE_EVENTSOURCE = 0;
        internal const int LOCAL_FORWARDING_EVENTSOURCE = 1;
        internal const int ALL_PRIVATE_EVENTSOURCES = 2;
        internal const int FIRST_AVAILABLE_LOGGERID = 3;

        #endregion
    }
}