text:
Unit tests and flake8
--------------------------

A majority of the code BiblioPixel code has _unit tests_ - tests that
are automatically run for every commit that test all the functionality is
working.  At this writing, there are 456 tests.

Also, we want to keep the code consistent with the standard Python style
which is explained neatly in
`this article <https://realpython.com/python-pep8/>`_ so there's a tool
called ``flake8`` that is run to find these style violations!

Both of these code quality tools are run automatically using `Travis CI
<https://travis-ci.org/>`_ for each pull request, but you will want to do
these tests on your own machine before submitting a pull request!

The programs to do this were already installed in a previous step, so here's
what you need to do!  Go to the root BiblioPixel directory and type:

.. code-block:: bash

    $ flake8
    $ pytest test

The first statement tests the code for style errors;  the second one runs all
the unit tests.

You don't have to wait until you have code to try it - do it now!  If everything
is OK, then all the tests should work.

Fixing bugs
==================

We welcome any and all bug fixes, but the best way to fix a bug is like this:

1. Create a test which demonstrates the problem - in other words, a test which
   fails because of the bug.

2. Fix the bug.

3. Demonstrate that the test now works.

The huge advantage of this is that it makes it harder for bugs to reappear -
"regressions", a problem which is very common in larger projects.

Writing new code
=====================

While we recognize that it is not always possible to write automatic tests for
all code, systematic automatic testing results in much more reliable code.

If you are adding new functionality to BiblioPixel, we would love it if you
added new tests for that functionality.

Good tests are hostile ;-) and try really hard to break the code with
unreasonable or extreme cases - what we call "edge cases".

It's OK for code to fail on actuall wrong inputs of course, but even then, it's
better if it fails in a clear and understandable way.  If you look at the
existing tests, there are dozens of tests that show that we handle errors
correctly and clearly.

Protip: assign these tests to a keystroke!
======================================================

How to do this depends entirely on your editor or development system, but I have
it set up so a single keystroke runs both of these tests and gives me an error
if either one of them fails.

In specific, I have the F7 key mapped to a command that saves everything, then
runs ``flake8 && pytest test``.

When I am developing, I run this after each tiny but complete change I make,
just by hitting a single key.  On a productive day, I will run this
a couple of hundred times, quite literally.


text:
package consensus

import (
	. "DNA/common"
)
type Policy struct {
	PolicyLevel PolicyLevel
	List []Uint160
}

func NewPolicy()  *Policy{
	return &Policy{}
}

func (p *Policy) Refresh(){
	//TODO: Refresh
}

var DefaultPolicy *Policy

func InitPolicy(){
	DefaultPolicy := NewPolicy()
	DefaultPolicy.Refresh()
}

redpajama_set_name: RedPajamaGithub


text:
set -e

if [ ! -d "build" ]; then
    mkdir build
fi
cd build
cmake .. $@
make $MAKEOPTS
cd ..

echo "Executing tests..."
build/tests/integral
build/tests/derivative
echo "Testing done."


text:
var parseDate = require('i18n-parse-date'),
    i18nContext = require('i18n-context')('ember_date_field', require.resolve('../locales')),
    t = i18nContext.t;

module.exports = require('ember-text-field').extend({
    autocomplete: 'off',

    min: null,
    max: null,

    required: null,

    sameDateString: function() {
        return t('same_date');
    }.property(),

    sameDate: null,

    showSelectorOnDownArrow: true,

    relative: false,

    init: function() {
        this._super();
        this.reformatInputValue(); //Trick to make sure that sameDate was set when formatting the inputValue
    },

    picker1Icon: 'icons/calendar',

    manipulateValue: function(value) {
        if (typeof value === 'string') {
            value = moment(value, 'YYYY-MM-DD');
        }
        value = value || null;
        Ember.assert('Value `'+value+'` is a not a valid moment object or null.', value === null || moment.isMoment(value));
        return value;
    },

    formatInputValue: function(value) {
        if (Ember.isEmpty(value)) {
            return null;
        }
        if (this.get('relative')) {
            if (value.isSame(moment().subtract(1, 'day'), 'day')) {
                return t('yesterday');
            }
            if (value.isSame(moment(), 'day')) {
                return t('today');
            }
            if (value.isSame(moment().add(1, 'day'), 'day')) {
                return t('tomorrow');
            }
        }
        var sameDate = this.get('sameDate');
        if (sameDate && value.format('L') == sameDate.format('L')) {
            return this.get('sameDateString');
        }
        return value.format('L');
    },

    sameDateDidChange: function() {
        this.reformatInputValue();
    }.observes('sameDate'),

    unformatInputValue: function(inputValue) {
        return Ember.isEmpty(inputValue) ? null : parseDate(inputValue)
    },

    validateInputValue: function(inputValue) {
        if (!Em.isEmpty(inputValue) && this.get('sameDateString') != inputValue && !(this.get('relative') && [t('yesterday'), t('today'), t('tomorrow')].contains(inputValue))) {
            var value = parseDate(inputValue);
            if (!value) {
                throw new UserError(t('invalid_date'));
            }

            // Range validation
            var min = this.get('min')
            var max = this.get('max')
            if (!Em.isEmpty(min) && value < min) {
                throw new Error(t('must_be_greater', { number: this.formatInputValue(min) }));
            }
            if (!Em.isEmpty(max) && value > max) {
                throw new Error(t('must_be_less', { number: this.formatInputValue(max) }));
            }
        } else if (Em.isEmpty(inputValue) && !!this.get('required')) {
            throw new Error(t('is_required'));
        }
    },

    selector: null,

    didClickPicker1: function() {
        if (this.get('selector')) {
            this.hideSelector();
        } else {
            this.showSelector();
        }
        this.focus();
    },

    showSelector: function() {
        var self = this,
            selector = this.get('selector');
        if (!selector) {
            selector = this.container.lookup('component:date-selector');
            this.set('selector', selector);
            selector.set('value', this.get('value'));
            selector.set('keyEl', this.$());
            selector.one('select', function(date) {
                self.selectValue(date);
                self.hideSelector();
            });
            selector.one('willDestroyElement', function() {
                self.set('selector', null);
            });
            selector.show(this);
        }
    },

    hideSelector: function() {
        var selector = this.get('selector');
        if (selector) {
            selector.destroy();
        }
    },

    keyDown: function(e) {
        if (!this.get('selector')) {
            if (e.which == $.keyCode.DOWN && this.get('showSelectorOnDownArrow')) {
                e.preventDefault();
                this.showSelector();
            }
        }
    },

    selectValue: function(value) {
        this.set('value', value);
        Ember.run.schedule('sync', this, function() {
            this.sendAction('didSelect', value);
        });
    }
});

module.exports.locale = i18nContext.locale;

module.exports.lang = function() {
    console.warn('.lang() is deprecated. Use .locale() instead');
    return i18nContext.locale.apply(null, arguments);
};


text:
@interface TeleportConfig : NSObject

@end


text:
module("baidu.lang.decontrol");

test('guid', function() {
	var m = window[baidu.guid];
	m._instances['a'] = {};
	baidu.lang.decontrol('a');
	equals(m._instances['a'], null, 'obj is deleted');
});


text:
package dk.lessismore.nojpa.rest;

import dk.lessismore.nojpa.db.methodquery.MQL;
import dk.lessismore.nojpa.reflection.db.model.ModelObjectInterface;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: seb
 * Date: 3/24/14
 * Time: 11:41 PM
 */
public class NoJpaFormatter implements Formatter<ModelObjectInterface> {

    private Class clazz;

    public NoJpaFormatter(Class clazz) {
        this.clazz = clazz;
    }

    @Override
    public ModelObjectInterface parse(String text, Locale locale) throws ParseException {
        Locator locator = AnnotationUtils.getAnnotation(clazz, Locator.class);
        if (locator != null) {
            try {
                return locator.locator().newInstance().get(text);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return MQL.selectByID(clazz, text);
    }

    @Override
    public String print(ModelObjectInterface object, Locale locale) {
        Printer printer = AnnotationUtils.getAnnotation(clazz, Printer.class);
        if (printer != null) {
            try {
                return printer.printer().newInstance().put(object);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return object.getObjectID();
    }

    public Class getClazz() {
        return clazz;
    }
}


text:
package cn.momia.api.user;

import cn.momia.api.user.dto.Child;
import cn.momia.api.user.dto.ChildComment;
import cn.momia.api.user.dto.ChildRecord;
import cn.momia.api.user.dto.ChildTag;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.api.HttpServiceApi;
import cn.momia.common.core.dto.PagedList;
import cn.momia.common.core.http.MomiaHttpParamBuilder;
import cn.momia.common.core.http.MomiaHttpRequestBuilder;
import cn.momia.common.core.util.TimeUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public class ChildServiceApi extends HttpServiceApi {
    public User add(String utoken, String children) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("children", children);
        return executeReturnObject(MomiaHttpRequestBuilder.POST(url("/child"), builder.build()), User.class);
    }

    public Child get(String utoken, long childId) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("utoken", utoken);
        return executeReturnObject(MomiaHttpRequestBuilder.GET(url("/child/%d", childId), builder.build()), Child.class);
    }

    public List<Child> list(String utoken) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("utoken", utoken);
        return executeReturnList(MomiaHttpRequestBuilder.GET(url("/child"), builder.build()), Child.class);
    }

    public User updateAvatar(String utoken, long childId, String avatar) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("avatar", avatar);
        return executeReturnObject(MomiaHttpRequestBuilder.PUT(url("/child/%d/avatar", childId), builder.build()), User.class);
    }

    public User updateName(String utoken, long childId, String name) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("name", name);
        return executeReturnObject(MomiaHttpRequestBuilder.PUT(url("/child/%d/name", childId), builder.build()), User.class);
    }

    public User updateSex(String utoken, long childId, String sex) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("sex", sex);
        return executeReturnObject(MomiaHttpRequestBuilder.PUT(url("/child/%d/sex", childId), builder.build()), User.class);
    }

    public User updateBirthday(String utoken, long childId, Date birthday) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("birthday", TimeUtil.SHORT_DATE_FORMAT.format(birthday));
        return executeReturnObject(MomiaHttpRequestBuilder.PUT(url("/child/%d/birthday", childId), builder.build()), User.class);
    }

    public User delete(String utoken, long childId) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("utoken", utoken);
        return executeReturnObject(MomiaHttpRequestBuilder.DELETE(url("/child/%d", childId), builder.build()), User.class);
    }

    public List<Child> list(Collection<Long> childrenIds) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder().add("cids", StringUtils.join(childrenIds, ","));
        return executeReturnList(MomiaHttpRequestBuilder.GET(url("/child/list"), builder.build()), Child.class);
    }

    public List<ChildTag> listAllTags() {
        return executeReturnList(MomiaHttpRequestBuilder.GET(url("/child/tag")), ChildTag.class);
    }

    public ChildRecord getRecord(String utoken, long childId, long courseId, long courseSkuId) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("coid", courseId)
                .add("sid", courseSkuId);
        return executeReturnObject(MomiaHttpRequestBuilder.GET(url("/child/%d/record", childId), builder.build()), ChildRecord.class);
    }

    public boolean record(String utoken, long childId, long courseId, long courseSkuId, String record) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("coid", courseId)
                .add("sid", courseSkuId)
                .add("record", record);
        return executeReturnObject(MomiaHttpRequestBuilder.POST(url("/child/%d/record", childId), builder.build()), Boolean.class);
    }

    public PagedList<ChildComment> listComments(String utoken, long childId, int start, int count) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("start", start)
                .add("count", count);
        return executeReturnPagedList(MomiaHttpRequestBuilder.GET(url("/child/%d/comment", childId), builder.build()), ChildComment.class);
    }

    public boolean comment(String utoken, long childId, long courseId, long courseSkuId, String comment) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("utoken", utoken)
                .add("coid", courseId)
                .add("sid", courseSkuId)
                .add("comment", comment);
        return executeReturnObject(MomiaHttpRequestBuilder.POST(url("/child/%d/comment", childId), builder.build()), Boolean.class);
    }

    public List<Long> queryCommentedChildIds(long courseId, long courseSkuId) {
        MomiaHttpParamBuilder builder = new MomiaHttpParamBuilder()
                .add("coid", courseId)
                .add("sid", courseSkuId);
        return executeReturnList(MomiaHttpRequestBuilder.POST(url("/child/comment"), builder.build()), Long.class);
    }

    public List<JSONObject> formatChildrenDetail(List<Child> children) {
        List<JSONObject> childrenDetail = new ArrayList<JSONObject>();
        for (int i = 0; i < Math.min(2, children.size()); i++) {
            Child child = children.get(i);
            JSONObject childJson = new JSONObject();
            childJson.put("sex", child.getSex());
            childJson.put("name", child.getName());
            childJson.put("age", TimeUtil.formatAge(child.getBirthday()));

            childrenDetail.add(childJson);
        }

        return childrenDetail;
    }

    public List<String> formatChildren(List<JSONObject> childrenDetail) {
        List<String> formatedChildren = new ArrayList<String>();
        for (JSONObject child : childrenDetail) {
            formatedChildren.add(child.getString("sex") + "孩" + child.getString("age"));
        }

        return formatedChildren;
    }
}


text:
/* eslint-disable @typescript-eslint/member-delimiter-style */

declare namespace Lulumi {
  import VueI18n from 'vue-i18n';

  export interface BrowserWindow {
    addLulumiExtension(srcDirectory: string): string;
    removeLulumiExtension(extensionId: string): string;
    getLulumiExtensions(): any;
  }

  export namespace Scheme {
    // lulumi:// scheme
    export interface LulumiObject extends Object {
      lulumi: Array<{ key: string, value: string }>;
      preferences: string[][];
      about: string[][];
    }
  }

  export namespace Preload {
    export interface IsolatedWorldMaps extends Object {
      [index: string]: number | undefined;
    }
    export interface Context extends Object {
      lulumi: any;
    }
  }

  export namespace API {
    // extension api
    export interface BackgroundPageObject {
      html: Buffer;
      name: string;
      webContentsId: number;
    }
    export interface BackgroundPages {
      [index: string]: BackgroundPageObject | undefined;
    }
    export interface IconInfo {
      type: 'path' | 'imageData';
      url: string;
      tabId: number | undefined;
    }
    export interface ManifestIcons {
      [size: string]: string;
    }
    export interface ManifestObject extends chrome.runtime.Manifest {
      extensionId: string;
      icons: ManifestIcons;
      srcDirectory: string;
    }
    export interface ManifestMap {
      [index: string]: ManifestObject | undefined;
    }
    export interface ManifestNameMap {
      [index: string]: ManifestObject | undefined;
    }
    export interface CustomTabsQueryInfo extends chrome.tabs.QueryInfo {
      webContentsId: number;
    }
    export interface GlobalObject extends NodeJS.Global {
      isOnline: boolean;
      __static: string;
      data: Record<'about' | 'backgroundPages' | 'manifestMap' | 'renderProcessPreferences', any>;
      func: Record<'createFromPath' | 'join' | 'module', any>;
      guestData: Scheme.LulumiObject;
      commandPalette: Electron.BrowserWindow;
    }
  }

  export namespace Store {
    // store
    export interface CustomStore {
      dispatch: (type: any, ...payload: any) => Promise<any> | void;
    }
    export interface ExtensionMetadata {
      browserActionIcon: string;
      pageActionIcon: string;
      badgeText: string;
      badgeBackgroundColor: string;
    }
    export interface ExtensionsMetadata extends Object {
      [index: string]: ExtensionMetadata;
    }
    export interface TabObject {
      browserViewId: number; // Id of the corresponding BrowserView
      webContentsId: number; // Id of the corresponding webContents
      id: number; // 頁籤的標識符。(某些狀況可能會沒有 id)
      index: number; // 頁籤在所在窗口中的索引,從 0 開始。
      windowId: number; // 頁籤所在窗口的標識符。
      openerTabId?: number; // 使用哪個已存在的頁籤打開指定的網址。
      highlighted: boolean; // 頁籤是否為高亮狀態。
      active: boolean; // 頁籤是否是窗口中的活動頁籤。 (因為視窗不一定是 focus 的狀態。)
      pinned: boolean; // 頁籤是否固定。(指定為tue的頁籤,不能移動,也沒有關閉鈕)
      url: string; // 頁籤中顯示的 URL。需要 "tabs" 權限
      title: string | null; // 頁籤的標題,如果頁籤正在加載它也可能是空字符串。需要 "tabs" 權限
      favIconUrl: string | null; // 頁籤的收藏夾圖標 URL,如果頁籤正在加載它也可能是空字符串。需要 "tabs" 權限
      status: string | null; // "loading"(正在加載)或 "complete"(完成)。
      incognito: boolean; // 頁籤是否在隱身窗口中。
      width?: number; // 頁籤寬度,以像素為單位。
      height?: number; // 頁籤高度,以像素為單位。
      sessionId?: number; // session 標識符。(如果使用 session 匯入 tab 可能導致沒有 tab 的 id 而只有 session 的 id)
      statusText: string | boolean;
      isLoading: boolean;
      didNavigate: boolean;
      isSearching: boolean;
      canGoBack: boolean;
      canGoForward: boolean;
      canRefresh: boolean;
      error: boolean;
      hasMedia: boolean;
      isAudioMuted: boolean;
      pageActionMapping: any;
      extensionsMetadata: ExtensionsMetadata;
    }
    export interface CommandPaletteConfig {
      browsingHistory: string;
      onlineSearch: string;
    }
    export interface LulumiObject {
      systemFavicon: string;
      tabFavicon: string;
      commandPalette: commandPaletteConfig;
    }
    export interface TabConfig {
      dummyTabObject: TabObject;
      lulumiDefault: LulumiObject;
    }
    export interface SearchEngineObject {
      name: string;
      search: string;
      autocomplete: string;
    }
    export interface TabHistory {
      title: string | null;
      url: string;
      favIconUrl: string | null;
      label: string;
      time: string;
      mtime: number;
    }
    export interface DownloadItem {
      getReceivedBytes: number;
      totalBytes: number;
      startTime: number;
      webContentsId: number;
      name: string;
      url: string;
      isPaused: boolean;
      canResume: boolean;
      state: string;
      savePath: string | null;
      dataState: string;
    }
    export interface LastOpenedTabObject {
      title: string | VueI18n.LocaleMessageArray | null;
      url: string;
      favIconUrl: string | null;
      mtime: number;
    }
    export interface CertificateObject {
      certificate: Electron.Certificate;
      verificationResult: string;
      errorCode: number;
    }
    export interface Certificates {
      [index: string]: CertificateObject | undefined;
    }
    export interface LulumiBrowserWindowProperty extends Electron.BrowserWindowConstructorOptions {
      id: number;
      focused?: boolean;
      left: number;
      top: number;
      state: string;
      tabs?: TabObject[];
      lastActive: boolean;
    }
    export interface ExtensionInfoDict extends Object {
      [index: string]: chrome.management.ExtensionInfo;
    }
    export interface State {
      tabId: number;
      tabs: TabObject[];
      tabsOrder: number[][];
      currentTabIndexes: number[];
      searchEngine: SearchEngineObject[];
      currentSearchEngine: SearchEngineObject;
      autoFetch: boolean;
      homepage: string;
      pdfViewer: string;
      tabConfig: TabConfig;
      lang: string;
      proxyConfig: Electron.Config;
      auth: { username: string, password: string };
      downloads: DownloadItem[];
      history: TabHistory[];
      permissions: any;
      lastOpenedTabs: LastOpenedTabObject[];
      certificates: Certificates;
      windows: LulumiBrowserWindowProperty[];
      extensionInfoDict: ExtensionInfoDict;
    }
    export interface TabsOrdering {
      tabObjects: Store.TabObject[];
      currentTabIndexes: number[];
    }
  }

  export namespace Main {
    // src/main/index.js
    export interface BrowserWindowSuggestionItem {
      url: string;
      follow: boolean;
    }
  }

  export namespace Renderer {
    // src/renderer/js
    export interface SuggestionItem {
      title?: string;
      value: string;
      url: string;
      icon: string;
    }
    export interface SuggestionMatch {
      indices: number[];
      key: string;
    }
    export interface SuggestionObject {
      item: SuggestionItem;
      matches?: SuggestionMatch[];
    }
    export interface AboutLocationObject {
      omniUrl: string;
      title: string;
      url: string;
    }
  }

  export namespace CommandPalette {
    export interface SuggestionItem {
      title?: string;
      value: string;
      url: string;
      icon: string;
    }
    export interface SuggestionMatch {
      indices: number[];
      key: string;
    }
    export interface SuggestionObject {
      item: SuggestionItem;
      matches?: SuggestionMatch[];
    }
    export interface Suggestion {
      header: string;
      icon: string;
      results: SuggestionObject[];
    }
  }

  export namespace BrowserMainView {
    // BrowserMainView.vue
    export interface Alarm {
      handler: any;
      periodInMinutes?: number;
    }
    export interface AlarmArray {
      [index: string]: Alarm | undefined;
    }
  }

  export namespace Tab {
    // Tab.vue
    export interface FindInPageObject {
      container?: HTMLDivElement;
      input: HTMLInputElement;
      counter: HTMLSpanElement;
      previous: HTMLElement;
      next: HTMLElement;
      endButton: HTMLElement;
      activeWebview: Electron.WebviewTag;
      start(): void;
      end(): void;
    }
  }
}


text:
public interface $(type-name)DataWriter extends
    $(scoped-type-name)DataWriterOperations,
    DDS.DataWriter
{
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mystrosporium cerasi Schulzer & Sacc.

### Remarks
null


text:
import { Plugin } from "@ckeditor/ckeditor5-core";
import { FocusTracker } from "@ckeditor/ckeditor5-utils";
import { Options } from "@ckeditor/ckeditor5-utils/src/dom/position";
import ButtonView from "../../button/buttonview";
import View from "../../view";
import ViewCollection from "../../viewcollection";
import BalloonPanelView from "./balloonpanelview";

export default class ContextualBalloon extends Plugin {
    static readonly pluginName: 'ContextualBalloon';

    readonly positionLimiter: Options["limiter"];
    readonly view: BalloonPanelView;
    visibleView: View | null;

    add(data: {
        stackId?: string | undefined;
        view?: View | undefined;
        position?: Options | undefined;
        balloonClassName?: string | undefined;
        withArrow?: boolean | undefined;
        singleViewMode?: boolean | undefined;
    }): void;
    hasView(view: View): boolean;
    remove(view: View): void;
    showStack(id: string): void;
    updatePosition(position?: Options): void;
}

export class RotatorView extends View {
    buttonNextView: ButtonView;
    buttonPrevView: ButtonView;
    readonly content: ViewCollection;
    focusTracker: FocusTracker;
    isNavigationVisible: boolean;

    hideView(): void;
    showView(view: View): void;
}


text:
import iOSProxyServices = require("./../common/mobile/ios/ios-proxy-services");
import iOSDevice = require("./../common/mobile/ios/ios-device");
import helpers = require("../common/helpers");
import net = require("net");
import path = require("path");
import util = require("util");

class AndroidDebugService implements IDebugService {
    private static ENV_DEBUG_IN_FILENAME = "envDebug.in";
	private static ENV_DEBUG_OUT_FILENAME = "envDebug.out";
    private static DEFAULT_NODE_INSPECTOR_URL = "http://127.0.0.1:8080/debug";
    private static PACKAGE_EXTERNAL_DIR_TEMPLATE = "/sdcard/Android/data/%s/files/";

	private _device: Mobile.IAndroidDevice = null;

	constructor(private $devicesServices: Mobile.IDevicesServices,
		private $platformService: IPlatformService,
		private $platformsData: IPlatformsData,
		private $projectData: IProjectData,
		private $logger: ILogger,
		private $options: IOptions,
		private $childProcess: IChildProcess,
        private $mobileHelper: Mobile.IMobileHelper,
        private $hostInfo: IHostInfo,
        private $errors: IErrors,
        private $opener: IOpener,
        private $staticConfig: IStaticConfig) { }

	private get platform() { return "android"; }

	private get device(): Mobile.IAndroidDevice {
		return this._device;
	}

	private set device(newDevice) {
		this._device = newDevice;
	}

	public debug(): IFuture<void> {
		return this.$options.emulator
			? this.debugOnEmulator()
			: this.debugOnDevice();
	}

	public debugOnEmulator(): IFuture<void> {
		return (() => {
			this.$platformService.deployOnEmulator(this.platform).wait();
			this.debugOnDevice().wait();
		}).future<void>()();
	}

	public debugOnDevice(): IFuture<void> {
		return (() => {
			let packageFile = "";

			if (this.$options.debugBrk) {
				this.$platformService.preparePlatform(this.platform).wait();

				let cachedDeviceOption = this.$options.forDevice;
				this.$options.forDevice = true;
				this.$platformService.buildPlatform(this.platform).wait();
				this.$options.forDevice = !!cachedDeviceOption;

				let platformData = this.$platformsData.getPlatformData(this.platform);
				packageFile = this.$platformService.getLatestApplicationPackageForDevice(platformData).wait().packageName;
				this.$logger.out("Using ", packageFile);
			}

			this.$devicesServices.initialize({ platform: this.platform, deviceId: this.$options.device}).wait();
			let action = (device: Mobile.IAndroidDevice): IFuture<void> => { return this.debugCore(device, packageFile, this.$projectData.projectId) };
			this.$devicesServices.execute(action).wait();

		}).future<void>()();
	}

	 private debugCore(device: Mobile.IAndroidDevice, packageFile: string, packageName: string): IFuture<void> {
        return (() => {
			this.device = device;

            if (this.$options.getPort) {
                this.printDebugPort(packageName).wait();
            } else if (this.$options.start) {
                this.attachDebugger(packageName);
            } else if (this.$options.stop) {
                this.detachDebugger(packageName).wait();
            } else if (this.$options.debugBrk) {
                this.startAppWithDebugger(packageFile, packageName).wait();
            } else {
                this.$logger.info("Should specify at least one option: debug-brk, start, stop, get-port.");
            }
        }).future<void>()();
    }

	private printDebugPort(packageName: string): IFuture<void> {
        return (() => {
            let res = this.$childProcess.spawnFromEvent(this.$staticConfig.getAdbFilePath().wait(), ["shell", "am", "broadcast", "-a", packageName + "-GetDgbPort"], "exit").wait();
            this.$logger.info(res.stdout);
        }).future<void>()();
    }

	private attachDebugger(packageName: string): void {
        let startDebuggerCommand = `am broadcast -a \"${packageName}-Debug\" --ez enable true`;
        let port = this.$options.debugPort;

        if (port > 0) {
            startDebuggerCommand += " --ei debuggerPort " + port;
            this.device.adb.executeShellCommand(startDebuggerCommand).wait();
        } else {
            let res = this.$childProcess.spawnFromEvent(this.$staticConfig.getAdbFilePath().wait(), ["shell", "am", "broadcast", "-a", packageName + "-Debug", "--ez", "enable", "true"], "exit").wait();
            let match = res.stdout.match(/result=(\d)+/);
            if (match) {
                port = match[0].substring(7);
            } else {
                port = 0;
            }
        }
        if ((0 < port) && (port < 65536)) {
            this.tcpForward(port, port).wait();
            this.startDebuggerClient(port).wait();
            this.openDebuggerClient(AndroidDebugService.DEFAULT_NODE_INSPECTOR_URL + "?port=" + port);
        } else {
          this.$logger.info("Cannot detect debug port.");
        }
    }

    private detachDebugger(packageName: string): IFuture<void> {
        return this.device.adb.executeShellCommand(this.device.deviceInfo.identifier, `shell am broadcast -a \"${packageName}-Debug\" --ez enable false`);
    }

    private startAppWithDebugger(packageFile: string, packageName: string): IFuture<void> {
        return (() => {
            this.device.applicationManager.uninstallApplication(packageName).wait();
            this.device.applicationManager.installApplication(packageFile).wait();

            let port = this.$options.debugPort;

            let packageDir = util.format(AndroidDebugService.PACKAGE_EXTERNAL_DIR_TEMPLATE, packageName);
            let envDebugOutFullpath = this.$mobileHelper.buildDevicePath(packageDir, AndroidDebugService.ENV_DEBUG_OUT_FILENAME);

            this.device.adb.executeShellCommand(`rm "${envDebugOutFullpath}"`).wait();
            this.device.adb.executeShellCommand(`mkdir -p "${packageDir}"`).wait();

    		let debugBreakPath = this.$mobileHelper.buildDevicePath(packageDir, "debugbreak");
            this.device.adb.executeShellCommand(`"cat /dev/null > ${debugBreakPath}"`).wait();

            this.device.applicationManager.startApplication(packageName).wait();

            let dbgPort = this.startAndGetPort(packageName).wait();
            if (dbgPort > 0) {
                this.tcpForward(dbgPort, dbgPort).wait();
                this.startDebuggerClient(dbgPort).wait();
                this.openDebuggerClient(AndroidDebugService.DEFAULT_NODE_INSPECTOR_URL + "?port=" + dbgPort);
            }
        }).future<void>()();
    }

    private tcpForward(src: Number, dest: Number): IFuture<void> {
        return this.device.adb.executeCommand(`forward tcp:${src.toString()} tcp:${dest.toString()}`);
    }

    private startDebuggerClient(port: Number): IFuture<void> {
        return (() => {
            let nodeInspectorModuleFilePath = require.resolve("node-inspector");
            let nodeInspectorModuleDir = path.dirname(nodeInspectorModuleFilePath);
            let nodeInspectorFullPath = path.join(nodeInspectorModuleDir, "bin", "inspector");
            this.$childProcess.spawn(process.argv[0], [nodeInspectorFullPath, "--debug-port", port.toString()], { stdio: "ignore", detached: true });
        }).future<void>()();
    }

    private openDebuggerClient(url: string): void {
		let chrome = this.$hostInfo.isDarwin ? "Google\ Chrome" : "chrome";
		let child = this.$opener.open(url, chrome);
		if(!child) {
			this.$errors.fail(`Unable to open ${chrome}.`);
		}
		return child;
    }

    private checkIfRunning(packageName: string): boolean {
        let packageDir = util.format(AndroidDebugService.PACKAGE_EXTERNAL_DIR_TEMPLATE, packageName);
        let envDebugOutFullpath = packageDir + AndroidDebugService.ENV_DEBUG_OUT_FILENAME;
        let isRunning = this.checkIfFileExists(envDebugOutFullpath).wait();
        return isRunning;
    }

    private checkIfFileExists(filename: string): IFuture<boolean> {
        return (() => {
            let args = ["shell", "test", "-f", filename, "&&", "echo 'yes'", "||", "echo 'no'"];
            let res = this.$childProcess.spawnFromEvent(this.$staticConfig.getAdbFilePath().wait(), args, "exit").wait();
            let exists = res.stdout.indexOf('yes') > -1;
            return exists;
        }).future<boolean>()();
    }

    private startAndGetPort(packageName: string): IFuture<number> {
        return (() => {
            let port = -1;
			let timeout = 60;

            let packageDir = util.format(AndroidDebugService.PACKAGE_EXTERNAL_DIR_TEMPLATE, packageName);
            let envDebugInFullpath = packageDir + AndroidDebugService.ENV_DEBUG_IN_FILENAME;
            this.device.adb.executeShellCommand(`rm "${envDebugInFullpath}"`).wait();

            let isRunning = false;
            for (let i = 0; i < timeout; i++) {
                helpers.sleep(1000 /* ms */);
                isRunning = this.checkIfRunning(packageName);
                if (isRunning)
                    break;
            }

            if (isRunning) {
                this.device.adb.executeShellCommand(`"cat /dev/null > ${envDebugInFullpath}"`).wait();

                for (let i = 0; i < timeout; i++) {
                    helpers.sleep(1000 /* ms */);
                    let envDebugOutFullpath = packageDir + AndroidDebugService.ENV_DEBUG_OUT_FILENAME;
                    let exists = this.checkIfFileExists(envDebugOutFullpath).wait();
                    if (exists) {
                        let res = this.$childProcess.spawnFromEvent(this.$staticConfig.getAdbFilePath().wait(), ["shell", "cat", envDebugOutFullpath], "exit").wait();
                        let match = res.stdout.match(/PORT=(\d)+/);
                        if (match) {
                            port = parseInt(match[0].substring(5), 10);
                            break;
                        }
                    }
                }
            }
            return port;
        }).future<number>()();
    }
}
$injector.register("androidDebugService", AndroidDebugService);


text:
@implementation JMButtom

- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit{
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.titleLabel.font = [UIFont systemFontOfSize:9.0];
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect{
    CGFloat titleX = 0;
    CGFloat titleY = contentRect.size.height *0.75;
    CGFloat titleW = contentRect.size.width;
    CGFloat titleH = contentRect.size.height - titleY;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect{
    CGFloat imageW = CGRectGetWidth(contentRect);
    CGFloat imageH = contentRect.size.height * 0.7;
    return CGRectMake(0, 0, imageW, imageH);
}

@end


text:
module.exports = function(RED) {
	"use strict";

	function Fifo(config) {
		RED.nodes.createNode(this,config);

		this.queue = [];
		this.depth = config.depth;
		this.status({fill:"red",shape:"ring",text:"no value"});

		this.on('input', function (msg) {
			// are we full?
			// if so, boot some out
			if (this.queue.length >= this.depth) {
				while (this.queue.length >= this.depth) {
					var outgoing = this.queue.shift();
					this.send(outgoing);
				}
			}

			// clone the message and whack it in the queue
			this.queue.push(msg);

			if (this.queue.length == this.depth) {
				// queue is full
				this.status({fill: "green", shape: "dot",
				             text: this.queue.length + "/" +
				             this.depth + " msgs"});
			} else {
				// queue is partially full
				this.status({fill: "green", shape: "ring",
				             text: this.queue.length + "/" +
				                   this.depth + " msgs"});
			}

		});

		this.on("close", function() {
		});
	}

	RED.nodes.registerType("fifo",Fifo);

}