text:
//
//  MHRootViewController.m
//  MHDevelopExample
//
//  Created by 何千元 on 2020/6/23.
//  Copyright © 2020 CoderMikeHe. All rights reserved.
//

#import "MHRootViewController.h"

@interface MHModule : NSObject

/// icon
@property (nonatomic, readwrite, copy) NSString *icon;

/// 模块名
@property (nonatomic, readwrite, copy) NSString *name;

/// 切换到哪个模块
@property (nonatomic, readwrite, assign) MHSwitchToRootType type;

@end

@implementation MHModule

@end

@interface MHRootViewController ()<UITableViewDelegate , UITableViewDataSource>

/** tableView */
@property (nonatomic, readwrite, weak) UITableView *tableView;

/// modules
@property (nonatomic, readwrite, strong) NSMutableArray *modules;
@end

@implementation MHRootViewController

- (void)dealloc{
    MHDealloc;
}

- (void)viewDidLoad{
    [super viewDidLoad];

    // 初始化
    [self _setup];

    // 设置导航栏
    [self _setupNavigationItem];

    // 设置子控件
    [self _setupSubViews];

}
#pragma mark - 公共方法

#pragma mark - 私有方法

#pragma mark - Getter
- (NSMutableArray *)modules{
    if (_modules == nil) {
        _modules = [[NSMutableArray alloc] init];

        MHModule *m0 = [[MHModule alloc] init];
        m0.name = @"iOS实用开发Demo";
        m0.icon = @"module";
        m0.type = MHSwitchToRootTypeModule;

        MHModule *m1 = [[MHModule alloc] init];
        m1.name = @"基于MVC的基类设计";
        m1.icon = @"architecture";
        m1.type = MHSwitchToRootTypeArchitecture;

        [_modules addObject:m0];
        [_modules addObject:m1];
    }
    return _modules;
}

#pragma mark - 初始化
- (void)_setup
{
    self.view.backgroundColor = [UIColor whiteColor];
}

#pragma mark - 设置导航栏
- (void)_setupNavigationItem
{
    self.title = @"CoderMikeHe";
}

#pragma mark - 设置子控件
- (void)_setupSubViews
{
    // 创建tableView
    [self _setupTableView];
}

// 创建tableView
- (void)_setupTableView
{
    // 初始化tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.rowHeight = 56;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    self.tableView = tableView;
    [self.view addSubview:tableView];

    // 布局
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.modules count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.textLabel.font = MHRegularFont_17;
        cell.textLabel.textColor = MHColorFromHexString(@"#1a1a1a");
        cell.accessoryView = [[UIImageView alloc] initWithImage:MHImageNamed(@"uf_filter_next")];
        cell.imageView.size = CGSizeMake(24.0f, 24.0f);
    }
    MHModule *m = self.modules[indexPath.row];
    cell.imageView.image = MHImageNamed(m.icon);
    cell.textLabel.text = m.name;
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    MHModule *m = self.modules[indexPath.row];
    /// 发通知
    [MHNotificationCenter postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey: @(m.type)}];
}

@end


text:
package action

import (
	"flag"
)

type agentChecks struct {
	*config
}

func AgentChecksAction() Action {
	return &agentChecks{
		config: &gConfig,
	}
}

func (a *agentChecks) CommandFlags() *flag.FlagSet {
	return a.newFlagSet(FLAG_NONE)
}

func (a *agentChecks) Run(args []string) error {
	client, err := a.newAgent()
	if err != nil {
		return err
	}

	config, err := client.Checks()
	if err != nil {
		return err
	}

	return a.Output(config)
}

redpajama_set_name: RedPajamaGithub


text:
package example.repo;

import example.model.Customer1807;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer1807Repository extends CrudRepository<Customer1807, Long> {

	List<Customer1807> findByLastName(String lastName);
}


text:
$(function() {
	$('select[name=ccmMultilingualChooseLanguage]').change(function() {
		$(this).parent().submit();
	});
});

var asd = 22
var rr = qweqwe


text:
package com.googlecode.cqengine.query.option;

import com.googlecode.cqengine.query.QueryFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * A wrapper around object keys ("flags") which are said to be enabled.
 *

 * Example usage using {@link QueryFactory}:

 * QueryOptions queryOptions = queryOptions(enableFlags("flag1", "flag2"))
 *
 * @author niall.gallagher
 */
public class FlagsEnabled {

    final Set<Object> flags = new HashSet<Object>();

    public void add(Object flag) {
        flags.add(flag);
    }

    public void remove(Object flag) {
        flags.remove(flag);
    }

    public boolean isFlagEnabled(Object flag) {
        return flags.contains(flag);
    }

    @Override
    public String toString() {
        return "flagsEnabled=" + flags;
    }

    /**
     * Returns an existing {@link FlagsEnabled} from the QueryOptions, or adds a new
     * instance to the query options and returns that.
     *
     * @param queryOptions The {@link QueryOptions}
     * @return The existing QueryOptions's FlagsEnabled or a new instance.
     */
    public static FlagsEnabled forQueryOptions(final QueryOptions queryOptions) {
        FlagsEnabled flags = queryOptions.get(FlagsEnabled.class);
        if (flags == null) {
            flags = new FlagsEnabled();
            queryOptions.put(FlagsEnabled.class, flags);
        }
        return flags;
    }

    public static boolean isFlagEnabled(QueryOptions queryOptions, Object flag) {
        FlagsEnabled flagsDisabled = queryOptions.get(FlagsEnabled.class);
        return flagsDisabled != null && flagsDisabled.isFlagEnabled(flag);
    }
}


text:
module("instance", lifecycle );

test("constructor sets culture", function() {
	var globalizeDe = Globalize("de");
	equal( Globalize.parseFloat("5.3"), 5.3 );
	equal( Globalize.parseFloat("5,3"), 53 );
	equal( Globalize.parseFloat("5.3", "de"), 53 );
	equal( Globalize.parseFloat("5,3", "de"), 5.3 );
	equal( globalizeDe.parseFloat("5.3"), 53 );
	equal( globalizeDe.parseFloat("5,3"), 5.3 );
	equal( globalizeDe.parseFloat("5.3", "en"), 5.3 );
	equal( globalizeDe.parseFloat("5,3", "en"), 53 );
});


text:
namespace IPC {
namespace internal {

namespace {

class MockAttachment : public BrokerableAttachment {
 public:
  MockAttachment() {}
  MockAttachment(BrokerableAttachment::AttachmentId id)
      : BrokerableAttachment(id) {}

#if defined(OS_POSIX)
  base::PlatformFile TakePlatformFile() override {
    return base::PlatformFile();
  }
#endif  // OS_POSIX

  BrokerableType GetBrokerableType() const override { return WIN_HANDLE; }

 private:
  ~MockAttachment() override {}
};

class MockAttachmentBroker : public AttachmentBroker {
 public:
  typedef std::set<scoped_refptr<BrokerableAttachment>> AttachmentSet;

  bool SendAttachmentToProcess(const BrokerableAttachment* attachment,
                               base::ProcessId destination_process) override {
    return false;
  }

  bool OnMessageReceived(const Message& message) override { return false; }

  void AddAttachment(scoped_refptr<BrokerableAttachment> attachment) {
    get_attachments()->push_back(attachment);
    NotifyObservers(attachment->GetIdentifier());
  }
};

class MockChannelReader : public ChannelReader {
 public:
  MockChannelReader()
      : ChannelReader(nullptr), last_dispatched_message_(nullptr) {}

  ReadState ReadData(char* buffer, int buffer_len, int* bytes_read) override {
    return READ_FAILED;
  }

  bool ShouldDispatchInputMessage(Message* msg) override { return true; }

  bool GetNonBrokeredAttachments(Message* msg) override { return true; }

  bool DidEmptyInputBuffers() override { return true; }

  void HandleInternalMessage(const Message& msg) override {}

  void DispatchMessage(Message* m) override { last_dispatched_message_ = m; }

  base::ProcessId GetSenderPID() override { return base::kNullProcessId; }

  bool IsAttachmentBrokerEndpoint() override { return false; }

  AttachmentBroker* GetAttachmentBroker() override { return broker_; }

  // This instance takes ownership of |m|.
  void AddMessageForDispatch(Message* m) {
    get_queued_messages()->push_back(m);
  }

  Message* get_last_dispatched_message() { return last_dispatched_message_; }

  void set_broker(AttachmentBroker* broker) { broker_ = broker; }

 private:
  Message* last_dispatched_message_;
  AttachmentBroker* broker_;
};

}  // namespace

TEST(ChannelReaderTest, AttachmentAlreadyBrokered) {
  MockAttachmentBroker broker;
  MockChannelReader reader;
  reader.set_broker(&broker);
  scoped_refptr<MockAttachment> attachment(new MockAttachment);
  broker.AddAttachment(attachment);

  Message* m = new Message;
  PlaceholderBrokerableAttachment* needs_brokering_attachment =
      new PlaceholderBrokerableAttachment(attachment->GetIdentifier());
  EXPECT_TRUE(m->WriteAttachment(needs_brokering_attachment));
  reader.AddMessageForDispatch(m);
  EXPECT_EQ(ChannelReader::DISPATCH_FINISHED, reader.DispatchMessages());
  EXPECT_EQ(m, reader.get_last_dispatched_message());
}

TEST(ChannelReaderTest, AttachmentNotYetBrokered) {
  MockAttachmentBroker broker;
  MockChannelReader reader;
  reader.set_broker(&broker);
  scoped_refptr<MockAttachment> attachment(new MockAttachment);

  Message* m = new Message;
  PlaceholderBrokerableAttachment* needs_brokering_attachment =
      new PlaceholderBrokerableAttachment(attachment->GetIdentifier());
  EXPECT_TRUE(m->WriteAttachment(needs_brokering_attachment));
  reader.AddMessageForDispatch(m);
  EXPECT_EQ(ChannelReader::DISPATCH_WAITING_ON_BROKER,
            reader.DispatchMessages());
  EXPECT_EQ(nullptr, reader.get_last_dispatched_message());

  broker.AddAttachment(attachment);
  EXPECT_EQ(m, reader.get_last_dispatched_message());
}

}  // namespace internal
}  // namespace IPC
#endif  // USE_ATTACHMENT_BROKER


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (C) 2017 Adrián García
  ~
  ~ 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.
  -->

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/grant_permissions_dialog_margin"
    android:layout_width="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="@color/light_grey"
        android:id="@+id/grant_permissions_container"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="@dimen/grant_permissions_dialog_container_padding">

        <TextView
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/grant_permissions_dialog_container_item_margin"
            android:layout_width="match_parent"
            android:text="@string/main_permissions_not_granted_title"
            android:textStyle="bold" />

        <TextView
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/grant_permissions_dialog_container_item_margin"
            android:layout_width="match_parent"
            android:text="@string/main_permissions_not_granted_description" />

        <TextView
            android:fontFamily="monospace"
            android:id="@+id/grant_permissions_text"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/grant_permissions_dialog_container_item_margin"
            android:layout_width="match_parent" />

        <Button
            android:id="@+id/permissions_share"
            android:layout_gravity="center_horizontal"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/share_permissions" />

    </LinearLayout>

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


text:
var Stripe = require('stripe');
var Emailer = require('./emailer');
var async = require('async');
var EventEmitter = require('events').EventEmitter;

module.exports = function(options, $digger){

	var stripe = Stripe(options.STRIPE_SECRET_KEY);
	var emailer = Emailer(options, $digger);
	var orders = $digger.connect('/orders');

	var api = new EventEmitter();

	api.payment = function(order, done){

		if(!order){
			return done('error no stripe data');
		}

		var objs = {};

		async.series([

			function(next){
				stripe.customers.create({
		  		email: order.stripe.email
				}).then(function(customer) {
					objs.customer = customer;
					next();
				}, next);

			},

			function(next){

				stripe.customers.createCard(
				  objs.customer.id,
				  {card: order.stripe.id},
				  function(err, card) {
				    if(err){
				    	return next(err);
				    }
				    objs.card = card;
				    next();
				  }
				);
			},

			function(next){

				var charge_details = {
				  amount: Math.ceil(order.amount*100),
				  currency: "gbp",
				  card: objs.card.id,
				  customer: objs.customer.id,
				  description: order.desc
				}
				stripe.charges.create(charge_details).then(function(charge){

					objs.charge = charge;
					next();

				}, next)

			},

			function(next){

				try{
					var container = $digger.create('order', {
						name:order.stripe.email + ' - ' + order.amount,
						customer:order.stripe.card.name,
						stripe_customer:objs.customer,
						email:order.stripe.email,
						order:order,
						payment:objs.charge
					}).addClass('stripe').addClass('new')

				} catch(e){
					next(e);
					return;
				}

				orders.append(container).ship(function(){

					self.emit('email', {
						notes:container.attr('order.notes'),
						amount:container.attr('order.amount'),
						paymentid:container.attr('payment.id'),
						address:container.attr('order.cart.settings.address'),
						email:container.attr('email')
					})

					objs.container = container;

					next();
				})
			}
		], done)
	}

	api.handler = function(req, res){

		api.payment(req.body, function(error, container){

			if(error){
				res.statusCode = 500;
				res.send(error.toString());
			}
			else{
				res.json({
					ok:true
				});
			}
		})
	}

	return api;
}


text:
using UnityEngine;
using System.Collections;
using System.IO;

namespace Ecosim
{
	public enum PlatformType
	{
		UNKNOWN = -1,
		MACOSX,
		WINDOWS,
		LINUX
	};

	public static class GameSettings
	{
		public const string VERSION_STR = "0.1.57";
		public const bool MULTITHREAD_RENDERING = false; // in current unity version true gives corruption of data
		public static bool SUCCESSION_IN_BG_THREAD = true;
		public static bool VEGETATION_SUCCESSION_MULTITHREADED = false;
		public static bool PLANTS_LOGIC_MULTITHREADED = false;
		public static bool ANIMALS_LOGIC_MULTITHREADED = false;
		public const bool ALLOW_EDITOR = true;
		public const int MAX_SAVEGAME_SLOTS = 9;
		private static PlatformType platformType = PlatformType.UNKNOWN;
		private static string _ScenePath = null;
		private static string _SaveGamesPath = null;
		private static string _MonoPath = null;

		/**
		 * Setup should be called at initialisation of EcoSim2
		 * The reason for this is that PlayerPrefs can only be used from mainthread.
		 * To overcome this limitation, we read the values in Setup so we can use
		 * the properties from other threads as well...
		 */
		public static void Setup ()
		{
			if (_ScenePath != null)
				return;

			if (PlayerPrefs.HasKey ("ScenePath")) {
				_ScenePath = PlayerPrefs.GetString ("ScenePath");
			} else {
				_ScenePath = DefaultScenePath;
			}
			if (PlayerPrefs.HasKey ("SaveGamesPath")) {
				_SaveGamesPath = PlayerPrefs.GetString ("SaveGamesPath");
			} else {
				_SaveGamesPath = DefaultSaveGamesPath;
			}
			if (PlayerPrefs.HasKey ("MonoPath")) {
				_MonoPath = PlayerPrefs.GetString ("MonoPath");
			} else {
				_MonoPath = DefaultMonoPath;
			}
		}

		public static char EnvPathSeparatorChar {
			get {
				if ((Application.platform == RuntimePlatform.WindowsPlayer) || (Application.platform == RuntimePlatform.WindowsEditor)) {
					return ';';
				}
				else {
					return ':';
				}
			}
		}

		public static PlatformType Platform {
			get {
				if (platformType == PlatformType.UNKNOWN) {
					if ((Application.platform == RuntimePlatform.OSXPlayer) || (Application.platform == RuntimePlatform.OSXDashboardPlayer) ||
			(Application.platform == RuntimePlatform.OSXEditor)) {
						platformType = PlatformType.MACOSX;
					} else if (Application.platform == RuntimePlatform.LinuxPlayer) {
						platformType = PlatformType.LINUX;
					} else if ((Application.platform == RuntimePlatform.WindowsPlayer) || (Application.platform == RuntimePlatform.WindowsEditor)) {
						platformType = PlatformType.WINDOWS;
					}
				}
				return platformType;
			}
		}

		public static string ScenePath {
			get {
				if (_ScenePath == null) {
					Log.LogError ("Setup not called!");
					Setup ();
				}
				return _ScenePath;
			}
			set {
				string path = value;
				if (path.StartsWith (".") && ((path.Length == 1) || (path[1] == Path.DirectorySeparatorChar))) {
					// Relative path...
				}
				else {
					path = Path.GetFullPath (value);
				}
				if (!path.EndsWith (Path.DirectorySeparatorChar.ToString ())) {
					path += Path.DirectorySeparatorChar;
				}
				PlayerPrefs.SetString ("ScenePath", path);
				PlayerPrefs.Save ();
				_ScenePath = path;
			}
		}

		public static string DefaultScenePath {
			get {
				return "." + Path.DirectorySeparatorChar + "Scenes" + Path.DirectorySeparatorChar;
			}
		}

		public static string DefaultMonoPath {
			get {
				if (Platform == PlatformType.MACOSX) {
					if (Directory.Exists ("/Applications/Unity/Unity.app/Contents/Frameworks/Mono")) {
						// default unity MONO path
						return "/Applications/Unity/Unity.app/Contents/Frameworks/Mono/";
					} else if (Directory.Exists ("/Library/Frameworks/Mono.framework/Versions/Current")) {
						// default Mac OS X MONO path
						return "/Library/Frameworks/Mono.framework/Versions/Current/";
					}
				}
				string monoVar = System.Environment.GetEnvironmentVariable ("MONO");
				if (monoVar == null) {
					return "." + Path.DirectorySeparatorChar + "Mono" + Path.DirectorySeparatorChar;
				}
				return monoVar;
			}
		}

		public static string MonoPath {
			get {
				if (_MonoPath == null) {
					Log.LogError ("Setup not called!");
					Setup ();
				}
				return _MonoPath;
			}
			set {
				string path = value;
				if (path.StartsWith (".") && ((path.Length == 1) || (path[1] == Path.DirectorySeparatorChar))) {
					// Relative path...
				}
				else {
					path = Path.GetFullPath (value);
				}
				if (!path.EndsWith (Path.DirectorySeparatorChar.ToString ())) {
					path += Path.DirectorySeparatorChar;
				}
				PlayerPrefs.SetString ("MonoPath", path);
				PlayerPrefs.Save ();
				_MonoPath = path;
			}
		}

		public static string SaveGamesPath {
			get {
				if (_SaveGamesPath == null) {
					Log.LogError ("Setup not called!");
					Setup ();
				}
				return _SaveGamesPath;
			}
			set {
				string path = value;
				if (path.StartsWith (".") && ((path.Length == 1) || (path[1] == Path.DirectorySeparatorChar))) {
					// Relative path...
				}
				else {
					path = Path.GetFullPath (value);
				}
				if (!path.EndsWith (Path.DirectorySeparatorChar.ToString ())) {
					path += Path.DirectorySeparatorChar;
				}
				PlayerPrefs.SetString ("SaveGamesPath", path);
				PlayerPrefs.Save ();
				_SaveGamesPath = path;
			}
		}

		public static string DefaultSaveGamesPath {
			get {
				switch (Platform) {
				case PlatformType.MACOSX :
					return System.Environment.GetEnvironmentVariable ("HOME") + "/Library/Application Support/EcoSim/SaveGames/";
				case PlatformType.LINUX :
					return System.Environment.GetEnvironmentVariable ("HOME") + ".ecosim/SaveGames/";
				case PlatformType.WINDOWS :
					return System.Environment.GetEnvironmentVariable ("APPDATA") + "\\EcoSim\\SaveGames\\";
				default :
					return "." + Path.DirectorySeparatorChar;
				}
			}
		}

		public static string DesktopPath {
			get {
				switch (Platform) {
				case PlatformType.MACOSX :
					return System.Environment.GetEnvironmentVariable ("HOME") + "/Desktop/";
				case PlatformType.LINUX :
					{
						string home = System.Environment.GetEnvironmentVariable ("HOME");
						if (Directory.Exists (home + "/Desktop")) {
							return home + "/Desktop/";
						} else if (Directory.Exists (home + "/desktop")) {
							return home + "/desktop/";
						}
						return home;
					}
				case PlatformType.WINDOWS :

					return System.Environment.GetEnvironmentVariable ("HOMEDRIVE") +
				System.Environment.GetEnvironmentVariable ("HOMEPATH") + "\\Desktop\\";
				default :
					return "." + Path.DirectorySeparatorChar;
				}
			}
		}

		public static bool DebugScripts {
			get {
				return (PlayerPrefs.GetString ("debugscripts", "false") == "true");
			}
			set {
				bool current = DebugScripts;
				if (value != current) {
					PlayerPrefs.SetString ("debugscripts", value ? "true" : "false");
					PlayerPrefs.Save ();
				}
			}
		}

		/**
		 * Setup must be called before this can be used...
		 * Thread safe
		 */
		public static string GetPathForScene (string name)
		{
			return _ScenePath + name + Path.DirectorySeparatorChar;
		}

		/**
		 * Setup must be called before this can be used...
		 * Thread safe
		 */
		public static string GetPathForSlotNr (int slotNr)
		{
			return _SaveGamesPath + slotNr + Path.DirectorySeparatorChar;
		}
	}

}


text:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return None

        dummy = ListNode(0)
        dummy.next = head

        pre = dummy
        cur = pre.next

        while cur:
            if cur.val == val:
                pre.next = cur.next
                cur = pre.next
                continue
            pre = pre.next
            cur = pre.next

        return dummy.next

l = ListNode(1)
cur = l
l.next = ListNode(2)
cur = l.next
cur.next = ListNode(6)
cur = cur.next
cur.next = ListNode(3)
cur = cur.next
cur.next = ListNode(6)


text:
package org.edx.indonesiax.view;

import android.app.ActionBar;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import org.edx.indonesiax.R;
import org.edx.indonesiax.base.BaseFragmentActivity;
import org.edx.indonesiax.model.VideoModel;
import org.edx.indonesiax.model.db.DownloadEntry;
import org.edx.indonesiax.module.db.DataCallback;
import org.edx.indonesiax.util.AppConstants;
import org.edx.indonesiax.util.NetworkUtil;
import org.edx.indonesiax.view.adapters.DownloadEntryAdapter;

import java.util.ArrayList;
import java.util.List;

public class DownloadListActivity extends BaseFragmentActivity {

    private static final int MSG_UPDATE_PROGRESS = 1022;
    private DownloadEntryAdapter adapter;
    private View offlineBar;
    private final Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == MSG_UPDATE_PROGRESS) {
                if (isActivityStarted()) {
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                        logger.debug("download list reloaded");
                    }
                    sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, 3000);
                }
            }
        }
    };

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

        handler.sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, 0);

        try{
            environment.getSegment().screenViewsTracking(getString
                    (R.string.title_download));
        }catch(Exception e){
            logger.error(e);
        }

        offlineBar = (View) findViewById(R.id.offline_bar);
        if (!(NetworkUtil.isConnected(this))) {
            AppConstants.offline_flag = true;
            invalidateOptionsMenu();
            if (offlineBar != null)
                offlineBar.setVisibility(View.VISIBLE);
        }

        ListView downloadListView = (ListView) findViewById(R.id.my_downloads_list);
        adapter = new DownloadEntryAdapter(this, environment) {

            @Override
            public void onItemClicked(DownloadEntry model) {
                // nothing to do here
            }

            @Override
            public void onDownloadComplete(DownloadEntry model) {
                //showDownloadCompleteView();
                adapter.remove(model);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onDeleteClicked(DownloadEntry model) {
                if(environment.getStorage().removeDownload(model) >= 1){
                    // update the list data as one download is removed
                    try{
                        adapter.remove(model);
                        adapter.notifyDataSetChanged();
                    }catch(Exception e){
                        logger.error(e);
                    }

                }
            }
        };

        adapter.setStore(environment.getStorage());
        downloadListView.setAdapter(adapter);
        final ArrayList<DownloadEntry> list = new ArrayList<DownloadEntry>();
        environment.getDatabase().getListOfOngoingDownloads(new DataCallback<List<VideoModel>>() {
            @Override
            public void onResult(List<VideoModel> result) {
                if(result!=null){
                    for(VideoModel de : result){
                        list.add((DownloadEntry) de);
                    }
                    adapter.setItems(list);
                }
            }
            @Override
            public void onFail(Exception ex) {
                logger.error(ex);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            ActionBar bar = getActionBar();
            if (bar != null) {
                bar.show();
            }
            setTitle(getString(R.string.title_download));
        }catch(Exception e){
            logger.error(e);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        handler.sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, 0);
        invalidateOptionsMenu();
    };

    @Override
    protected void onOffline() {
        AppConstants.offline_flag = true;
        offlineBar.setVisibility(View.VISIBLE);
        invalidateOptionsMenu();
    }

    @Override
    protected void onOnline() {
        AppConstants.offline_flag = false;
        offlineBar.setVisibility(View.GONE);
        invalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // inflate menu from xml
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);

        MenuItem menuItem = menu.findItem(R.id.progress_download);
        menuItem.setVisible(false);

        MenuItem offline_tvItem = menu.findItem(R.id.offline);
        if (AppConstants.offline_flag) {
            offline_tvItem.setVisible(true);
        } else {
            offline_tvItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.findItem(R.id.progress_download);
        menuItem.setVisible(false);

        MenuItem checkBox_menuItem = menu.findItem(R.id.delete_checkbox);
        checkBox_menuItem.setVisible(false);

        return true;
    }

}


text:
/* NOTE: this is auto-generated from IDL */
/* From ppb_console.idl modified Thu May 12 07:00:00 2016. */

using System;
using System.Runtime.InteropServices;

namespace PepperSharp {

/**
 * @file
 * This file defines the PPB_Console interface.
 */

/**
 * @addtogroup Enums
 * @{
 */
public enum PPLogLevel {
  Tip = 0,
  Log = 1,
  Warning = 2,
  Error = 3
}
/**
 * @}
 */

/**
 * @addtogroup Interfaces
 * @{
 */
internal static partial class PPBConsole {
  [DllImport("PepperPlugin", EntryPoint = "PPB_Console_Log")]
  extern static void _Log ( PPInstance instance,
                            PPLogLevel level,
                            PPVar value);

  /**
   * Logs the given message to the JavaScript console associated with the
   * given plugin instance with the given logging level. The name of the plugin
   * issuing the log message will be automatically prepended to the message.
   * The value may be any type of Var.
   */
  public static void Log ( PPInstance instance,
                           PPLogLevel level,
                           PPVar value)
  {
  	 _Log (instance, level, value);
  }

  [DllImport("PepperPlugin", EntryPoint = "PPB_Console_LogWithSource")]
  extern static void _LogWithSource ( PPInstance instance,
                                      PPLogLevel level,
                                      PPVar source,
                                      PPVar value);

  /**
   * Logs a message to the console with the given source information rather
   * than using the internal PPAPI plugin name. The name must be a string var.
   *
   * The regular log function will automatically prepend the name of your
   * plugin to the message as the "source" of the message. Some plugins may
   * wish to override this. For example, if your plugin is a Python
   * interpreter, you would want log messages to contain the source .py file
   * doing the log statement rather than have "python" show up in the console.
   */
  public static void LogWithSource ( PPInstance instance,
                                     PPLogLevel level,
                                     PPVar source,
                                     PPVar value)
  {
  	 _LogWithSource (instance, level, source, value);
  }

}
/**
 * @}
 */

}


text:
(function(Layx) {
	// TODO: This is awful
	var withoutFirstLastChars = function (str) { return str.substr(1, str.length - 2); };

	Layx.addToPrototype({
		getPriorityFromLine: function(line) {
			var split = line.split("@");
			if (split.length == 2)
				return split[1].trim();
			return null;
		},

		dictFromSingleLine: function(line) {
			var reIndentation = /^\t*/; // matches tabs in the beginning of a line
			var reEvent = /^(\![a-zA-Z]+)\s*:\s*([^\s:].*)$/; // matches an event and it's action in an expression like "!click: replace(a,b)"
			var reProperty = /^([a-zA-Z]+)\s*:\s*([^\s:].*)$/; // matches a property and it's value in an expression like "bgColor: aabbcc"
			var reCSSProperty = /^css\(([a-zA-Z\-]+)\)\s*:\s*([^\s:].*)$/; // matches a css property and it's value in an expression like "css(border): 1px solid red"
			var reConstraint = /^([^"]+)\s*(<=|>=|=)\s*([^\s"@][^"@]*)(\s*@\s*\d+)?$/; // matches left side, comparison operator and right side of a constraint. UPDATE: matches @123 also
			var reViewName = /^([a-zA-Z_][a-zA-Z0-9_\-]*)(::(.+))?$/; // to check if string is a proper name (no start with numbers, no weird chars)
			var reTextContent = /^\"(.*)\"$/; // matches a single line text content

			// comments don't reach this place anymore
			// var commentStart = line.indexOf("#");
			// if (commentStart >= 0)
				// line = line.substr(0, commentStart);
			line = line.trim();

			if (line.length == 0) return null; // TODO: this should never happen. check.
		/*
			if (line.indexOf('"') < 0 && line.indexOf(',') >= 0) {
				var ops = [">=", "<=", "=", ":"], op = null;
				for (var iop = 0; !op && iop < ops.length; iop++)
					if (line.indexOf(ops[iop]) >= 0) op = ops[iop];
				if (!op) return [{ "error" : "mysterious comma found" }];

				var sides = line.split(op);
				var left = sides[0].split(',');
				var right = sides[0].split(',');

				if (left.length == right.length || right.length == 1) {
					var unpackedLines = [];
					for (var i = 0; i < left.length; i++) {
						var rightIndex = i % right.length;
						unpackedLines.push(parseLine(left[i] + op + right[rightIndex])[0]);
					}
					return unpackedLines;
				} else {
					return [{ "error" : "invalid number of values to unpack" }];
				}
			}
			*/
			var results;

			if (results = line.match(reConstraint)) {
				// we have a constraint in our hands

				return {
					"comparator" : results[2],
					"string" : line
				};

			} else if (results = line.match(reProperty)) {
				// we have a property (like bgColor)

				if (results[1] == "content" || results[1] == "title" || results[1] == "icon") {
					// TODO: Regex for this and quotes (simple, double, and escaped)
					return {
						"property" : results[1],
						"value" : withoutFirstLastChars(results[2])
					};
				}

				return {
					"property" : results[1],
					"value" : results[2]
				};

			} else if (results = line.match(reCSSProperty)) {
				// we have a CSS property (like border)

				return {
					"cssProperty" : results[1],
					"value" : results[2]
				};

			} else if (results = line.match(reEvent)) {
				// we have an event (like !click)

				return {
					"event" : results[1].substr(1),
					"action" : results[2]
				};

			// TODO: Join duplicated call currentView.setText(results[1]);
			} else if (results = line.match(reTextContent)) {
				// we have a single line text content (like "hello world! :)")

				// TODO: Regex for this and quotes (simple, double, and escaped)
				return {
					"property" : "content",
					"value" : results[1]
				};

			} else if (results = line.match(reViewName)) {
				// we have a view id

				var newViewDict = { "name" : results[1] };

				if (results[3])
					newViewDict.class = results[3];

				return newViewDict;

			}
			return { "error" : "I don't understand what this is supposed to be" };
		},

		splitLayerClass: function(str) {
			var reLayerClass = /^::([a-zA-Z_][a-zA-Z0-9_\-]*)\s*(\(.*\))?$/;
			var results = str.match(reLayerClass);

			if (!results)
				return false;

			var className = results[1];
			var params = [];
			if (results[2] && results[2] != "()") {
				withoutFirstLastChars(results[2]);
				var untrimmedParams = withoutFirstLastChars(results[2]).split(",");
				for (var i = 0; i < untrimmedParams.length; i++)
					params.push(untrimmedParams[i].trim());
			}

			return { "name": className, "params": params };
		},

		parseLines: function(linesIn) {
			if (linesIn.length == 0) return [];
			var that = this;
			function buildLayerDict() {
				if (firstLevel == 0 && (classStuff = that.splitLayerClass(name))) {
					that.classes[classStuff.name] = that.buildLayerClass(classStuff.name, classStuff.params, childrenLines);
					childrenLines = [];
					return;
				}

				if (childrenLines.length > 0) {
					jsonLines = that.parseLines(childrenLines);
					for (var k = 0; k < jsonLines.length; k++) {
						var jsonLine = jsonLines[k];
						if ("comparator" in jsonLine)
							layerDict.constraints.push(jsonLine);
						else if ("property" in jsonLine)
							layerDict.properties.push([jsonLine.property, jsonLine.value]);
						else if ("cssProperty" in jsonLine)
							layerDict.cssProperties[jsonLine.cssProperty] = jsonLine.value;
						else if ("event" in jsonLine)
							layerDict.events[jsonLine.event] = jsonLine.action;
						else
							layerDict.children.push(jsonLine);
					}
					childrenLines = []; // TODO: check .length = 0 differences
				} else {
					// This "line" has no children inside.
					// So if this is a layer => this has not to break the code,
					// as this would be a possible instance of a class.
					// (If this is not an instance of a class this would also work)
					// ---
					// if possibleLeaf has a name property, it actually is a
					// layer that has nothing inside, so don't kill layerDict
					if(!("name" in possibleLeaf))
						layerDict = possibleLeaf;

				}
				list.push(layerDict);
			}

			var reTabs = /^\t*/;

			var firstLevel = linesIn[0].match(reTabs)[0].length; // now that there's no empty lines, this is sure to work
			var layerDict = {};
			var name = null;
			var possibleLeaf = null;

			var list = [];
			var childrenLines = [];
			for (var i = 0; i < linesIn.length; i++) {
				var rawLine = linesIn[i];
				var currentLevel = rawLine.match(reTabs)[0].length;

				if (!name) {
					var lineDict = this.dictFromSingleLine(rawLine.trim());
					if ("name" in lineDict)
						name = lineDict.name; // Has to be a name //linesIn[i].trim();
					else
						name = rawLine;
					possibleLeaf = lineDict;
					//if ("name" in possibleLeaf) possibleLeaf = null;
					layerDict = {
						name: name,
						children: [],
						constraints: [],
						properties: [],
						cssProperties: {},
						events: [],
						classes : {},
						view: null
					};

					if ("class" in lineDict) {
						var classes = lineDict.class.split("::");
						for (var j = 0; j < classes.length; j++) {
							var layerClass = classes[j];
							var classStuff = this.splitLayerClass("::"+layerClass);
							layerDict.classes[classStuff.name] = classStuff.params;
						}
					}

					continue;
				}

				if (currentLevel > firstLevel) {
					childrenLines.push(rawLine);
				} else {
					// terminar y guardar en el layerDict
					buildLayerDict();
					i--;
					layerDict = null;
					name = null;
				}

			}
			// TODO: al final tambien o agregarle algo al final
			buildLayerDict();
			return list;
		},

		generateViewTree: function(children, parentView) {
			for (var i = 0; i < children.length; i++) {
				var child = children[i];
				var name = child.name;
				var view = (name == "root") ?
					this.views["root"] : this.buildLayer(name);
				if (name == "_")
					child.view = view;
				if (parentView) parentView.addChild(view);
				this.generateViewTree(child.children, view);
			}
		},

		processLayerObject: function(layer) {
			var that = this;
			var propertySetters = {
				textColor: "setTextColor",
				zindex: "setZIndex",
				overflow: "setOverflow",
				visible: "setVisible",
				multiline: "setMultiline",
				bgColor: "setBackgroundColor",
				fontStyle: "setFontStyle",
				fontSize: "setFontSize",
				link: "setLink",
				img: "setImage",
				content: "addTextLine",
				title: "setTitle",
				icon: "setIcon"
			};
			var jsEvents = {
				click: "click"
			};

			var layerObj = layer.obj;
			this.DEBUG_TIMEI(2,'\t\tInternal');

			// Add constraints
			for (var j = 0; j < layerObj.constraints.length; j++) {
				var cons = layerObj.constraints[j];
				var priority = "priority" in cons ? cons.priority : undefined;

				// This is here to remember how to add our own constraints (Constrant class) to this
				//var c_old = this.addConstraint(layer[cons.attribute], cons.comparator, rightAttribute, cons.m, cons.b, priority);

				// Do not use window. as it will ruin the layx2html
				PARSER_LAYX = this;
				PARSER_LAYER = layer;
				// This parser will throw the nice-error if there are any
				var objConstraint = parser.parse(cons.string);
				var cassoConstraint = objConstraint[0];
				var cLayers = objConstraint[1];
				// DOC: Constraints also depend on the container layer to admit
				// DOC: for ex. layer.height = 200 only when the layer is in canvas
				cLayers.push(layer);
				this.addConstraint(cassoConstraint, cLayers);
			}
			this.DEBUG_TIME(2,'\t\t\tConstraints');

			// This is for optimization (start)
			var inCanvas = layer.inCanvas;
			layer.inCanvas = false;

			// Add properties
			for (var j = 0; j < layerObj.properties.length; j++) {
				var prop = layerObj.properties[j];
				var pName = prop[0], pValue = prop[1];
				if (pName in propertySetters) {
					var funcName = propertySetters[pName];
					layer[funcName](pValue);
				} else {
					throw 'property \''+pName+'\' not recognized, duuuude!';
				}
			}
			this.DEBUG_TIME(2,'\t\t\tProperties');

			// This is for optimization (end)
			layer.inCanvas = inCanvas;
			if (layer.inCanvas && layer._toAdjustContentSize) {
				layer._adjustContentSize();
				layer._toAdjustContentSize = false;
			}

			// Add CSS properties
			for (var pName in layerObj.cssProperties) {
				var pValue = layerObj.cssProperties[pName];
				layer.div.css(pName, pValue);
			}
			this.DEBUG_TIME(2,'\t\t\tCSS Properties');
			// Add events
			for (var eName in layerObj.events) {
				var eAction = layerObj.events[eName];
				if (eName in jsEvents) {
					var jsEvent = jsEvents[eName];
					var f = function(eAction) {
						return function(e) {
							// Stop loading if opened in another tab / page
							var event = e || window.event;
							if (event && (event.ctrlKey || event.metaKey || event.shiftKey)) return true;
							// TODO: Check if this improves the performance
							setTimeout(function() {
								// TODO: Check if this improves the performance
								that.solver.autoSolve = false;
								eval(eAction);
								that.solver.autoSolve = true;
								that.solver.solve();
								that.drawAll();
							}, 1);
							return false;
						};
					};
					layer.div.on(jsEvent, f(eAction));
					if (jsEvent === 'click') {
						layer.div.css('cursor', 'pointer');

						var linkIni = eAction.indexOf('loadURL(');
						if (linkIni >= 0) {
							var link = eAction.substr(linkIni+9, eAction.indexOf(')', linkIni+1) - linkIni - 10);
							layer.setLink(link);
						}
					}
				} else {
					throw 'event \''+eName+'\' not recognized, duuuude!';
				}
			}
			// Add classes
			for (var cName in layerObj.classes) {
				var args = layerObj.classes[cName];
				if (cName in this.classes) {
					var layerClass = this.classes[cName];
					layer.addClass(layerClass, args);
				} else {
					throw 'class \''+cName+'\' not recognized, duuuude!';
				}
			}
			this.DEBUG_TIME(2,'\t\t\tEvents');
			layer.obj = null;
		},

		addConstraintsAndProperties: function(children) {
			for (var i = 0; i < children.length; i++) {
				var child = children[i];
				// in case we have an anonymous "_" view
				var layer = ("view" in child && !!child.view) ? child.view : this.views[child.name];
				layer.obj = child;
				if (!layer.inCanvas) continue;
				this.processLayerObject(layer);
				this.addConstraintsAndProperties(child.children);
			}
		},

		parseConstraint: function(line) {
			var priority = this.getPriorityFromLine(line);
			line = line.split("@")[0];
			var terms = line.split('=');
			if (terms.length > 2) {
				var lines = [];
				for (var i = 0; i < terms.length - 1; i++) {
					var l = (terms[i] + '=' + terms[i+1]).trim();
					if (l.charAt(0) == '>' || l.charAt(0) == '<') l = l.substr(1);
					if (l.charAt(l.length-1) == '>' || l.charAt(l.length-1) == '<') l = l.substr(0, l.length-1);
					if (priority) l += " @ " + priority;
					lines.push(l);
				}
				return lines;
			}
			// var a = 'holachaup=epea  asd=asd', j = /^.*(a).*$/g; var i; while(i = j.exec(a)) this.DEBUG(i);
			return [line];
		},

		parseCode: function(code) {

			this.DEBUG_TIMEI(1, '\tParse A');
			var chunks = code.split('program'); // TODO: HACERLO BIEN! CHEQUEAR QUE SEA UNA LINEA, ETC..
			code = chunks[0];
			var program = chunks.length == 1 ? '' : chunks.slice(1).join('');
			var lines = code.split("\n");

			this.DEBUG_TIME(1, '\t\tParse A done');
			var tmpLines, expanded;
			do {
				expanded = false;
				tmpLines = [];

				var multiLineComment = false;

				for (var k = 0; k < lines.length; k++) {
					var line = lines[k];

					// if we're inside a multiline comment
					if (multiLineComment) {
						var multiLineCommentEnd = line.indexOf("=#");
						// if it ended with a =#, remove that part and carry on
						if (multiLineCommentEnd >= 0) {
							line = line.substr(multiLineCommentEnd + 2);
							multiLineComment = false;
						// if it didn't end, skip this line
						} else {
							continue;
						}
					}

					// multiLine comments that actually are only one line
					// e.g.: "A #= B =# C" -> "A  C"
					line = line.replace(/#=.*?=#/g, "");

					var singleLineCommentStart = line.indexOf("#");

					// allow lines like this:
					// 		"this is a # fake comment" # this is a real comment
					//
					// TODO:
					// lines like these 2 don't work yet:
					//		"this is a # fake comment" # this is a real comment with a " character
					// 		"this is a string with #= a comment =# in it"
					//
					// I think starts and ends of strings AND comments should both be handled
					// by the jison parser, thus this wouldn't happen -mati
					if (singleLineCommentStart >= 0) {
						var quoteStart = line.indexOf('"');
						if (quoteStart >= 0 && quoteStart < singleLineCommentStart) {
							var quoteEnd = line.lastIndexOf('"');

							singleLineCommentStart = line.indexOf("#", quoteEnd);
						}
					}

					if (singleLineCommentStart >= 0) {

						// if it's an '#='
						if (line[singleLineCommentStart + 1] == "=") {
							multiLineComment = true;

							// no 'continue', we still need to parse this one line
						}

						line = line.substr(0, singleLineCommentStart);
					}

					var reTabs = /^\t*/;
					var tabsCount = line.match(reTabs)[0].length;
					line = line.trim();
					// TODO: by ignoring lines, line numbers screw up for error messages.
					// actually they're already screwed up by expanding so doesn't matter much.
					if (line == "") continue;
					var tabs = "";
					for (var j = 0; j < tabsCount; j++) tabs += '\t';

					var ops = [">=", "<=", "=", ":"], op = null;
					for (var iop = 0; !op && iop < ops.length; iop++)
						if (line.indexOf(ops[iop]) >= 0) op = ops[iop];

					// TODO: Enhance this code. Avoiding '(' to permit f(x,y) and rgb(r,g,b) in the right side
					// TODO: Avoid characters in strings in functions, etc.
					var constraintTerms = line.split('=');
					if (line.substr(0, 2) !== '::' && constraintTerms.length > 2 && line.indexOf('"')) {
						var constraints = this.parseConstraint(line);
						for (var i = 0; i < constraints.length; i++)
							tmpLines.push(tabs + constraints[i].trim());
						expanded = true;

					// TODO: Enhance this code. Avoiding '(' to permit f(x,y) and rgb(r,g,b) in the right side
					// TODO: Avoid characters in strings in functions, etc.
					// TODO: GUARDA CON LAS NUEVAS CLASES Y ESTAS CONDICIONES!
					// Separating commas into multiple lines
					} else if (line.indexOf('"') < 0 && (line.indexOf(',') >= 0 || (op != ':' && (line.indexOf('rect') >= 0 || line.indexOf('position') >= 0 || line.indexOf('center') >= 0 || line.indexOf('size') >= 0))) && (op !== ':' || line.indexOf('(') < 0) && line.indexOf('::') < 0) {
						if (!op) {
							tmpLines.push(tabs + "error: LALALAL mysterious comma found");
							continue;
						}
						var priority = this.getPriorityFromLine(line);
						priority = (priority ? " @ " + priority : "");
						line = line.split("@")[0];

						var sides = line.split(op);
						var left = sides[0], right = sides[1];
						if (op != ':') {
							// grammarDistrib-parser will throw the nice-error if there are any
							left = grammarDistrib.parse(left);
							right = grammarDistrib.parse(right);
						}
						left = left.split(",");
						right = right.split(",");
						if (left.length === right.length) {
							for (var i = 0; i < left.length; i++) {
								tmpLines.push(tabs + (left[i] + op + right[i]).trim() + priority);
							}
							if (left.length > 1 || ((left[0] + op + right[0]).trim() + priority) != line.trim() + priority)
								expanded = true;
						} else if (right.length === 1) {
							for (var i = 0; i < left.length; i++) {
								tmpLines.push(tabs + (left[i] + op + right[0]).trim() + priority);
							}
							expanded = true;
						} else if (left.length === 1) {
							if (op != ':') {
								for (var i = 0; i < right.length; i++) {
									tmpLines.push(tabs + (left[0] + op + right[i]).trim() + priority);
								}
								expanded = true;
							} else {
								tmpLines.push(tabs + line + priority);
							}
						} else{
							tmpLines.push(tabs + "error: LALALAL invalid number of values to unpack");
							expanded = true;
						}

					} else {
						tmpLines.push(tabs + line);
					}
				}
				lines = tmpLines;
			} while(expanded);
			this.DEBUG_TIME(1, '\t\tParse B done');

			if (false) {
				// TODO: Check this
				// TODO: (something else) parseLine was replaced with this.dictFromSingleLine,
				//		 returns a dict instead of an array of dicts.
				this.DEBUG("----PARSED LINES INIT-----------------------");
				for (var i = 0; i < lines.length; i++)
					this.DEBUG(JSON.stringify(parseLine(lines[i])));
				this.DEBUG("----PARSED LINES END------------------------");
			}

			this.DEBUG_TIME(1, '\t\tParse C done');

			var parsedCode = this.parseLines(lines);
			//this.DEBUG(JSON.stringify(parsedCode, undefined, 2));

			this.DEBUG_TIME(1, '\t\tParse D done');
			if (parsedCode.length >= 1 && (parsedCode[0] && ('children' in parsedCode[0]))) {
				this.generateViewTree(parsedCode);
				this.DEBUG_TIME(1, '\t\tParse E done');
				this.addConstraintsAndProperties(parsedCode);
				this.DEBUG_TIME(1, '\t\tParse F done');
			}
			if (program) {
				this.drawAll();
				//$('body').append('<script>' + program + '</scr' + 'ipt>');
				eval(program); // Using eval() to run in nodejs when layx-html~ing
				// TODO: Check security!
			}
			this.DEBUG_TIME(1, '\t\tParse G done');
			return;

			// ESTO ES VIEJO Y ES POR REFERENCIA DE IMPLEMENTACION ITERATIVA vs. RECURSIVA
			//var reIndentation = /^\t*/; // matches tabs in the beginning of a line
			/*
			var lines = code.split("\n");
			var viewStack = [root];

			for (var i = 0; i < lines.length; i++) {

				try {

					var line = lines[i];
					var lineLevel = line.match(reIndentation)[0].length;
					var commentStart = line.indexOf("#");
					if (commentStart >= 0)
						line = line.substr(0, commentStart);
					line = line.trim();

					if (line.length == 0)
						continue;

					if (lineLevel == 0 && line == "root")
						continue;

					if (viewStack.length < lineLevel)
						throw "looks like there are too many tabs";

					if (lineLevel == 0)
						throw "are you trying to add a view/constraint/property to the super of root???";

					viewStack.length = lineLevel;

					var currentView = viewStack[viewStack.length - 1];

					var results;
					// Esto lo hace parseLine

				} catch (ex) {
					throw "[PARSER] "+ex+" (line "+(i + 1)+")";
				}
			}*/
		}
	});
})(Layx);


text:
<?php

/** */
namespace Organizations\Form;

use Core\Entity\Hydrator\EntityHydrator;
use Core\Form\Hydrator\Strategy\CollectionStrategy;
use Core\Form\ViewPartialProviderInterface;
use Laminas\Form\Fieldset;

/**
 * The employees fieldset used for managing employees.
 *
 * Currently has two elements:
 * A user search bar to add new employees and a Collection of EmployeeFieldsets (one for each employee).
 *
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 * @since 0.18
 */
class EmployeesFieldset extends Fieldset implements ViewPartialProviderInterface
{
    protected $partial = 'organizations/form/employees-fieldset';

    public function setViewPartial($partial)
    {
        $this->partial = (string) $partial;

        return $this;
    }

    public function getViewPartial()
    {
        return $this->partial;
    }

    /**
     * Initializes the fieldset.
     */
    public function init()
    {
        $this->setName('employees');

        $this->add(
            array(
            'name' => 'inviteemployee',
            'type' => 'Organizations/InviteEmployeeBar',
            'options' => [
                'description' => /*@translate*/ 'Invite an employee via email address.',
            ]
            )
        );

        $this->add(
            array(

            'type' => 'Collection',
            'name' => 'employees',
            'options' => array(
                'count' => 0,
                'should_create_template' => true,
                'use_labeled_items' => false,
                'allow_add' => true,
                'allow_remove' => true,
                'renderFieldset' => true,
                'target_element' => array(
                    'type' => 'Organizations/EmployeeFieldset'
                )
            ),
            )
        );
    }
}