text:
using Microsoft.Extensions.CommandLineUtils;
using Platibus.RabbitMQ;
using System.Threading;
using System.Threading.Tasks;

namespace Platibus.SampleConsoleApp
{
    public class SendCommand : RabbitMQHostCommand
    {
        public static void Configure(CommandLineApplication app)
        {
            app.HelpOption("-h|-?|--help");

            var countOption = app.Option(
                "-c|--count",
                "The number of pings to send through the system",
                CommandOptionType.SingleValue);

            var idOption = app.Option(
                "-n|--node",
                "The node ID",
                CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                int.TryParse(countOption.Value(), out var count);
                var id = idOption.Value();
                var command = new SendCommand(count, id);
                return command.Execute();
            });
        }

        private readonly int _count;

        public SendCommand(int count, string id) : base(id)
        {
            _count = count;
        }

        protected override async Task Execute(RabbitMQHost host, CancellationToken cancellationToken)
        {
            var ping = new Ping(Id, _count);
            await host.Bus.Send(ping, cancellationToken: cancellationToken);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation FIRCLSThreadArrayOperation

- (void)enumerateFramesWithBlock:(void (^)(FIRStackFrame *frame))block {
  for (NSArray *frameArray in self.threadArray) {
    for (FIRStackFrame *frame in frameArray) {
      block(frame);

      if ([self isCancelled]) {
        break;
      }
    }
  }
}

@end


text:
package app.testapplication.gihan.com.weatherapp;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Crate control fragment.
 */
public class ControlModuleFragment extends FragmentPagerAdapter {

    ArrayList<Fragment> frgments;
    Context context;
    FragmentManager fm;

    public ControlModuleFragment (FragmentManager fm,ArrayList<Fragment> fragment){
        super(fm);
        this.frgments =fragment;

    }

    @Override
    public Fragment getItem(int position) {
        return frgments.get(position);
    }

    @Override
    public int getCount() {
        return frgments.size();
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {

        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

}


text:
import { AngularSrcPage } from './app.po';

describe('angular-src App', () => {
  let page: AngularSrcPage;

  beforeEach(() => {
    page = new AngularSrcPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});


text:
import React, {Component} from "react";
import {observer} from "mobx-react";
import PropTypes from "prop-types";

@observer
class Button extends Component {
    render() {
        const {props} = this;
        return (
            <button
                id={props.id || null}
                type="button"
                className={props.className}
                disabled={props.disabled}
                data-toggle={props.dataToggle || null}
                aria-haspopup={props.hasPopup || null}
                title={props.title || null}
                onClick={props.onClick}>
                {props.faClass ? <i className={props.faClass} /> : null}
                {props.text}
            </button>
        );
    }
}

Button.propTypes = {
    id: PropTypes.string,
    text: PropTypes.string,
    className: PropTypes.string.isRequired,
    title: PropTypes.string,
    disabled: PropTypes.bool,
    onClick: PropTypes.func,
    faClass: PropTypes.string,
    dataToggle: PropTypes.string,
    hasPopup: PropTypes.bool,
};
Button.defaultProps = {
    disabled: false,
};

export default Button;


text:
import test from 'ava';
import {transform} from 'babel-core';
import es2015 from 'babel-preset-es2015';
import es2016 from 'babel-preset-es2016';
import plugin from '../dist/index';

/**
 * Creates test macros from babel presets and a test prefix
 * @param {Object[]} presets - babel presets for transform
 * @param {string} prefix - text to prepend to expected output
 * @return {function} test macro
 */
function babelTransformFactory(presets = [], prefix = '') {
  return (t, input, expected) => {
    const actual = transform(input, {plugins: [plugin], presets}).code;
    t.is(actual, `${prefix}${expected}`);
  };
}

/**
 * Creates titles for a test macro
 * @param {string} version - Javascript version or dialet being tested
 * @return {function} title macro
 */
function titleFactory(version) {
  return (providedTitle, input, expected) => providedTitle ?
    `${providedTitle} in ${version}` :
    `"${input}" becomes "${expected}" in ${version}`;
}

const babelES5Transform = babelTransformFactory();
const babelES6Transform = babelTransformFactory([es2015], '"use strict";\n\n');
const babelES7Transform = babelTransformFactory([es2015, es2016], '"use strict";\n\n');

babelES5Transform.title = titleFactory('ES5');
babelES6Transform.title = titleFactory('ES6');
babelES7Transform.title = titleFactory('ES7');

test(
  'constant boolean unchanged',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = true;',
  'var a = true;'
);

test(
  'true boolean and expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = true && true;',
  'var a = true;'
);

test(
  'true boolean or expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = false || true;',
  'var a = true;'
);

test(
  'false boolean or expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = false || false;',
  'var a = false;'
);

test(
  'true boolean mixed expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = true && false || true;',
  'var a = true;'
);

test(
  'false boolean mixed expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = true && (false || false);',
  'var a = false;'
);

test(
  'inferred boolean expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = true; var b = false || a;',
  'var a = true;var b = true;'
);

test(
  'boolean expression with variable partially reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = b || true && false;',
  'var a = b || false;'
);

test(
  'constant number unchanged',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 1;',
  'var a = 1;'
);

test(
  'number addition expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 1 + 1;',
  'var a = 2;'
);

test(
  'number subtraction expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 1 - 1;',
  'var a = 0;'
);

test(
  'number multiplication expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 2 * 2;',
  'var a = 4;'
);

test(
  'number division expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 2 / 2;',
  'var a = 1;'
);

test(
  'number exponential expression reduced',
  [babelES7Transform],
  'var a = 4 ** 2;',
  'var a = 16;'
);

test(
  'number mixed expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 2 * 2 + 2 * 2;',
  'var a = 8;'
);

test(
  'inferred number expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = 2 + 2; var b = a * 2;',
  'var a = 4;var b = 8;'
);

test(
  'number library abs calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.abs(-2);',
  'var a = 2;'
);

test(
  'number library cbrt calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.cbrt(27);',
  'var a = 3;'
);

test(
  'number library ceil calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.ceil(2.1);',
  'var a = 3;'
);

test(
  'number library max calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.max(-1, 2, -2);',
  'var a = 2;'
);

test(
  'number library min calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.min(-1, 2, -2);',
  'var a = -2;'
);

test(
  'number library pow calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.pow(2, 3);',
  'var a = 8;'
);

test(
  'number library Math.random calls not reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = Math.random();',
  'var a = Math.random();'
);

test(
  'number expression with variable partially reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = b + 2 * 2;',
  'var a = b + 4;'
);

test(
  'constant single quoted string unchanged',
  [babelES5Transform],
  'var a = \'a\';',
  'var a = \'a\';'
);

test(
  'constant double quoted string unchanged',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "a";',
  'var a = "a";'
);

test(
  'single quoted string concat expression reduced',
  [babelES5Transform],
  'var a = \'a\' + \'a\';',
  'var a = \'aa\';'
);

test(
  'double quoted string concat expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "a" + "a";',
  'var a = "aa";'
);

test(
  'inferred string concat expression reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "a"; var b = a + "a";',
  'var a = "a";var b = "aa";'
);

test(
  'string libary charAt calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "abc".charAt(1);',
  'var a = "b";'
);

test(
  'string libary trim calls reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "  a  ".trim();',
  'var a = "a";'
);

test(
  'string expression with variable partially reduced',
  [babelES5Transform, babelES6Transform, babelES7Transform],
  'var a = "a" + "b" + c;',
  'var a = "ab" + c;'
);


text:
(function()
{
	function addCombo( editor, comboName, styleType, lang, entries, defaultLabel, styleDefinition )
	{
		var config = editor.config;

		// Gets the list of fonts from the settings.
		var names = entries.split( ';' ),
			values = [];

		// Create style objects for all fonts.
		var styles = {};
		for ( var i = 0 ; i < names.length ; i++ )
		{
			var vars = {};
			var parts = names[ i ].split( '/' );

			var name = names[ i ] = parts[ 0 ];
			vars[ styleType ] = values[ i ] = parts[ 1 ] || name;

			styles[ name ] = new CKEDITOR.style( styleDefinition, vars );
		}

		editor.ui.addRichCombo( comboName,
			{
				label : lang.label,
				title : lang.panelTitle,
				voiceLabel : lang.voiceLabel,
				className : 'cke_' + ( styleType == 'size' ? 'fontSize' : 'font' ),
				multiSelect : false,

				panel :
				{
					css : [ CKEDITOR.getUrl( editor.skinPath + 'editor.css' ) ].concat( config.contentsCss ),
					voiceLabel : lang.panelVoiceLabel
				},

				init : function()
				{
					this.startGroup( lang.panelTitle );

					for ( var i = 0 ; i < names.length ; i++ )
					{
						var name = names[ i ];

						// Add the tag entry to the panel list.
						this.add( name, '' + name + '', name );
					}
				},

				onClick : function( value )
				{
					editor.focus();
					editor.fire( 'saveSnapshot' );

					var style = styles[ value ];

					if ( this.getValue() == value )
						style.remove( editor.document );
					else
						style.apply( editor.document );

					editor.fire( 'saveSnapshot' );
				},

				onRender : function()
				{
					editor.on( 'selectionChange', function( ev )
						{
							var currentValue = this.getValue();

							var elementPath = ev.data.path,
								elements = elementPath.elements;

							// For each element into the elements path.
							for ( var i = 0, element ; i < elements.length ; i++ )
							{
								element = elements[i];

								// Check if the element is removable by any of
								// the styles.
								for ( var value in styles )
								{
									if ( styles[ value ].checkElementRemovable( element, true ) )
									{
										if ( value != currentValue )
											this.setValue( value );
										return;
									}
								}
							}

							// If no styles match, just empty it.
							this.setValue( '', defaultLabel );
						},
						this);
				}
			});
	}

	CKEDITOR.plugins.add( 'font',
	{
		requires : [ 'richcombo', 'styles' ],

		init : function( editor )
		{
			var config = editor.config;

			addCombo( editor, 'Font', 'family', editor.lang.font, config.font_names, config.font_defaultLabel, config.font_style );
			addCombo( editor, 'FontSize', 'size', editor.lang.fontSize, config.fontSize_sizes, config.fontSize_defaultLabel, config.fontSize_style );
		}
	});
})();

/**
 * The list of fonts names to be displayed in the Font combo in the toolbar.
 * Entries are separated by semi-colons (;), while it's possible to have more
 * than one font for each entry, in the HTML way (separated by comma).
 *
 * A display name may be optionally defined by prefixing the entries with the
 * name and the slash character. For example, "Arial/Arial, Helvetica, sans-serif"
 * will be displayed as "Arial" in the list, but will be outputted as
 * "Arial, Helvetica, sans-serif".
 * @type String
 * @example
 * config.font_names =
 *     'Arial/Arial, Helvetica, sans-serif;' +
 *     'Times New Roman/Times New Roman, Times, serif;' +
 *     'Verdana';
 * @example
 * config.font_names = 'Arial;Times New Roman;Verdana';
 */
CKEDITOR.config.font_names =
	'Arial/Arial, Helvetica, sans-serif;' +
	'Comic Sans MS/Comic Sans MS, cursive;' +
	'Courier New/Courier New, Courier, monospace;' +
	'Georgia/Georgia, serif;' +
	'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
	'Tahoma/Tahoma, Geneva, sans-serif;' +
	'Times New Roman/Times New Roman, Times, serif;' +
	'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
	'Verdana/Verdana, Geneva, sans-serif';

/**
 * The text to be displayed in the Font combo is none of the available values
 * matches the current cursor position or text selection.
 * @type String
 * @example
 * // If the default site font is Arial, we may making it more explicit to the end user.
 * config.font_defaultLabel = 'Arial';
 */
CKEDITOR.config.font_defaultLabel = '';

/**
 * The style definition to be used to apply the font in the text.
 * @type Object
 * @example
 * // This is actually the default value for it.
 * config.font_style =
 *     {
 *         element		: 'span',
 *         styles		: { 'font-family' : '#(family)' },
 *         overrides	: [ { element : 'font', attributes : { 'face' : null } } ]
 *     };
 */
CKEDITOR.config.font_style =
	{
		element		: 'span',
		styles		: { 'font-family' : '#(family)' },
		overrides	: [ { element : 'font', attributes : { 'face' : null } } ]
	};

/**
 * The list of fonts size to be displayed in the Font Size combo in the
 * toolbar. Entries are separated by semi-colons (;).
 *
 * Any kind of "CSS like" size can be used, like "12px", "2.3em", "130%",
 * "larger" or "x-small".
 *
 * A display name may be optionally defined by prefixing the entries with the
 * name and the slash character. For example, "Bigger Font/14px" will be
 * displayed as "Bigger Font" in the list, but will be outputted as "14px".
 * @type String
 * @default '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px'
 * @example
 * config.fontSize_sizes = '16/16px;24/24px;48/48px;';
 * @example
 * config.fontSize_sizes = '12px;2.3em;130%;larger;x-small';
 * @example
 * config.fontSize_sizes = '12 Pixels/12px;Big/2.3em;30 Percent More/130%;Bigger/larger;Very Small/x-small';
 */
CKEDITOR.config.fontSize_sizes =
	'8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px';

/**
 * The text to be displayed in the Font Size combo is none of the available
 * values matches the current cursor position or text selection.
 * @type String
 * @example
 * // If the default site font size is 12px, we may making it more explicit to the end user.
 * config.fontSize_defaultLabel = '12px';
 */
CKEDITOR.config.fontSize_defaultLabel = '';

/**
 * The style definition to be used to apply the font size in the text.
 * @type Object
 * @example
 * // This is actually the default value for it.
 * config.fontSize_style =
 *     {
 *         element		: 'span',
 *         styles		: { 'font-size' : '#(size)' },
 *         overrides	: [ { element : 'font', attributes : { 'size' : null } } ]
 *     };
 */
CKEDITOR.config.fontSize_style =
	{
		element		: 'span',
		styles		: { 'font-size' : '#(size)' },
		overrides	: [ { element : 'font', attributes : { 'size' : null } } ]
	};


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;

namespace Microsoft.CodeAnalysis.Completion
{
    internal sealed class CompletionViewOptions
    {
        private const string FeatureName = "CompletionOptions";

        public static readonly PerLanguageOption2<bool> HighlightMatchingPortionsOfCompletionListItems =
            new(FeatureName, nameof(HighlightMatchingPortionsOfCompletionListItems), defaultValue: true,
            storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.HighlightMatchingPortionsOfCompletionListItems"));

        public static readonly PerLanguageOption2<bool> ShowCompletionItemFilters =
            new(FeatureName, nameof(ShowCompletionItemFilters), defaultValue: true,
            storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowCompletionItemFilters"));

        // Use tri-value so the default state can be used to turn on the feature with experimentation service.
        public static readonly PerLanguageOption2<bool?> EnableArgumentCompletionSnippets =
            new(FeatureName, nameof(EnableArgumentCompletionSnippets), defaultValue: null,
            storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.EnableArgumentCompletionSnippets"));

        public static readonly PerLanguageOption2<bool> BlockForCompletionItems =
            new(FeatureName, nameof(BlockForCompletionItems), defaultValue: true,
            storageLocation: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.BlockForCompletionItems"));
    }
}


text:
import pathwayElement from './pathway';

describe('Pathway element', () => {
  describe('pathway setting on', () => {
    describe('pathway data present', () => {
      let nodes = [];
      beforeAll(() => {
        const report = {
          pathway: [
            { id: 1, term: 'a' },
            { id: 2, term: 'b' },
          ],
          uniprot: ['abc'],
        };
        const settings = {
          pathway: true,
        };
        nodes = pathwayElement(report, settings);
      });

      it('should return a header link with UniProt accession', () => {
        const a = nodes[1].children[0].children[1];
        const expected = 'https://www.uniprot.org/uniprot/abc#section_x-ref_pathway';
        expect(a.href).toBe(expected);
      });

      it('should return a list', () => {
        const ul = nodes[1].children[1];
        expect(ul).not.toBeNull();
        expect(ul.tag).toBe('ul');
      });

      it('should return two list elements', () => {
        const ul = nodes[1].children[1];
        expect(ul.children.length).toBe(2);
      });

      it('should have pathway text in list links', () => {
        const li = nodes[1].children[1].children[0];
        expect(li.children[0].textContent).toBe('a');
      });

      it('should link to pathway ID in list links', () => {
        const a = nodes[1].children[1].children[0].children[1];
        const expected = 'https://reactome.org/PathwayBrowser/#1&FLG=abc';
        expect(a.href).toBe(expected);
      });
    });

    describe('pathway data empty', () => {
      let nodes;

      beforeAll(() => {
        const report = {
          pathway: [],
          uniprot: ['abc'],
        };
        const settings = {
          pathway: true,
        };
        nodes = pathwayElement(report, settings);
      });

      it('should return a header link with UniProt accession', () => {
        const a = nodes[1].children[0].children[1];
        const expected = 'https://www.uniprot.org/uniprot/abc#section_x-ref_pathway';
        expect(a.href).toBe(expected);
      });

      it('should return not found text', () => {
        const div = nodes[1].children[1];
        const expected = 'no Reactome data';
        expect(div.textContent).toBe(expected);
      });
    });

    describe('pathway data missing', () => {
      let nodes;

      beforeAll(() => {
        const report = {
          uniprot: ['abc'],
        };
        const settings = {
          pathway: true,
        };
        nodes = pathwayElement(report, settings);
      });

      it('should return a header link with UniProt accession', () => {
        const a = nodes[1].children[0].children[1];
        const expected = 'https://www.uniprot.org/uniprot/abc#section_x-ref_pathway';
        expect(a.href).toBe(expected);
      });

      it('should return not found text', () => {
        const div = nodes[1].children[1];
        const expected = 'no Reactome data';
        expect(div.textContent).toBe(expected);
      });
    });
  });

  describe('pathway setting off', () => {
    let nodes;

    beforeAll(() => {
      const report = {};
      const settings = {
        pathway: false,
      };
      nodes = pathwayElement(report, settings);
    });

    it('should return an empty string', () => {
      expect(nodes).toEqual([]);
    });
  });
});


text:
#ifndef BOOST_SMART_PTR_DETAIL_SP_IF_ARRAY_HPP
#define BOOST_SMART_PTR_DETAIL_SP_IF_ARRAY_HPP

#include <boost/smart_ptr/shared_ptr.hpp>

namespace pdalboost {
    namespace detail {
        template<class T>
        struct sp_if_array;

        template<class T>
        struct sp_if_array<T[]> {
            typedef pdalboost::shared_ptr<T[]> type;
        };

        template<class T>
        struct sp_if_size_array;

        template<class T, std::size_t N>
        struct sp_if_size_array<T[N]> {
            typedef pdalboost::shared_ptr<T[N]> type;
        };
    }
}

#endif


text:
describe('oauth', function () {

    var expect = require('chai').expect,
        oauth = require('oauth').OAuth,
        _ = require('underscore'),
        fitbitKeys = require('../../../../../../oauth/fitbit-private').settings
        ;

    var testOauth;

    beforeEach(function () {
        testOauth = new oauth(
            fitbitKeys.requestTokenUrl,
            fitbitKeys.accessTokenUrl,
            fitbitKeys.consumerKey,
            fitbitKeys.consumerSecret,
            fitbitKeys.version,
            fitbitKeys.callbackUrl,
            fitbitKeys.signatureMethod
        );
    });

    it('should get statuses', function (done) {
        testOauth.get(
            "http://api.fitbit.com/1/user/-/foods/log/date/2012-01-01.json",
            fitbitKeys.awanrky.accessToken, fitbitKeys.awanrky.accessTokenSecret,
            function (error, data) {
                if (error) done(require('sys').inspect(error));
                var response = JSON.parse(data);
                expect(response.summary.calories).to.equal(0);
                done();
            }
        );
    });

});


text:
{% extends "base.html" %}

{% block main %}

Activities

                    {% if activities %}
                    {% for activity in activities %}

                            <input class="palette" type="text" value="" style="background-color: {{ activity['color'] }};" disabled />

                            {{ activity['title'] }}

                            <input type="text" value="{{ activity['title'] }}" />

                    {% end %}
                    {% else %}

You have no activities, create one using the form to the right.

                    {% end %}

New activity

                        <form id="create-activity" action="/api/activity" method="POST" data-validation>
                            <fieldset>
                                Title
                                <input type="text" name="title" id="title"
                                    data-validator="required"
                                    data-validator-on="focus-loss" />
                            </fieldset>
                            <fieldset>
                                Color
                                <input type="text" name="color" id="color" class="palette"
                                    data-palette-mode="show-code"
                                    data-validator="required"
                                    style="background-color: #fff" value="#fff" />
                            </fieldset>
                            <fieldset>
                                <button type="submit">Create</button>
                            </fieldset>
                        </form>

{% end %}


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.github.sakserv.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyParser {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyParser.class);

    private Properties props = new Properties();
    private String propFileName;

    public String getPropFileName() {
        return propFileName;
    }

    public void setPropFileName(String propFileName) {
        this.propFileName = propFileName;
    }

    public String getProperty(String key) {
        return props.get(key).toString();
    }

    public void parsePropsFile() throws IOException {

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

        try {
            if (null != inputStream) {
                props.load(inputStream);
            } else {
                throw new IOException("Could not load property file from the resources directory, trying local");
            }
        } catch(IOException e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                inputStream = new FileInputStream(new File(propFileName).getAbsolutePath());
                props.load(inputStream);
            } catch (IOException ex) {
                LOG.error("Could not load property file at " + new File(propFileName).getAbsolutePath());
                ex.printStackTrace();
                throw ex;
            }
        }
    }
}


text:
package com.opengamma.analytics.financial.interestrate;

import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionMarginSecurity;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionMarginTransaction;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionPremiumSecurity;
import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionPremiumTransaction;
import com.opengamma.analytics.financial.interestrate.future.method.InterestRateFutureOptionMarginSecurityBlackSurfaceMethod;
import com.opengamma.analytics.financial.interestrate.swaption.derivative.SwaptionPhysicalFixedIbor;
import com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionPhysicalFixedIborBlackMethod;
import com.opengamma.analytics.financial.model.option.definition.YieldCurveWithBlackCubeBundle;
import com.opengamma.util.ArgumentChecker;

/**
 * Interpolates, for interest rate instruments using Black model, and returns the implied volatility required.
 */
public final class ImpliedVolatilityBlackCalculator extends AbstractInstrumentDerivativeVisitor<YieldCurveBundle, Double> {

  /**
   * The method unique instance.
   */
  private static final ImpliedVolatilityBlackCalculator INSTANCE = new ImpliedVolatilityBlackCalculator();

  /**
   * Return the unique instance of the class.
   * @return The instance.
   */
  public static ImpliedVolatilityBlackCalculator getInstance() {
    return INSTANCE;
  }

  /**
   * Constructor.
   */
  ImpliedVolatilityBlackCalculator() {
  }

  /**
   * The methods used in the calculator.
   */
  private static final SwaptionPhysicalFixedIborBlackMethod METHOD_SWAPTION_PHYSICAL = SwaptionPhysicalFixedIborBlackMethod.getInstance();
  private static final InterestRateFutureOptionMarginSecurityBlackSurfaceMethod METHOD_MARGINED_FUTUREOPTION = InterestRateFutureOptionMarginSecurityBlackSurfaceMethod.getInstance();

  @Override
  public Double visitSwaptionPhysicalFixedIbor(final SwaptionPhysicalFixedIbor swaption, final YieldCurveBundle curves) {
    return METHOD_SWAPTION_PHYSICAL.impliedVolatility(swaption, curves);
  }

  @Override
  public Double visitInterestRateFutureOptionMarginSecurity(final InterestRateFutureOptionMarginSecurity option, final YieldCurveBundle curves) {
    return METHOD_MARGINED_FUTUREOPTION.impliedVolatility(option, curves);
  }

  @Override
  public Double visitInterestRateFutureOptionMarginTransaction(final InterestRateFutureOptionMarginTransaction option, final YieldCurveBundle curves) {
    return METHOD_MARGINED_FUTUREOPTION.impliedVolatility(option.getUnderlyingOption(), curves);
  }

  @Override
  public Double visitInterestRateFutureOptionPremiumTransaction(final InterestRateFutureOptionPremiumTransaction option, final YieldCurveBundle curves) {
    ArgumentChecker.notNull(curves, "curves");
    ArgumentChecker.notNull(option, "option");
    if (curves instanceof YieldCurveWithBlackCubeBundle) {
      final InterestRateFutureOptionPremiumSecurity underlyingOption = option.getUnderlyingOption();
      final InterestRateFutureOptionMarginSecurity underlyingMarginedOption = new InterestRateFutureOptionMarginSecurity(underlyingOption.getUnderlyingFuture(), underlyingOption.getExpirationTime(),
          underlyingOption.getStrike(), underlyingOption.isCall());
      return METHOD_MARGINED_FUTUREOPTION.impliedVolatility(underlyingMarginedOption, curves);
    }
    throw new UnsupportedOperationException("The PresentValueBlackCalculator visitor visitInterestRateFutureOptionPremiumTransaction requires a YieldCurveWithBlackCubeBundle as data.");
  }

}


text:
import ServerActions from '../action/server';
import $ from 'jquery';

export default {
	/**
	 *
	 */
	login (credentials) {
		return $.post('/auth/login', credentials);
	},

	/**
	 *
	 */
	register (credentials) {
		return $.post('/auth/register', credentials);
	},

	/**
	 *
	 */
	logout () {
		return $.get('/auth/logout');
	},

	/**
	 *
	 */
	fetchUsers () {
		return $.get('/user');
	}
}


text:
using System;

using Xamarin.Forms;

namespace XamarinFormsCells
{
	public class SampleCellsDemo : TabbedPage
	{
		public SampleCellsDemo ()
		{
			Children.Add (new EntryCellDemo ());
			Children.Add (new SwitchCellDemo ());
			Children.Add (new TextCellDemo ());
			Children.Add (new ImageCellDemo ());
		}
	}

	public class EntryCellDemo : ContentPage {
		public EntryCellDemo ()
		{
			var tableView = new TableView {
				Intent = TableIntent.Form,
				Root = new TableRoot {
					new TableSection {
						new EntryCell {
							Label = "Entry Cell:",
							Placeholder = "Enter some data",

						}
					}
				}
			};

			Title = "Entry";
			Content = tableView;
		}
	}

	public class SwitchCellDemo : ContentPage {
		public SwitchCellDemo ()
		{
			var tableView = new TableView {
				Intent = TableIntent.Form,
				Root = new TableRoot {
					new TableSection {
						new SwitchCell {
							Text = "Switch Cell:"
						}
					}
				}
			};

			Title = "Switch";
			Content = tableView;
		}
	}

	public class TextCellDemo : ContentPage {
		public TextCellDemo ()
		{
			var tableView = new TableView {
				Intent = TableIntent.Form,
				Root = new TableRoot {
					new TableSection {
						new TextCell {
							Text = "Primary Text",
							Detail = "Secondary Text"
						}
					}
				}
			};

			Title = "Text";
			Content = tableView;
		}
	}

	public class ImageCellDemo : ContentPage {
		public ImageCellDemo ()
		{
			var tableView = new TableView {
				Intent = TableIntent.Form,
				Root = new TableRoot {
					new TableSection {
						new ImageCell {
							ImageSource = ImageSource.FromUri(new Uri("http://placehold.it/50x50")),
							Text = "Primary Text",
							Detail = "Secondary Text"
						}
					}
				}
			};

			Title = "Image";
			Content = tableView;
		}
	}
}


text:
from __future__ import division, print_function
import numpy as np

from BDProjects.Client import Connector, Client

client = Client(Connector(config_file_name='config.ini'))

client.user_manager.sign_in('john_smith', 'secret_password')

project_name = 'Super Project'
project = client.user_manager.project_manager.open_project(project_name)
print(project)

sample = client.user_manager.sample_manager.get_samples(name='SCF343')[0]
tool = client.user_manager.equipment_manager.get_equipment(name='Super setup')[0]
measurement_type = client.user_manager.measurement_type_manager.get_measurement_types('IV measurement')[0]

measurement = client.user_manager.measurement_manager.get_measurements(name='Test IV measurement')
if measurement:
    measurement = measurement[0]
else:
    measurement = client.user_manager.measurement_manager.create_measurement(name='Test IV measurement',
                                                                             measurement_type=measurement_type,
                                                                             equipment=tool,
                                                                             description='Fake measurement for testing')
client.user_manager.measurement_manager.add_sample_to_measurement(measurement, sample)
current_meter_channel = client.user_manager.measurement_manager.create_data_channel(name='Current channel',
                                                                                measurement=measurement,
                                                                                description='Current meter channel',
                                                                                unit_name='A')
voltmeter_channel = client.user_manager.measurement_manager.create_data_channel(name='Voltage channel',
                                                                                measurement=measurement,
                                                                                description='Voltmeter channel',
                                                                                unit_name='V')
print(measurement)

current_points = np.linspace(-1, 1, num=11, endpoint=True)
index = range(current_points.size)
resistance = 10
voltage_points = resistance * np.copy(current_points)

print('Measurement progress:', measurement.progress)
if measurement.finished is None:
    client.user_manager.measurement_manager.create_data_points(channel=current_meter_channel,
                                                               float_value=current_points,
                                                               point_index=index)
    client.user_manager.measurement_manager.create_data_points(channel=voltmeter_channel,
                                                               float_value=voltage_points,
                                                               point_index=index)
    client.user_manager.measurement_manager.update_measurement_progress(measurement=measurement,
                                                                        progress=100)
    client.user_manager.measurement_manager.finish_measurement(measurement=measurement)
print('Measurement finished:', measurement.finished)

i_data = client.user_manager.measurement_manager.get_data_points_array(channel=current_meter_channel)
v_data = client.user_manager.measurement_manager.get_data_points_array(channel=voltmeter_channel)
print(i_data[:, 0])
print(v_data)

client.user_manager.measurement_manager.delete_measurement(measurement)
#client.user_manager.measurement_manager.delete_data_points(channel=voltmeter_channel,
#                                                           point_index=index[:5])

dp = client.user_manager.parameter_manager.get_dangling_parameters(delete=True)

client.user_manager.sign_out()

#client.user_manager.delete_user('john_smith', 'secret_password')


text:
'use strict';

var http = require('http'),
    colors = require('colors'),
    createApp = require('./app');

colors.enabled = true;

module.exports = function startServer(config, appInitCb) {

    var app,
        server;

    // create the express app
    app = createApp(config, appInitCb);

    // Create server
    server = http.createServer(app);

    // Limits maximum incoming headers count
    server.maxHeadersCount = config.maxHeadersCount;

    // Inactivity before a socket is presumed to have timed out
    server.timeout = config.serverTimeout;

    // Start the server on port
    server.listen(config.port, function listenCb() {
        console.info(colors.black.bold.bgGreen('server listening: \nport "%d" \nmode "%s"'), config.port, config.environment);
    });

    return server;
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: bill
 * Date: 03.09.15
 * Time: 12:51
 */

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\db\Query;
use yii\helpers\Inflector;
use yii\rbac\DbManager;
use yii\rbac\Item;
use yii\rbac\Permission;
use yii\rbac\Role;

/**
 * Class RoleForm
 *
 * @package backend\models
 * @property array $availableRoles
 * @property array $availablePermissions
 *
 */
class RoleForm extends Model
{
    const SCOPE_PARENTS = 0;
    const SCOPE_CHILDREN = 1;
    public $name;
    public $description;
    public $updatedAt;
    public $childRoles = [];
    public $childPermissions = [];

    public function scenarios()
    {
        return [
            'create' => ['name', 'description', 'childRoles', 'childPermissions'],
            'update' => ['description', 'childRoles', 'childPermissions'],
        ];
    }

    public function rules()
    {
        return [
            [['name', 'description'], 'required'],
            ['name', 'validateName'],
            [['childRoles', 'childPermissions'], 'filter', 'filter' => function ($value) {
                return empty($value) ? [] : $value;
            }]
        ];
    }

    public function validateName($attribute)
    {
        $name = Inflector::camelize(Inflector::slug($this->$attribute));
        $label = $this->getAttributeLabel($attribute);

        if (empty($name)) {
            $this->addError($attribute, "'$label' должно состоять только из букв и цифр");
        } else {
            $this->$attribute = $name;
        }
    }

    public function attributeLabels()
    {
        return [
            'name' => 'Название',
            'description' => 'Описание',
            'childRoles' => 'Дочерние роли',
            'childPermissions' => 'Дочерние привилегии'
        ];
    }

    /**
     * @return bool
     */
    public function create()
    {
        $authManager = Yii::$app->getAuthManager();
        if ($this->validate()) {
            $role = $authManager->createRole($this->name);
            $role->description = $this->description;
            if ($authManager->add($role)) {
                $this->addChildren($role);
                return true;
            }
        }
        return false;
    }

    /**
     * @param Role $role
     * @return bool
     */
    public function update(Role $role)
    {
        $authManager = Yii::$app->getAuthManager();
        if ($this->validate()) {
            $role->description = $this->description;
            $authManager->removeChildren($role);
            $this->addChildren($role);
            return $authManager->update($role->name, $role);
        }
        return false;
    }

    /**
     * @return array
     */
    public function getAvailableRoles()
    {
        /** @var DbManager $authManager */
        $authManager = Yii::$app->authManager;
        $roles = (new Query())->select(['name','description'])->from($authManager->itemTable)->where(['type' => Item::TYPE_ROLE])->indexBy('name')->all();
        $parents = Yii::$app->getDb()->createCommand('call relativeItems("'.$this->name.'",'.self::SCOPE_PARENTS.')')->queryAll();

        foreach ($parents as $parent) {
            unset($roles[$parent['item']]);
        }
        unset($roles[$this->name], $roles[Yii::$app->params['admin.role']]);

        return array_map(function($item){return $item['description'];},$roles);
    }

    /**
     * @return array
     */
    public function getAvailablePermissions()
    {
        /** @var DbManager $authManager */
        $authManager = Yii::$app->authManager;
        $systemPermissionsQuery = (new Query())->select(['name','description'])->from($authManager->itemTable)->where(['type' => Item::TYPE_PERMISSION]);
        $childPermissionsQuery = Yii::$app->getDb()->createCommand('call relativeItems("'.$this->name.'",'.self::SCOPE_CHILDREN.')');
        $children = array_map(function($item){return $item['item'];}, $childPermissionsQuery->queryAll());

        $permissions = [];
        foreach ($systemPermissionsQuery->all() as $item) {
            if(!in_array($item['name'], $children) || in_array($item['name'], $this->childPermissions)){
                $permissions[$item['name']] = $item['description'];
            }
        }

        return $permissions;
    }

    /**
     * @param Role $role
     * @return void
     */
    private function addChildren(Role $role)
    {
        $authManager = Yii::$app->getAuthManager();
        foreach ($this->childRoles as $child) {
            $authManager->addChild($role, $authManager->getRole($child));
        }
        foreach ($this->childPermissions as $child) {
            $authManager->addChild($role, $authManager->getPermission($child));
        }
    }

    /**
     * @return void
     */
    public function initChildren()
    {
        if (isset($this->name)) {
            foreach (Yii::$app->authManager->getChildren($this->name) as $child) {
                if ($child instanceof Role) {
                    $this->childRoles[] = $child->name;
                } elseif ($child instanceof Permission) {
                    $this->childPermissions[] = $child->name;
                }
            }
        }
    }
}


text:
require 'spec_helper'

describe DashboardController do

  it 'GET #show' do
    sign_in_as_admin
    get :show
    assert_redirected_to inbox_account_conversations_path(@account)
  end

end


text:
The `Solarflare` app drives one port of a Solarflare SFN7 Ethernet
controller. Multiple instances of the Solarflare app can be instantiated
on the same PCI device. Packets received from the network will be
dispatched between apps based on destination MAC address and VLAN.
Packets taken from the `rx` port are transmitted onto the network.
Packets received from the network are put on the `tx` port.

![Solarflare](.images/Solarflare.png)

### Configuration

The `Solarflare` app accepts a table as its configuration argument. The
following keys are defined:

— Key **pciaddr**

*Required*. The PCI address of the NIC as a string.

— Key **macaddr**

*Optional*. The MAC address to use as a string. The default is a
wild-card (e.g. accept all packets).

— Key **vlan**

*Optional*. A twelve bit integer (0-4095). If set, incoming packets from
other VLANs are dropped and outgoing packets are tagged with a VLAN
header.


text:
<?php
namespace Icecave\Chrono\Doctrine;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\StringType;
use Icecave\Chrono\TimeZone;

/**
 * A type for utilizing Chrono timezones.
 */
class TimeZoneType extends StringType
{
    /**
     * Get the name.
     *
     * @return string The name.
     */
    public function getName()
    {
        return 'chrono_timezone';
    }

    /**
     * If this Doctrine Type maps to an already mapped database type,
     * reverse schema engineering can't take them apart. You need to mark
     * one of those types as commented, which will have Doctrine use an SQL
     * comment to typehint the actual Doctrine Type.
     *
     * @param AbstractPlatform $platform
     *
     * @return boolean
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }

    /**
     * Convert the supplied database value to its PHP equivalent.
     *
     * @param mixed            $value    The database value.
     * @param AbstractPlatform $platform The platform to use.
     *
     * @return mixed               The converted value.
     * @throws ConversionException If conversion fails.
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if (null === $value) {
            return null;
        }

        return TimeZone::fromIsoString($value);
    }

    /**
     * Convert the supplied PHP value to its database equivalent.
     *
     * @param mixed            $value    The PHP value.
     * @param AbstractPlatform $platform The platform to use.
     *
     * @return mixed               The converted value.
     * @throws ConversionException If conversion fails.
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (null === $value) {
            return null;
        } elseif (!$value instanceof TimeZone) {
            throw ConversionException::conversionFailed(
                $value,
                $this->getName()
            );
        }

        return $value->isoString();
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path");
var logger_1 = require("../logger/logger");
var Constants = require("../util/constants");
var helpers_1 = require("../util/helpers");
var typescript_utils_1 = require("../util/typescript-utils");
var typescript_1 = require("typescript");
function calculateUnusedComponents(dependencyMap) {
    return calculateUnusedComponentsImpl(dependencyMap, getIonicModuleFilePath());
}
exports.calculateUnusedComponents = calculateUnusedComponents;
function calculateUnusedComponentsImpl(dependencyMap, importee) {
    var filteredMap = filterMap(dependencyMap);
    processImportTree(filteredMap, importee);
    calculateUnusedIonicProviders(filteredMap);
    return generateResults(filteredMap);
}
exports.calculateUnusedComponentsImpl = calculateUnusedComponentsImpl;
function generateResults(dependencyMap) {
    var toPurgeMap = new Map();
    var updatedMap = new Map();
    dependencyMap.forEach(function (importeeSet, modulePath) {
        if ((importeeSet && importeeSet.size > 0) || requiredModule(modulePath)) {
            logger_1.Logger.debug("[treeshake] generateResults: " + modulePath + " is not purged");
            updatedMap.set(modulePath, importeeSet);
        }
        else {
            logger_1.Logger.debug("[treeshake] generateResults: " + modulePath + " is purged");
            toPurgeMap.set(modulePath, importeeSet);
        }
    });
    return {
        updatedDependencyMap: updatedMap,
        purgedModules: toPurgeMap
    };
}
function requiredModule(modulePath) {
    var mainJsFile = helpers_1.changeExtension(helpers_1.getStringPropertyValue(Constants.ENV_APP_ENTRY_POINT), '.js');
    var mainTsFile = helpers_1.changeExtension(helpers_1.getStringPropertyValue(Constants.ENV_APP_ENTRY_POINT), '.ts');
    var appModule = helpers_1.changeExtension(helpers_1.getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH), '.js');
    var appModuleNgFactory = getAppModuleNgFactoryPath();
    var moduleFile = getIonicModuleFilePath();
    var menuTypes = path_1.join(path_1.dirname(helpers_1.getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT)), 'components', 'menu', 'menu-types.js');
    return modulePath === mainJsFile
        || modulePath === mainTsFile
        || modulePath === appModule
        || modulePath === appModuleNgFactory
        || modulePath === moduleFile
        || modulePath === menuTypes;
}
function filterMap(dependencyMap) {
    var filteredMap = new Map();
    dependencyMap.forEach(function (importeeSet, modulePath) {
        if (isIonicComponentOrAppSource(modulePath) || modulePath === getIonicModuleFilePath()) {
            importeeSet.delete(helpers_1.getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT));
            filteredMap.set(modulePath, importeeSet);
        }
    });
    return filteredMap;
}
function processImportTree(dependencyMap, importee) {
    var importees = [];
    dependencyMap.forEach(function (importeeSet, modulePath) {
        if (importeeSet && importeeSet.has(importee)) {
            importeeSet.delete(importee);
            // if it importer by an `ngfactory` file, we probably aren't going to be able to purge it
            var ngFactoryImportee = false;
            var importeeList = Array.from(importeeSet);
            for (var _i = 0, importeeList_1 = importeeList; _i < importeeList_1.length; _i++) {
                var entry = importeeList_1[_i];
                if (isNgFactory(entry)) {
                    ngFactoryImportee = true;
                    break;
                }
            }
            if (!ngFactoryImportee) {
                importees.push(modulePath);
            }
        }
    });
    importees.forEach(function (importee) { return processImportTree(dependencyMap, importee); });
}
function calculateUnusedIonicProviders(dependencyMap) {
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: beginning to purge providers");
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to purge action sheet controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to purge alert controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_ALERT_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to loading controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_LOADING_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to modal controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_MODAL_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to picker controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_PICKER_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to popover controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_CONTROLLER_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to toast controller");
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_TOAST_CONTROLLER_PATH));
    // check if the controllers were deleted, if so, purge the component too
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to action sheet component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to alert component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_ALERT_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_ALERT_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_ALERT_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to loading component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_LOADING_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_LOADING_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_LOADING_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to modal component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_MODAL_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_MODAL_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_MODAL_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to picker component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_PICKER_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_PICKER_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_PICKER_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to popover component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_COMPONENT_FACTORY_PATH));
    logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to toast component");
    processIonicOverlayComponents(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_TOAST_VIEW_CONTROLLER_PATH), helpers_1.getStringPropertyValue(Constants.ENV_TOAST_COMPONENT_PATH), helpers_1.getStringPropertyValue(Constants.ENV_TOAST_COMPONENT_FACTORY_PATH));
    // in this case, it's actually an entry component, not a provider
    processIonicProviders(dependencyMap, helpers_1.getStringPropertyValue(Constants.ENV_SELECT_POPOVER_COMPONENT_FACTORY_PATH));
}
function processIonicOverlayComponents(dependencyMap, viewControllerPath, componentPath, componentFactoryPath) {
    var viewControllerImportees = dependencyMap.get(viewControllerPath);
    var componentImportees = dependencyMap.get(componentPath);
    if (viewControllerImportees && viewControllerImportees.size === 0 && componentImportees && componentImportees.size === 1 && componentImportees.has(componentFactoryPath)) {
        var componentFactoryImportees = dependencyMap.get(componentFactoryPath);
        var onlyNgModuleFactoryImportees = onlyNgModuleFactories(componentFactoryImportees);
        if (onlyNgModuleFactoryImportees) {
            // sweet, we can remove this bad boy
            dependencyMap.set(componentFactoryPath, new Set());
            componentImportees.delete(componentFactoryPath);
        }
    }
}
function getAppModuleNgFactoryPath() {
    var appNgModulePath = helpers_1.getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH);
    var jsVersion = helpers_1.changeExtension(appNgModulePath, '.js');
    return helpers_1.convertFilePathToNgFactoryPath(jsVersion);
}
exports.getAppModuleNgFactoryPath = getAppModuleNgFactoryPath;
function processIonicProviders(dependencyMap, providerPath) {
    var importeeSet = dependencyMap.get(providerPath);
    var appModuleNgFactoryPath = getAppModuleNgFactoryPath();
    // we can only purge providers that are only referenced in .module.ngfactory.js files
    var onlyNgModuleFactoryImportees = onlyNgModuleFactories(importeeSet);
    if (onlyNgModuleFactoryImportees && importeeSet && importeeSet.has(appModuleNgFactoryPath)) {
        logger_1.Logger.debug("[treeshake] processIonicProviders: Purging " + providerPath);
        importeeSet.delete(appModuleNgFactoryPath);
        // loop over the dependency map and remove this provider from importee sets
        processImportTreeForProviders(dependencyMap, providerPath);
    }
}
function onlyNgModuleFactories(importeeSet) {
    var moduleNgFactoryTs = helpers_1.changeExtension(helpers_1.getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX), '.ngfactory.ts');
    var moduleNgFactoryJs = helpers_1.changeExtension(helpers_1.getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX), '.ngfactory.js');
    var onlyNgModuleFactories = true;
    if (importeeSet) {
        importeeSet.forEach(function (importee) {
            if (onlyNgModuleFactories && !(importee.endsWith(moduleNgFactoryTs) || importee.endsWith(moduleNgFactoryJs))) {
                onlyNgModuleFactories = false;
            }
        });
    }
    return onlyNgModuleFactories;
}
function processImportTreeForProviders(dependencyMap, importee) {
    var importees = [];
    dependencyMap.forEach(function (importeeSet, modulePath) {
        if (importeeSet.has(importee)) {
            importeeSet.delete(importee);
            importees.push(modulePath);
        }
    });
    importees.forEach(function (importee) { return processImportTreeForProviders(dependencyMap, importee); });
}
function isIonicComponentOrAppSource(modulePath) {
    // for now, just use a simple filter of if a file is in ionic-angular/components
    var ionicAngularComponentDir = path_1.join(helpers_1.getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_DIR), 'components');
    var srcDir = helpers_1.getStringPropertyValue(Constants.ENV_VAR_SRC_DIR);
    return modulePath.indexOf(ionicAngularComponentDir) >= 0 || modulePath.indexOf(srcDir) >= 0;
}
exports.isIonicComponentOrAppSource = isIonicComponentOrAppSource;
function isNgFactory(modulePath) {
    return modulePath.indexOf('.ngfactory.') >= 0;
}
exports.isNgFactory = isNgFactory;
function purgeUnusedExportsFromIndexFile(filePath, fileContent, modulePathsToPurge) {
    logger_1.Logger.debug("[treeshake] purgeUnusedExportsFromIndexFile: Starting to purge exports ... ");
    for (var _i = 0, modulePathsToPurge_1 = modulePathsToPurge; _i < modulePathsToPurge_1.length; _i++) {
        var modulePath = modulePathsToPurge_1[_i];
        // I cannot get the './' prefix to show up when using path api
        logger_1.Logger.debug("[treeshake] purgeUnusedExportsFromIndexFile: Removing " + modulePath + " from " + filePath);
        var extensionless = helpers_1.changeExtension(modulePath, '');
        var relativeImportPath = './' + path_1.relative(path_1.dirname(filePath), extensionless);
        var importPath = helpers_1.toUnixPath(relativeImportPath);
        var exportRegex = generateExportRegex(importPath);
        logger_1.Logger.debug("[treeshake] purgeUnusedExportsFromIndexFile: Removing exports with path " + importPath);
        var results = null;
        while ((results = exportRegex.exec(fileContent)) && results.length) {
            fileContent = fileContent.replace(exportRegex, "/*" + results[0] + "*/");
        }
    }
    logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Starting to purge exports ... DONE");
    return fileContent;
}
exports.purgeUnusedExportsFromIndexFile = purgeUnusedExportsFromIndexFile;
function purgeUnusedImportsAndExportsFromModuleFile(moduleFilePath, moduleFileContent, modulePathsToPurge) {
    logger_1.Logger.debug("[treeshake] purgeUnusedImportsAndExportsFromModuleFile: Starting to purge import/exports ... ");
    for (var _i = 0, modulePathsToPurge_2 = modulePathsToPurge; _i < modulePathsToPurge_2.length; _i++) {
        var modulePath = modulePathsToPurge_2[_i];
        // I cannot get the './' prefix to show up when using path api
        logger_1.Logger.debug("[treeshake] purgeUnusedImportsAndExportsFromModuleFile: Removing " + modulePath + " from " + moduleFilePath);
        var extensionless = helpers_1.changeExtension(modulePath, '');
        var relativeImportPath = './' + path_1.relative(path_1.dirname(moduleFilePath), extensionless);
        var importPath = helpers_1.toUnixPath(relativeImportPath);
        logger_1.Logger.debug("[treeshake] purgeUnusedImportsAndExportsFromModuleFile: Removing imports with path " + importPath);
        var importRegex = generateImportRegex(importPath);
        // replace the import if it's found
        var results = null;
        while ((results = importRegex.exec(moduleFileContent)) && results.length) {
            moduleFileContent = moduleFileContent.replace(importRegex, "/*" + results[0] + "*/");
        }
        results = null;
        var exportRegex = generateExportRegex(importPath);
        logger_1.Logger.debug("[treeshake] purgeUnusedImportsAndExportsFromModuleFile: Removing exports with path " + importPath);
        while ((results = exportRegex.exec(moduleFileContent)) && results.length) {
            moduleFileContent = moduleFileContent.replace(exportRegex, "/*" + results[0] + "*/");
        }
    }
    logger_1.Logger.debug("[treeshake] purgeUnusedImportsAndExportsFromModuleFile: Starting to purge import/exports ... DONE");
    return moduleFileContent;
}
exports.purgeUnusedImportsAndExportsFromModuleFile = purgeUnusedImportsAndExportsFromModuleFile;
function generateImportRegex(relativeImportPath) {
    var cleansedString = helpers_1.escapeStringForRegex(relativeImportPath);
    return new RegExp("^import.*?{(.+)}.*?from.*?['\"`]" + cleansedString + "['\"`];", 'gm');
}
function generateExportRegex(relativeExportPath) {
    var cleansedString = helpers_1.escapeStringForRegex(relativeExportPath);
    return new RegExp("^export.*?{(.+)}.*?from.*?'" + cleansedString + "';", 'gm');
}
function purgeComponentNgFactoryImportAndUsage(appModuleNgFactoryPath, appModuleNgFactoryContent, componentFactoryPath) {
    logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Starting to purge component ngFactory import/export ...");
    var extensionlessComponentFactoryPath = helpers_1.changeExtension(componentFactoryPath, '');
    var relativeImportPath = path_1.relative(path_1.dirname(appModuleNgFactoryPath), extensionlessComponentFactoryPath);
    var importPath = helpers_1.toUnixPath(relativeImportPath);
    logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Purging imports from " + importPath);
    var importRegex = generateWildCardImportRegex(importPath);
    var results = importRegex.exec(appModuleNgFactoryContent);
    if (results && results.length >= 2) {
        appModuleNgFactoryContent = appModuleNgFactoryContent.replace(importRegex, "/*" + results[0] + "*/");
        var namedImport = results[1].trim();
        logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Purging code using named import " + namedImport);
        var purgeFromConstructor = generateRemoveComponentFromConstructorRegex(namedImport);
        var purgeFromConstructorResults = purgeFromConstructor.exec(appModuleNgFactoryContent);
        if (purgeFromConstructorResults && purgeFromConstructorResults.length) {
            appModuleNgFactoryContent = appModuleNgFactoryContent.replace(purgeFromConstructor, "/*" + purgeFromConstructorResults[0] + "*/");
        }
    }
    logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Starting to purge component ngFactory import/export ... DONE");
    return appModuleNgFactoryContent;
}
exports.purgeComponentNgFactoryImportAndUsage = purgeComponentNgFactoryImportAndUsage;
function purgeProviderControllerImportAndUsage(moduleNgFactoryPath, moduleNgFactoryContent, providerPath) {
    logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Starting to purge provider controller and usage ...");
    var extensionlessComponentFactoryPath = helpers_1.changeExtension(providerPath, '');
    var relativeImportPath = path_1.relative(path_1.dirname(helpers_1.getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_DIR)), extensionlessComponentFactoryPath);
    var importPath = helpers_1.toUnixPath(relativeImportPath);
    logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Looking for imports from " + importPath);
    var importRegex = generateWildCardImportRegex(importPath);
    var results = importRegex.exec(moduleNgFactoryContent);
    if (results && results.length >= 2) {
        var namedImport = results[1].trim();
        // purge the getter
        var purgeIfRegEx = generateRemoveIfStatementRegex(namedImport);
        var purgeIfResults = purgeIfRegEx.exec(moduleNgFactoryContent);
        if (purgeIfResults) {
            // okay, sweet, find out what is actually returned from this bad boy
            var getNameOfReturnedPropertyRegex = /return this\.(.*?);/g;
            var returnValueResults = getNameOfReturnedPropertyRegex.exec(purgeIfResults[0]);
            if (returnValueResults && returnValueResults.length >= 2) {
                var propertyNameOfProvider = returnValueResults[1];
                var getterRegex = generateRemoveGetterFromImportRegex(namedImport, propertyNameOfProvider);
                var getterRegexResults = getterRegex.exec(moduleNgFactoryContent);
                if (getterRegexResults) {
                    moduleNgFactoryContent = moduleNgFactoryContent.replace(importRegex, "/*" + results[0] + "*/");
                    logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Purging getter logic using " + namedImport);
                    var getterContentToReplace = getterRegexResults[0];
                    var newGetterContent = "/*" + getterContentToReplace + "*/";
                    moduleNgFactoryContent = moduleNgFactoryContent.replace(getterContentToReplace, newGetterContent);
                    logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Purging factory logic using " + namedImport);
                    var purgeIfContentToReplace = purgeIfResults[0];
                    var newPurgeIfContent = "/*" + purgeIfContentToReplace + "*/";
                    moduleNgFactoryContent = moduleNgFactoryContent.replace(purgeIfContentToReplace, newPurgeIfContent);
                }
            }
        }
    }
    logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Starting to purge provider controller and usage ... DONE");
    return moduleNgFactoryContent;
}
exports.purgeProviderControllerImportAndUsage = purgeProviderControllerImportAndUsage;
function purgeProviderClassNameFromIonicModuleForRoot(moduleFileContent, providerClassName) {
    logger_1.Logger.debug("[treeshake] purgeProviderClassNameFromIonicModuleForRoot: Purging reference in the ionicModule forRoot method ...");
    var regex = generateIonicModulePurgeProviderRegex(providerClassName);
    var results = regex.exec(moduleFileContent);
    if (results && results.length) {
        moduleFileContent = moduleFileContent.replace(regex, "/*" + results[0] + "*/");
    }
    logger_1.Logger.debug("[treeshake] purgeProviderClassNameFromIonicModuleForRoot: Purging reference in the ionicModule forRoot method ... DONE");
    return moduleFileContent;
}
exports.purgeProviderClassNameFromIonicModuleForRoot = purgeProviderClassNameFromIonicModuleForRoot;
function generateWildCardImportRegex(relativeImportPath) {
    var cleansedString = helpers_1.escapeStringForRegex(relativeImportPath);
    return new RegExp("import.*?as(.*?)from '" + cleansedString + "';");
}
exports.generateWildCardImportRegex = generateWildCardImportRegex;
function generateRemoveComponentFromConstructorRegex(namedImport) {
    return new RegExp(namedImport + "..*?,");
}
exports.generateRemoveComponentFromConstructorRegex = generateRemoveComponentFromConstructorRegex;
function generateRemoveGetterFromImportRegex(namedImport, propertyName) {
    var regexString = "(Object.defineProperty.*?\"" + propertyName + "\".*?{[\\s\\S]*?" + namedImport + "[\\s\\S]*?}[\\s\\S]*?}[\\s\\S]*?}\\);)";
    return new RegExp(regexString);
}
exports.generateRemoveGetterFromImportRegex = generateRemoveGetterFromImportRegex;
function generateRemoveIfStatementRegex(namedImport) {
    return new RegExp("if \\(\\(token === " + namedImport + ".([\\S]*?)\\)\\) {([\\S\\s]*?)}", "gm");
}
exports.generateRemoveIfStatementRegex = generateRemoveIfStatementRegex;
function generateIonicModulePurgeProviderRegex(className) {
    return new RegExp(className + ",", "gm");
}
exports.generateIonicModulePurgeProviderRegex = generateIonicModulePurgeProviderRegex;
function getIonicModuleFilePath() {
    var entryPoint = helpers_1.getStringPropertyValue(Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT);
    return path_1.join(path_1.dirname(entryPoint), 'module.js');
}
exports.getIonicModuleFilePath = getIonicModuleFilePath;
// okay, so real talk
// the ng4 compiler changed how some of this stuff works.
// basically, due to imports not-really-being-used in AoT mode WRT pages/providers,
// we don't have a good way of detecting whether a provider is actually used in an app
// since they're in the ng-module ng-factories regardless if they're used or not. If that sounds
// confusing and weird - it's because it is.
// the simple answer is this method analyzes a developers srcDir for TS files
// and if they import a provider, we are manually inserting those files into the "dependency map"
// so that we have an accurate representation of what's user providers
function checkIfProviderIsUsedInSrc(context, dependencyMap) {
    var srcFiles = context.fileCache.getAll().filter(function (file) { return path_1.extname(file.path) === '.ts'
        && file.path.startsWith(context.srcDir)
        && !file.path.endsWith('.d.ts')
        && !file.path.endsWith('.ngfactory.ts')
        && !file.path.endsWith(helpers_1.getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX)); });
    srcFiles.forEach(function (srcFile) {
        var sourceFile = typescript_utils_1.getTypescriptSourceFile(srcFile.path, srcFile.content);
        var imports = typescript_utils_1.findNodes(sourceFile, sourceFile, typescript_1.SyntaxKind.ImportDeclaration);
        imports.forEach(function (importStatement) {
            if (importStatement.moduleSpecifier.text === 'ionic-angular'
                && importStatement.importClause.namedBindings
                && importStatement.importClause.namedBindings.elements) {
                importStatement.importClause.namedBindings.elements.forEach(function (importSpecifier) {
                    if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_CONTROLLER_CLASSNAME)) {
                        var actionSheetControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_ACTION_SHEET_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(actionSheetControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(actionSheetControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_ALERT_CONTROLLER_CLASSNAME)) {
                        var alertControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_ALERT_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(alertControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(alertControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_LOADING_CONTROLLER_CLASSNAME)) {
                        var loadingControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_LOADING_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(loadingControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(loadingControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_MODAL_CONTROLLER_CLASSNAME)) {
                        var modalControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_MODAL_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(modalControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(modalControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_PICKER_CONTROLLER_CLASSNAME)) {
                        var pickerControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_PICKER_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(pickerControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(pickerControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_CONTROLLER_CLASSNAME)) {
                        var popoverControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_POPOVER_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(popoverControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(popoverControllerPath, importeeSet);
                    }
                    else if (importSpecifier.name.text === helpers_1.getStringPropertyValue(Constants.ENV_TOAST_CONTROLLER_CLASSNAME)) {
                        var toastControllerPath = helpers_1.getStringPropertyValue(Constants.ENV_TOAST_CONTROLLER_PATH);
                        var importeeSet = dependencyMap.get(toastControllerPath);
                        importeeSet.add(srcFile.path);
                        dependencyMap.set(toastControllerPath, importeeSet);
                    }
                });
            }
        });
    });
    return dependencyMap;
}
exports.checkIfProviderIsUsedInSrc = checkIfProviderIsUsedInSrc;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: function/fnOrError.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: function/fnOrError.js

import {typeOf} from '../object/typeOf';

export const

    /**
     * Returns a function or throws an error if given `f` is not a function.
     * @function module:function.fnOrError
     * @param symbolName {String} - Error message prefix.
     * @param f {Function|*} - Expected function.
     * @returns {Function}
     * @throws {Error} - Error if `f` is not of `function`
     */
    fnOrError = (symbolName, f) => {
        if (!f || !(f instanceof Function)) {
            throw new Error(`${symbolName} should be a function. ` +
                `Type received: ${typeOf(f)};  Value received: ${f}.`);
        }
        return f;
    }

;

Home

Modules

boolean

console

errorThrowing

fjl

function

jsPlatform

list

listUtils

object

string

utils

Global

apply

defineReverse

some

    Documentation generated by JSDoc 3.6.10 on Mon Apr 25 2022 13:44:32 GMT-0400 (Eastern Daylight Time)


text:
package com.asakusafw.windgate.hadoopfs;

import java.text.MessageFormat;
import java.util.ResourceBundle;

import com.asakusafw.windgate.core.WindGateLogger;

/**
 * Logger for WindGate resource based Hadoop File System.
 * @since 0.2.2
 */
public class HadoopFsLogger extends WindGateLogger {

    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(
            "com.asakusafw.windgate.hadoopfs.log"); //$NON-NLS-1$

    /**
     * Creates a new instance.
     * @param target the client class
     * @throws IllegalArgumentException if some parameters were {@code null}
     */
    public HadoopFsLogger(Class<?> target) {
        super(target, "HADOOP_FS");
    }

    @Override
    protected String getMessage(String code, Object... arguments) {
        String messagePattern = BUNDLE.getString(code);
        return MessageFormat.format(messagePattern, arguments);
    }
}


text:
            {{ 'CATEGORIES' | translate | uppercase }}
            <button ui-sref="content.add({ type: 'category' })"
                    class="btn btn-xs btn-success pull-right"
                    type="button"
                    title="{{ 'ADD_CATEGORY' | translate }}">

            </button>

                    {{ 'UNCATEGORIZED' | translate }}

                    {{ 'TRASHCAN' | translate }}

             - {{ 'PUBLISHED' | translate }}

             - {{ 'NOT_PUBLISHED' | translate }}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'foobar-component',
  template: `
    <h1>{{ title }}</h1>
  `,
  styleUrls: ['./foo-bar.component.css'],
})
export class FooBarComponent {
  public title: string = 'foobar!';
}


text:
require "appliance_console/timezone_configuration"

describe ApplianceConsole::TimezoneConfiguration do
  subject { described_class.new('US/Eastern') }

  context "#ask_questions" do
    it "returns true when all user input is provided" do
      expect(subject).to receive(:ask_timezone_area).and_return(true)
      expect(subject).to receive(:ask_timezone_city).and_return(true)
      expect(subject).to receive(:confirm).and_return(true)
      expect(subject.ask_questions).to_not be false
    end

    it "returns false when apply timezone is canceled" do
      expect(subject).to receive(:ask_timezone_area).and_return(true)
      expect(subject).to receive(:ask_timezone_city).and_return(true)
      expect(subject).to receive(:confirm).and_return(false)
      expect(subject.ask_questions).to be false
    end

    it "returns false when new city is canceled" do
      expect(subject).to receive(:ask_timezone_area).and_return(true)
      expect(subject).to receive(:ask_timezone_city).and_return(false)
      expect(subject).to_not receive(:confirm)
      expect(subject.ask_questions).to be false
    end

    it "returns false when new area is canceled" do
      expect(subject).to receive(:ask_timezone_area).and_return(false)
      expect(subject).to_not receive(:ask_timezone_city)
      expect(subject).to_not receive(:confirm)
      expect(subject.ask_questions).to be false
    end
  end

  context "#ask_timezone_area" do
    it "asks for a new timezone area" do
      expect(subject).to receive(:ask_with_menu).and_return('United States')
      expect(subject.ask_timezone_area).to be true
      expect(subject.new_loc).to eq('US')
    end

    it "returns false when cancel is requested" do
      expect(subject).to receive(:ask_with_menu).and_return(ApplianceConsole::CANCEL)
      expect(subject.ask_timezone_area).to be false
    end
  end

  context "#ask_timezone_city" do
    before { subject.instance_variable_set(:@new_loc, 'US') }

    it "asks for a new timezone city" do
      expect(subject).to receive(:ask_with_menu).and_return('Alaska')
      expect(subject.ask_timezone_city).to be true
      expect(subject.new_city).to eq('Alaska')
    end

    it "returns false when cancel is requested" do
      expect(subject).to receive(:ask_with_menu).and_return(ApplianceConsole::CANCEL)
      expect(subject.ask_timezone_city).to be false
    end
  end

  context "#confirm" do
    before do
      subject.instance_variable_set(:@tz_area, 'US')
      subject.instance_variable_set(:@new_city, 'Alaska')
      allow(subject).to receive(:clear_screen)
      allow(subject).to receive(:say)
    end

    it "asks to apply timezone" do
      expect(subject).to receive(:agree).and_return(true)
      expect(subject.confirm).to be true
    end

    it "returns false when cancel is requested" do
      expect(subject).to receive(:agree).and_return(false)
      expect(subject.confirm).to be false
    end
  end

  context "#activate" do
    before do
      expect(subject).to receive(:log_and_feedback).and_yield
      allow(subject).to receive(:say)
    end

    it "Applies the requested timezone" do
      expect(LinuxAdmin::TimeDate).to receive(:system_timezone=)
      expect(subject.activate).to be_truthy
    end

    it "returns false on failure" do
      expect(LinuxAdmin::TimeDate).to receive(:system_timezone=).and_raise(LinuxAdmin::TimeDate::TimeCommandError)
      expect(subject.activate).to be_falsy
    end
  end
end


text:
import { NgModule } from '@angular/core';
import { CourseUpdateContainerComponent } from './course-update-container.component';
import { CourseFormModule } from '../course-form';
import { CommonModule } from '@angular/common';

@NgModule({
    declarations: [CourseUpdateContainerComponent],
    imports: [CommonModule, CourseFormModule],
    exports: [CourseUpdateContainerComponent]
})
export class CourseUpdateContainerModule {

}


text:
// https://dl.dropboxusercontent.com/spa/pjlfdak1tmznswp/api_keys.js/public/index.html
// https://github.com/dropbox/dropbox-js/blob/master/doc/getting_started.md
// http://coffeedoc.info/github/dropbox/dropbox-js/master/classes/Dropbox/Client.html

define([
    "jwebkit",
    "jwebkit.ui",
    "jwebdesk",
    "./dropbox"
], function(jwk, ui, jwebdesk, dropboxjs) {
    window.$ = jwk.query;
    function DropBox(owner) {
        jwebdesk.Drive.call(this, owner, {
            title: "Dropbox",
            id: "dropbox"
        });
    }
    DropBox.prototype = new jwebdesk.Drive();
    DropBox.prototype.constructor = DropBox;

    // Private auxiliar functions ---------------------------------------------------------------
    // Esta función recibe la data de un readdir del api de dropbox de forma cruda como la maneja dropbox.
    // Hay que hacer una traducción de esta data a un formato unificado
    function to_nodes (entries, parent) {
// console.error("-------------->", entries[0]);
        var self = this;
        var nodes = [];
        for (var i=0;  i<entries.length; i++) {
            var entry = entries[i];
            //*
            var node = this.create_node({
                source: entry,
                name: entry.name,
                path: entry.path,
                isFolder: entry.isFolder,
                mimeType: entry.mimeType,
                hasThumbnail: entry.hasThumbnail,
                parent: parent,
                // TODO: hay que formatear este campo
                modifiedAt: entry.modifiedAt,
                size: entry.size,
                size_display: entry._json.size
            });
            // console.error("----------------------------->", typeof entry.modifiedAt, entry.modifiedAt.getTime());
            /*/
            var node = new Node({
                // TODO: una forma de resolver un fetch de sus folders
                root: "dropbox",
                name: entry.name,
                path: entry.path,
                fetched: false,
                isFolder: entry.isFolder,
                mimeType: entry.mimeType,
                extension: ext != name ? ext : "",
                hasThumbnail: entry.hasThumbnail,
                icon: entry.isFolder ? "folder" : ext + " " + entry.mimeType.split("/")[0],
                // TODO: hay que llamar a una función y que resuelva cada caso. No tenemos porque depender del mimeType de dropbox
                drive: self,
                parent: parent,
                // TODO: hay que formatear este campo
                modifiedAt: entry.modifiedAt
            });
            //*/
            nodes.push(node);
        }

        var orden = function (a, b) {
            var ret = 0;
            if (a.isFolder && !b.isFolder) ret = -1;
            if (!a.isFolder && b.isFolder) ret = 1;
            if (ret == 0) ret = (a.name.toLowerCase() > b.name.toLowerCase()) ? 1 : -1;
            return ret;
        }

        nodes = nodes.sort(orden);

        return nodes;
    }

    function assert_logged() {
        if (!this.flag("logged")) {
            this.login();
        }
        return this.wait_flag("logged");
    }

    function assert_readdir(node) {
        var self = this;
        var deferred = jwk.Deferred();
        if (!node.isFolder) return deferred.reject().promise();
        if (node.children) return deferred.resolve(node).promise();

        assert_logged.call(this).done(function() {
            if (!node.fetched && !node.requested) {
                console.assert(self && self.client, "ERROR: this node does not have the Dropbox.Client instantiated");
                self.client.readdir(node.path, function(error, names, stat, entries) {
                    if (error) return console.error(error);
                    var nodes = to_nodes.call(self, entries, node);
                    // node.set("children", nodes);
                    node.children = nodes;
                    deferred.resolve(node);
                });
                // Esto supuestamente impide que se realicen varios fetchs del mismo nodo seguidos (uno tras otro)
                node.requested = true;
                setTimeout(function () {
                    node.requested = false;
                }, 3000);

            } else if (node.fetched) {
                deferred.resolve(node);
            } else {
                node.wait_flag("children").done(function(node) {
                    deferred.resolve(node);
                });
            }
        });

        return deferred.promise();
    }

    // -------------------------------------------------------------------------------------------
    if (typeof Dropbox.Drivers == "undefined") alert("no se cargó el Dropbox.Redirect");
    if (typeof Dropbox.Drivers.Redirect == "undefined") alert("no se cargó el Dropbox.Redirect.Redirect");
    if (window.opener && jwk.urlParam("package")) {
        var view = {
            "disable_selection": true,
            "ui_type": "panel.emboss",
            "namespace": "jwk-ui",
            "class": "expand",
            "text": "Connecting to Dropbox..."
        }

        var tree = jwk.ui.display_component(view);
        var proxy = jwk.global.proxy("drive-dropbox-popup");

        var client = new Dropbox.Client({
            key: dropbox.key, sandbox: true
        });
        client.authDriver(new Dropbox.Drivers.Redirect({rememberUser: true}));
        client.authenticate(function(error, client) {
            if (error) {
                return console.error(error);
            }
            client.getUserInfo(function(error, userInfo) {
                if (error) {
                    return showError(error);  // Something went wrong.
                }
                proxy.trigger("logged", {client: client, name:userInfo.name, root: "dropbox", networkname:"DropBox"});
            });
        });

    }

    // DropBox API functions ----------------------------------------------------------------------

    DropBox.prototype.login = function (do_popup) {
        var self = this;
        var win;
        var deferred = jwk.Deferred();
        if (self.client) {
            return deferred.resolve();
        }
        var timer = false;
        var proxy = jwk.global.proxy("drive-dropbox-popup");
        proxy.on("logged", function (n,e) {
            console.log("hago un close del popup");
            var data = jwk.extend({}, e);
            self.client = new Dropbox.Client({
                network: "dropbox",
                key: data.client._credentials.key,
                sandbox: false
            });
            self.client.authDriver(new Dropbox.Drivers.Redirect({rememberUser: true}));
            self.client.authenticate(function(error, client) {
                if (error) {
                    console.error(error);
                    return deferred.reject(error);
                } else {
                    deferred.resolve(data);
                    self.flag_on("logged");
                }
            });
            console.log("hago un close del popup");
            if (window['popup_dropbox']) window['popup_dropbox'].close();
            delete window['popup_dropbox'];
        });
        var url = jwebdesk.serverURL + "?package=dropbox-drive&apptoken=" + this._apptoken;
        win = jwk.popupWindow(url, "Dropbox login", 600, 600);
        window['popup_dropbox'] = win;
        return deferred;
    }

    DropBox.prototype.logout = function () { }

    DropBox.prototype.user = function () {}

    DropBox.prototype.root = function () {}

    DropBox.prototype.writeFile = function (node, data, params) {
        var deferred = jwk.Deferred();
        var self = this;

        assert_logged.call(this).done(function() {
            if (true) {
                console.assert(self && self.client, "ERROR: this node does not have the Dropbox.Client instantiated");

                var options = {};
                self.client.writeFile(node.path, data, options, function(error, stat) {
                    // console.log(arguments)
                    if (error) {
                        deferred.reject(error);
                        return console.error(error);
                    }
                    node.data_fetched = false; // clear cache: me aseguro de que la próxima lectura refleje la realidad (o sea lo que hay en el servidor)
                    node.data = data;
                    deferred.resolve(node);
                });
                // Esto supuestamente impide que se realicen varios fetchs del mismo nodo seguidos (uno tras otro)
                node.data_requested = true;
                setTimeout(function () {
                    node.data_requested = false;
                }, 3000);

            }
        });

        return deferred.promise();
    }

    DropBox.prototype.readFile = function (node) {
        var deferred = jwk.Deferred();
        var self = this;

        assert_logged.call(this).done(function() {
            if (!node.data_fetched && !node.data_requested) {
                console.assert(self && self.client, "ERROR: this node does not have the Dropbox.Client instantiated");

                var options = {};

                self.client.readFile(node.path, options, function(error, data, stat, range) {
                    // console.log(arguments)
                    if (error) return console.error(error);
                    node.data = data;
                    node.data_fetched = true;
                    deferred.resolve(data, node);
                });
                // Esto supuestamente impide que se realicen varios fetchs del mismo nodo seguidos (uno tras otro)
                node.data_requested = true;
                setTimeout(function () {
                    node.data_requested = false;
                }, 3000);

            } else if (node.data_fetched && node.data) {
                deferred.resolve(node.data, node);
            } else {
                console.error("????", [node]);
            }

        });

        return deferred.promise();
    }

    DropBox.prototype.readdir = function (node) {
        var self = this;
        var deferred = jwk.Deferred();
        if (!node.isFolder) return deferred.reject().promise();
        if (node.children) return deferred.resolve(node).promise();

        assert_logged.call(this).done(function() {
            if (!node.fetched && !node.requested) {
                console.assert(self && self.client, "ERROR: this node does not have the Dropbox.Client instantiated");
                self.client.readdir(node.path, function(error, names, stat, entries) {
// console.error("mtime y size y que más hay?", arguments);
                    if (error) return console.error(error);
                    var nodes = to_nodes.call(self, entries, node);
                    node.children = nodes;
                    deferred.resolve(node.children, node);
                });
                // Esto supuestamente impide que se realicen varios fetchs del mismo nodo seguidos (uno tras otro)
                node.requested = true;
                setTimeout(function () {
                    node.requested = false;
                }, 3000);

            } else if (node.fetched) {
                deferred.resolve(node.children, node);
            } else {
                node.wait_flag("children").done(function(node) {
                    deferred.resolve(node.children, node);
                });
            }
        });

        return deferred.promise();
    }

    DropBox.prototype.getAPI = function () {  }

    DropBox.prototype.link = function (node) {
        console.log("Se pidió un link para el node", [node]);
        var self = this;
        var deferred = jwk.Deferred();

        assert_logged.call(this).done(function() {
            if (!node.fetched && !node.requested) {
                console.assert(self && self.client, "ERROR: this node does not have the Dropbox.Client instantiated");
                self.client.makeUrl(node.path, function(error, url) {
                    console.log("resultado:", arguments);
                    if (error) return console.error(error);
                    deferred.resolve(url);
                });
            } else {
                console.log("este Node no ha sido fetcheado todavía", [this, node]);
            }
        });
        return deferred.promise();
    }

    DropBox.prototype.thumbnail = function () {  }

    return DropBox;
});


text:
from network import Listener, Handler, poll

handlers = {}  # map client handler to user name

class MyHandler(Handler):

    def on_open(self):
        pass

    def on_close(self):
        pass

    def on_msg(self, msg):
        print msg

port = 8888
server = Listener(port, MyHandler)
while 1:
    poll(timeout=0.05) # in seconds


text:
package ru.skycelot.metamodel.persistence;

import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Template.class)
public abstract class Template_ {

	public static volatile SingularAttribute<Template, String> code;
	public static volatile SingularAttribute<Template, String> name;
	public static volatile SingularAttribute<Template, String> description;
	public static volatile SingularAttribute<Template, Project> project;
	public static volatile SingularAttribute<Template, Long> id;

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=trait.Cloned.html">

Redirecting to trait.Cloned.html...


text:
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'activities', pathMatch: 'full' }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes, { useHash: true }) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Mag. nat. Hist. , Ser. 2 7: (1851)

#### Original name
Bolacotricha grisea Berk. & Broome, 1851

### Remarks
null


text:
import { Type } from 'class-transformer';
import { IsEmail, IsNotEmpty, IsUUID, ValidateNested } from 'class-validator';
import {
    Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, Req
} from 'routing-controllers';
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';

import { UserNotFoundError } from '../errors/UserNotFoundError';
import { User } from '../models/User';
import { UserService } from '../services/UserService';
import { PetResponse } from './PetController';

class BaseUser {
    @IsNotEmpty()
    public firstName: string;

    @IsNotEmpty()
    public lastName: string;

    @IsEmail()
    @IsNotEmpty()
    public email: string;

    @IsNotEmpty()
    public username: string;
}

export class UserResponse extends BaseUser {
    @IsUUID()
    public id: string;

    @ValidateNested({ each: true })
    @Type(() => PetResponse)
    public pets: PetResponse[];
}

class CreateUserBody extends BaseUser {
    @IsNotEmpty()
    public password: string;
}

@Authorized()
@JsonController('/users')
@OpenAPI({ security: [{ basicAuth: [] }] })
export class UserController {

    constructor(
        private userService: UserService
    ) { }

    @Get()
    @ResponseSchema(UserResponse, { isArray: true })
    public find(): Promise<User[]> {
        return this.userService.find();
    }

    @Get('/me')
    @ResponseSchema(UserResponse, { isArray: true })
    public findMe(@Req() req: any): Promise<User[]> {
        return req.user;
    }

    @Get('/:id')
    @OnUndefined(UserNotFoundError)
    @ResponseSchema(UserResponse)
    public one(@Param('id') id: string): Promise<User | undefined> {
        return this.userService.findOne(id);
    }

    @Post()
    @ResponseSchema(UserResponse)
    public create(@Body() body: CreateUserBody): Promise<User> {
        const user = new User();
        user.email = body.email;
        user.firstName = body.firstName;
        user.lastName = body.lastName;
        user.password = body.password;
        user.username = body.username;

        return this.userService.create(user);
    }

    @Put('/:id')
    @ResponseSchema(UserResponse)
    public update(@Param('id') id: string, @Body() body: BaseUser): Promise<User> {
        const user = new User();
        user.email = body.email;
        user.firstName = body.firstName;
        user.lastName = body.lastName;
        user.username = body.username;

        return this.userService.update(id, user);
    }

    @Delete('/:id')
    public delete(@Param('id') id: string): Promise<void> {
        return this.userService.delete(id);
    }

}