text:
<!DOCTYPE html>

	<title>

            Levy Zavet LLP, Lawyers -

    Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
  </title>

<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />

<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta content="width=device-width,initial-scale=1" name="viewport">

<meta name = "format-detection" content = "telephone=no">

<meta name="robots" content="noarchive">

<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" />

<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">

  	<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  	<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />

<meta property="legalName" content="Department_of_Industry">

Skip to main content

Skip to "About this site"

Language selection

Français

<object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object> Government of Canada

Search and menus

Search and menus

Topics menu

Jobs

Immigration

Travel

Business

Benefits

Health

Taxes

More services

You are here:

Home

Industries and Business

Canadian Company Capabilities

<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>

 Company profile - Canadian Company Capabilities

New Search |

<form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">

          <input type="hidden" name="lang" value="eng" />
          <input type="hidden" name="profileId" value="" />
          <input type="hidden" name="prtl" value="1" />
          <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D"  />

          <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />

          <input type="hidden" name="V_SEARCH.depth" value="1" />
          <input type="hidden" name="V_SEARCH.showStricts" value="false" />
          <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />

  </form>

| Previous Company

| Next Company

      Third-Party Information Liability Disclaimer

Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

      Levy Zavet LLP, Lawyers

Legal/Operating Name:

Levy Zavet LLP, Lawyers

http://www.LevyZavet.com

Info@LevyZavet.com

Mailing Address:

              	<address class="mrgn-bttm-md">

                   201-315 Eglinton Ave W

                    TORONTO,

                    Ontario

                  M5N 1A1

                </address>

Location Address:

              	         <address class="mrgn-bttm-md">

                   201-315 Eglinton Ave W

                    TORONTO,

                    Ontario

                  M5N 1A1

                         </address>

Tel.:
		      (416) 777-2244

Tel.:
			      (877) 777-8977

Fax:
		      (416) 477-2847

Company Profile

            We offer a range of legal services including real estate, coporate, commercial, litigation, tax, wills and estates, intellectual property, family and domestic law, contracts and personal injury.

We are barristers and solicitors who only practice in areas that complement one another. That allows us to have a wider perspective and focus on the issue while providing our clients with thoughtful, tailored solutions to their legal concerns.

Our close-knit boutique firm is dedicated to providing unparalleled customer service to our clients. We guarantee accessibility, a timely response through phone or email, and fair billing practices for only time we spend adding value to your file.

Clients of Levy Zavet LLP know that they can call or email us at any time and our approachable, warm staff will help answer their questions and concerns. Our lawyers respond to clients quickly and provide them with flexible meeting times to accommodate their daily schedules and our flat-rate billing system puts clients at ease and gives them an advantage when they are budgeting their expenses.

				Full profile

				Full profile

				Contact information

                Jeffrey
                Levy

                  Title:

                Partner/Associate

                    Area of Responsibility:

                    Management Executive.

                  Telephone:

                (416) 777-2244

                  Ext:

                770

                  Facsimile:

                (416) 477-2847

                    Email:

                  JLev@LevyZavet.com

                Maxim
                Zavet

                  Title:

                Partner/Associate

                  Telephone:

                (416) 777-2244

                  Ext:

                790

                  Facsimile:

                (416) 477-2847

                    Email:

                  MZavet@LevyZavet.com

  top of page

				Company description

            Country of Ownership:

              Canada

            Exporting:

              No

                Primary Industry (NAICS):

				541110 - Offices of Lawyers

            Primary Business Activity:

            Services

				Product / Service / Licensing

                              Service Name:

                            Legal services, law firm, lawyers offices

                            We offer a range of legal services including real estate, coporate, commercial, litigation, tax, wills and estates, intellectual property, family and domestic law, contracts and personal injury.

  top of page

					Market profile

                        Alliances:

                            Financial

Sales/Marketing

                          Strategic alliances:

                        Looking to grow our law firm in different countries with expert lawyers in all fields/areas of law.

                          Industry sector market interests:

Service Industry

  top of page

					Sector information

                Unique applications:

              We are barristers and solicitors who only practice in areas that complement one another. That allows us to have a wider perspective and focus on the issue while providing our clients with thoughtful, tailored solutions to their legal concerns.

Our close-knit boutique firm is dedicated to providing unparalleled customer service to our clients. We guarantee accessibility, a timely response through phone or email, and fair billing practices for only time we spend adding value to your file.

Clients of Levy Zavet LLP know that they can call or email us at any time and our approachable, warm staff will help answer their questions and concerns. Our lawyers respond to clients quickly and provide them with flexible meeting times to accommodate their daily schedules and our flat-rate billing system puts clients at ease and gives them an advantage when they are budgeting their expenses.

JEFF LEVY

Jeff is an experienced Ontario business lawyer practicing primarily in the areas of corporate law, corporate finance, technology law, mergers and acquisitions, joint ventures, tax law and commercial finance. His primary role is serving as a trusted advisor to entrepreneurial and family-owned businesses of all sizes.

His experience and training in business law provide him with the background to counsel his clients on a wide variety of legal issues including private equity, venture capital and other financing; joint ventures and strategic business relationships; software development contracts, licensing agreements and other technology issues; sales agency and other distribution matters; and employment issues and executive compensation arrangements.

His clients range from start-ups seeking guidance on formation of their business entity, to established companies looking for new sources of capital to fuel their growth, to mature family-owned companies planning for transfer of the business to the next generation. He provides advice on buying a business for those starting out or expanding their existing operations and counsels others on selling their business or pursuing other exit strategies.

MAXIM ZAVET

Maxim Zavet has many years experience in real estate law, having worked as a solicitor with several  reputable law firms before forming his own practice.

His caseload includes hundreds of real estate transactions for investment, residential and vacation properties. His experience and work for a diverse base of clients gives him a wide perspective on the intricate issues that can often muddle property transactions.

Maxim Zavet also has experience in real estate disputes, having dealt with a host of issues from contractual challenges to home warranty claims.

Before earning a law degree from the University of Windsor, Maxim Zavet received an undergraduate degree in political science from York University. Since then, he has been an active member of his community, participating in ratepayers' associations, condominium boards, municipal planning, and collaborating on political campaigns.

When it comes to real estate law, nobody is more passionate and prepared to handle your case.

					Third-Party Information Liability Disclaimer

					Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

				Contacts

				Contact information

                Jeffrey
                Levy

                  Title:

                Partner/Associate

                    Area of Responsibility:

                    Management Executive.

                  Telephone:

                (416) 777-2244

                  Ext:

                770

                  Facsimile:

                (416) 477-2847

                    Email:

                  JLev@LevyZavet.com

                Maxim
                Zavet

                  Title:

                Partner/Associate

                  Telephone:

                (416) 777-2244

                  Ext:

                790

                  Facsimile:

                (416) 477-2847

                    Email:

                  MZavet@LevyZavet.com

				Description

				Company description

            Country of Ownership:

              Canada

            Exporting:

              No

                Primary Industry (NAICS):

				541110 - Offices of Lawyers

            Primary Business Activity:

            Services

				Products, services and licensing

				Product / Service / Licensing

                              Service Name:

                            Legal services, law firm, lawyers offices

                            We offer a range of legal services including real estate, coporate, commercial, litigation, tax, wills and estates, intellectual property, family and domestic law, contracts and personal injury.

					Market

					Market profile

                        Alliances:

                            Financial

Sales/Marketing

                          Strategic alliances:

                        Looking to grow our law firm in different countries with expert lawyers in all fields/areas of law.

                          Industry sector market interests:

Service Industry

					Sector

					Sector information

                Unique applications:

              We are barristers and solicitors who only practice in areas that complement one another. That allows us to have a wider perspective and focus on the issue while providing our clients with thoughtful, tailored solutions to their legal concerns.

Our close-knit boutique firm is dedicated to providing unparalleled customer service to our clients. We guarantee accessibility, a timely response through phone or email, and fair billing practices for only time we spend adding value to your file.

Clients of Levy Zavet LLP know that they can call or email us at any time and our approachable, warm staff will help answer their questions and concerns. Our lawyers respond to clients quickly and provide them with flexible meeting times to accommodate their daily schedules and our flat-rate billing system puts clients at ease and gives them an advantage when they are budgeting their expenses.

JEFF LEVY

Jeff is an experienced Ontario business lawyer practicing primarily in the areas of corporate law, corporate finance, technology law, mergers and acquisitions, joint ventures, tax law and commercial finance. His primary role is serving as a trusted advisor to entrepreneurial and family-owned businesses of all sizes.

His experience and training in business law provide him with the background to counsel his clients on a wide variety of legal issues including private equity, venture capital and other financing; joint ventures and strategic business relationships; software development contracts, licensing agreements and other technology issues; sales agency and other distribution matters; and employment issues and executive compensation arrangements.

His clients range from start-ups seeking guidance on formation of their business entity, to established companies looking for new sources of capital to fuel their growth, to mature family-owned companies planning for transfer of the business to the next generation. He provides advice on buying a business for those starting out or expanding their existing operations and counsels others on selling their business or pursuing other exit strategies.

MAXIM ZAVET

Maxim Zavet has many years experience in real estate law, having worked as a solicitor with several  reputable law firms before forming his own practice.

His caseload includes hundreds of real estate transactions for investment, residential and vacation properties. His experience and work for a diverse base of clients gives him a wide perspective on the intricate issues that can often muddle property transactions.

Maxim Zavet also has experience in real estate disputes, having dealt with a host of issues from contractual challenges to home warranty claims.

Before earning a law degree from the University of Windsor, Maxim Zavet received an undergraduate degree in political science from York University. Since then, he has been an active member of his community, participating in ratepayers' associations, condominium boards, municipal planning, and collaborating on political campaigns.

When it comes to real estate law, nobody is more passionate and prepared to handle your case.

    Last Update Date 2015-07-20

Date Modified:

      <time>2017-03-02</time>

About government

Contact us

Departments and agencies

Public service and military

News

Treaties, laws and regulations

Government-wide reporting

Prime Minister

How government works

Open government

About this site

Social media

Mobile applications

About Canada.ca

Terms and conditions

Privacy

Top of Page

<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>


text:
var page = tabris.create("Page", {
  title: "Actions",
  topLevel: true
});

tabris.create("Action", {
  title: "Action",
  image: "images/share.png"
}).on("select", function() {
  console.log("Action selected.");
});

page.open();

redpajama_set_name: RedPajamaGithub


text:
title: "Dashboard overview"
linkTitle: "Overview"
description: "The Sensu backend includes the Sensu dashboard: a unified view of your Sensu resources with user-friendly tools to reduce alert fatigue. Read the doc to get started using the dashboard."
weight: 120
version: "5.15"
product: "Sensu Go"
platformContent: false
menu:
  sensu-go-5.15:
    parent: dashboard
---

- [Accessing the dashboard](#accessing-the-dashboard)
- [Signing in](#signing-in)
- [Namespaces](#namespaces)
- [Managing entities](#managing-entities)
- [Managing checks](#managing-checks)
- [Managing handlers](#managing-handlers)
- [Managing event filters](#managing-event-filters)
- [Managing mutators](#managing-mutators)
- [Themes](#themes)

The Sensu backend includes the **Sensu dashboard**:
a unified view of your events, entities, and checks with user-friendly tools to reduce alert fatigue.

**LICENSED TIER**: Unlock the Sensu dashboard homepage (shown below) in the Sensu Go dashboard with a Sensu license. To activate your license, see the [getting started guide][6].

Sensu dashboard homepage

### Accessing the dashboard
After [starting the Sensu backend][1], you can access the dashboard in your browser
by visiting http://localhost:3000. You may need to replace `localhost` with the
hostname or IP address where the Sensu backend is running.

### Signing in
Sign in to the dashboard with your [sensuctl][2] username and password.
See the [role-based access control reference][3] for [default user credentials][4] and instructions for [creating new users][5].

### Namespaces
The dashboard displays events, entities, checks, and silences for a single namespace at a time.
By default, the dashboard displays the `default` namespace.
To switch namespaces, select the menu icon in the upper-left corner, and choose a namespace from the dropdown.
**COMMERCIAL FEATURE**: The namespaces listed will be limited to those that the current user has access to.

Sensu dashboard namespace switcher

### Managing entities

You can delete Sensu entities using the dashboard entities page.

### Managing checks

**COMMERCIAL FEATURE**: Access check management in the packaged Sensu Go distribution. For more information, see the [getting started guide][6].

You can create, edit, and delete Sensu checks using the dashboard checks page.

### Managing handlers

**COMMERCIAL FEATURE**: Access handler management in the packaged Sensu Go distribution. For more information, see the [getting started guide][6].

You can create, edit, and delete Sensu handlers using the dashboard handlers page.

### Managing event filters

**COMMERCIAL FEATURE**: Access filter management in the packaged Sensu Go distribution. For more information, see the [getting started guide][6].

You can create, edit, and delete Sensu event filters using the dashboard filters page.

### Managing mutators

**COMMERCIAL FEATURE**: Access mutator management in the packaged Sensu Go distribution. For more information, see the [getting started guide][6].

You can create, edit, and delete Sensu mutators using the dashboard mutators page.

### Themes
Use the preferences menu to change the theme or switch to the dark theme.

[1]: ../../reference/backend#restarting-the-service
[2]: ../../sensuctl/reference/
[3]: ../../reference/rbac
[4]: ../../reference/rbac#default-user
[5]: ../../reference/rbac#creating-a-user
[6]: ../../getting-started/enterprise


text:
package org.artifactory.webapp.wicket.page.config.services.cron;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.artifactory.common.wicket.ajax.NoAjaxIndicatorDecorator;
import org.artifactory.common.wicket.behavior.JavascriptEvent;
import org.artifactory.common.wicket.component.links.BaseTitledLink;
import org.artifactory.webapp.wicket.util.CronUtils;

import java.util.Date;

/**
 * @author Yoav Aharoni
 */
public class CronNextDatePanel extends Panel {
    public CronNextDatePanel(String id, final FormComponent cronExpField) {
        super(id);

        String nextRun = getNextRunTime(cronExpField.getValue());
        final Label nextRunLabel = new Label("cronExpNextRun", nextRun);
        nextRunLabel.setOutputMarkupId(true);
        add(nextRunLabel);

        // send ajax request with only cronExpField
        BaseTitledLink calculateButton = new BaseTitledLink("calculate", "Refresh");
        calculateButton.add(new JavascriptEvent("onclick", new AbstractReadOnlyModel() {
            @Override
            public Object getObject() {
                return "dojo.byId('" + cronExpField.getMarkupId() + "').onchange();";
            }
        }));
        add(calculateButton);

        // update nextRunLabel on cronExpField change
        cronExpField.setOutputMarkupId(true);
        cronExpField.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                nextRunLabel.setDefaultModelObject(getNextRunTime(cronExpField.getValue()));
                target.add(nextRunLabel);
            }

            @Override
            protected void onError(AjaxRequestTarget target, RuntimeException e) {
                super.onError(target, e);
                nextRunLabel.setDefaultModelObject(getNextRunTime(cronExpField.getValue()));
                target.add(nextRunLabel);
            }

            @Override
            protected IAjaxCallDecorator getAjaxCallDecorator() {
                return new NoAjaxIndicatorDecorator();
            }
        });
    }

    private String getNextRunTime(String cronExpression) {
        if (StringUtils.isEmpty(cronExpression)) {
            return "The cron expression is blank.";
        }
        if (CronUtils.isValid(cronExpression)) {
            Date nextExecution = CronUtils.getNextExecution(cronExpression);
            if (nextExecution != null) {
                return formatDate(nextExecution);
            } else {
                return "Next run time is in the past.";
            }
        }
        return "The cron expression is invalid.";
    }

    private String formatDate(Date nextRunDate) {
        return nextRunDate.toString();
    }

}


text:
package org.shenit.tutorial.android.broadcast;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import org.shenit.tutorial.android.R;
import org.shenit.tutorial.android.notification.NotificationResultActivity;

/**
 * 供外部使用的广播接收类.
 */
public class NotificationBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        //创建点击NOTIFICATION时跳转的活动
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)        //set to true then notification will cancel itself once clicked
                .setContentTitle("Android Tutorial Notification")
                .setNumber(10)      //notification count
                .setContentText("We receive data -> "+intent.getStringExtra("message"));

        Intent resultIntent = new Intent(context,NotificationResultActivity.class);
        //set your data for the result activity here...

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT);

        builder.setContentIntent(pendingIntent);

        NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mgr.notify(01,builder.build());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Discord.WebSocket;
using SharedExtensions;

namespace MechHisui.FateGOLib
{
    public class FgoStatService
    {
        private readonly Timer _logintimer;
        internal FgoConfig Config { get; }

        internal FgoStatService(FgoConfig config, DiscordSocketClient client)
        {
            Config = config ?? throw new ArgumentNullException(nameof(config));

            _logintimer = new Timer(async o =>
            {
                await (client.GetChannel(120979035290468352ul) as SocketTextChannel)
                    .SendMessageAsync("Login bonuses have been distributed.").ConfigureAwait(false);
            }, null,
            new DateTimeWithZone(DateTime.UtcNow, FgoExtensions.JpnTimeZone)
                .TimeUntilNextLocalTimeAt(new TimeSpan(hours: 3, minutes: 59, seconds: 59)),
            TimeSpan.FromHours(24));
        }

        public IEnumerable<ServantProfile> LookupStats(string term, bool fullsearch = false)
        {
            var list = Config.FindServants(term)
                .Where(s => RegexMatchOneWord(s.Name, term) || s.Aliases.Any(a => RegexMatchOneWord(a.Alias, term)))
                .ToList();

            //if (!servants.Any() || fullsearch)
            //{
            //    servants = servants.Concat(list.Where(p => RegexMatchOneWord(p.Name, servant)));

            //    if (!servants.Any() || fullsearch)
            //    {
            //        var lookup = list
            //            .Where(s => s.Aliases.Any(a => a.Equals(servant, StringComparison.OrdinalIgnoreCase)))
            //            .ToList();

            //        if (lookup.Count == 0 || fullsearch)
            //        {
            //            lookup = lookup.Concat(list
            //                .Where(s => s.Aliases.Any(a => RegexMatchOneWord(a, servant))))
            //                .ToList();
            //        }

            //        if (lookup.Count > 0)
            //        {
            //            servants = servants.Concat(list.Where(p => lookup.Any(l => l.Id == p.Id)));
            //        }
            //    }
            //}

            //return servants.ToList();
            return list;
        }

        public IEnumerable<CEProfile> LookupCE(string name, bool fullsearch = false)
        {
            var list = Config.GetCEs();
            var ces = list
                .Where(ce => ce.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            if (!ces.Any() || fullsearch)
            {
                ces = ces.Concat(list.Where(ce => RegexMatchOneWord(ce.Name, name)));

                if (!ces.Any() || fullsearch)
                {
                    var lookup = list
                        .Where(ce => ce.Aliases.Any(a => a.Equals(name, StringComparison.OrdinalIgnoreCase)))
                        .ToList();

                    if (lookup.Count == 0 || fullsearch)
                    {
                        lookup = lookup.Concat(list
                            .Where(ce => ce.Aliases.Any(a => RegexMatchOneWord(a, name))))
                            .ToList();
                    }

                    if (lookup.Count > 0)
                    {
                        ces = ces.Concat(list.Where(ce => lookup.Any(l => l.Id == ce.Id)));
                    }
                }
            }

            return ces.ToList();
        }

        public IEnumerable<MysticCode> LookupMystic(string code, bool fullsearch = false)
        {
            var list = Config.GetMystics();
            var mystics = list
                .Where(m => m.Code.Equals(code, StringComparison.OrdinalIgnoreCase))
                .ToList();

            if (mystics.Count == 0 || fullsearch)
            {
                mystics = mystics.Concat(list.Where(m => RegexMatchOneWord(m.Code, code))).ToList();

                if (mystics.Count == 0 || fullsearch)
                {
                    var lookup = list
                        .Where(m => m.Aliases.Any(a => a.Equals(code, StringComparison.OrdinalIgnoreCase)))
                        .ToList();

                    if (lookup.Count == 0 || fullsearch)
                    {
                        lookup = lookup.Concat(list
                            .Where(m => m.Aliases.Any(a => RegexMatchOneWord(a, code))))
                            .ToList();
                    }

                    if (lookup.Count > 0)
                    {
                        mystics = mystics.Concat(list.Where(m => lookup.Any(l => l.Code == m.Code))).ToList();
                    }
                }
            }

            return mystics;
        }

        //public void ReadAliasList()
        //{
        //    FgoHelpers.ServantDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Config.ServantAliasesPath));
        //    FgoHelpers.CEDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Config.CEAliasesPath));
        //    FgoHelpers.MysticCodeDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Config.MysticAliasesPath));
        //}

        private static bool RegexMatchOneWord(string hay, string needle)
            => Regex.Match(hay, String.Concat(@"\b", needle, @"\b"), RegexOptions.IgnoreCase).Success;
    }
}


text:
// src/polyfills.js must be the first import.
import '../polyfills';

import {draw3p, init} from '../integration-lib';
import {register} from '../3p';

import {beaverads} from '../../ads/vendors/beaverads';

init(window);
register('beaverads', beaverads);

window.draw3p = draw3p;


text:
using System;

namespace task_3
{
    class Program
    {
        static void Main(string[] args)
        {
    Console.OutputEncoding = System.Text.Encoding.UTF8;
            // Define instructions
            Console.WriteLine("Ohjelma selvittää onko syötetty luku parillinen vai pariton, positiivinen vai negatiivinen.");
            bool isNumber;
            do
            {

                Console.Write("Syötä luku: ");
                // define variables
                string userInput;
                userInput = Console.ReadLine();

                int evaluatedNumber;
                isNumber = int.TryParse(userInput, out evaluatedNumber);

                // programming logics
                if (evaluatedNumber % 2 == 0)
                {
                    Console.WriteLine($"Numero {evaluatedNumber} on parillinen");
                }
                else if (evaluatedNumber % 2 == 1)
                {
                    Console.WriteLine($"Numero {evaluatedNumber} on pariton");
                }
                else
                {
                    Console.WriteLine($"Numero {evaluatedNumber} on pariton");
                }
                if (evaluatedNumber < 0)
                {
                    Console.WriteLine($"Numero {evaluatedNumber} on negatiivinen");
                }
                else if (evaluatedNumber >= 0)
                {
                    Console.WriteLine($"Numero {evaluatedNumber} on positiivinen");
                }

            } while (isNumber == true);
            Console.ReadKey();
        }
    }
}


text:
package com.burrito.matic.product;

import com.burrito.matic.inventory.Ingredient;
import com.burrito.matic.inventory.IngredientType;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Utility class to collect expressions and functions used to validate burritos.
 *
 * @author ewarner
 *
 */
public class RuleUtils {
	/**
	 * Expression defining a complete two ingredient burrito.
	 */
	protected static final String TWO_ING_COMPLETE = "meat >= 1 and salsa >= 1";

	/**
	 * Expression defining a complete three ingredient burrito.
	 */
	protected static final String THREE_ING_COMPLETE = "meat >= 1 and salsa >= 1 and toppings >= 1";

	/**
	 * Expression defining a valid two ingredient burrito.
	 */
	protected static final String TWO_VALIDATE_BURRITO = "meat == 1 and salsa == 1 and toppings == 0 and base <= 2";

	/**
	 * Expression defining a valid three ingredient burrito.
	 */
	protected static final String THREE_VALIDATE_BURRITO = "meat == 1 and salsa == 1 and toppings == 1 and base <= 2";

	/**
	 * Map defining a valid three ingredient burrito.
	 */
	protected static final EnumMap<IngredientType, Integer> THREE_VALIDATE_BURRITO_MAP = new EnumMap<IngredientType, Integer>(IngredientType.class);

	/**
	 * Expression defining if adding an ingredient will create a valid burrito.
	 */
	protected static final String TWO_VALIDATE_INGREDIENT = "meat <= 1 and salsa <= 1 and toppings == 0 and base <= 2";

	/**
	 * Expression defining if adding an ingredient will create a valid burrito.
	 */
	protected static final String THREE_VALIDATE_INGREDIENT = "meat <= 1 and salsa <= 1 and toppings <= 1 and base <= 2";

	/**
	 * Expression defining a valid initialized burrito bowl.
	 */
	protected static final String BOWL = "bowl == 1 and wrap == 0";

	/**
	 * Expression defining a valid initialized burrito wrap.
	 */
	protected static final String WRAP = "bowl == 0 and wrap == 1";

	/**
	 * Maximum number of ingredients.
	 */
	protected static int MAX_NUMBER_OF_INGREDIENTS = 12;

	static {
		THREE_VALIDATE_BURRITO_MAP.put(IngredientType.BASE, 2);
		THREE_VALIDATE_BURRITO_MAP.put(IngredientType.MEAT, 1);
		THREE_VALIDATE_BURRITO_MAP.put(IngredientType.SALSA, 1);
		THREE_VALIDATE_BURRITO_MAP.put(IngredientType.TOPPINGS, 1);
	}

	/**
	 * Evaluate a burrito for completeness against a two ingredient rule.
	 *
	 * @param product the burrito to be evaluated
	 * @return if the burrito is complete
	 */
	protected static boolean isCompleteTwoIngredient(BurritoProduct product) {
		Map<IngredientType, List<Ingredient>> ingredients = product
				.getBurritoIngredients();

		JexlEngine jexl = new JexlEngine();
		Expression expression = jexl
				.createExpression(RuleUtils.TWO_ING_COMPLETE);

		JexlContext jc = new MapContext();
		int x = (ingredients.get(IngredientType.MEAT) != null) ? ingredients
				.get(IngredientType.MEAT).size() : 0;
		int y = (ingredients.get(IngredientType.SALSA) != null) ? ingredients
				.get(IngredientType.SALSA).size() : 0;

		jc.set("meat", x);
		jc.set("salsa", y);

		return (Boolean) expression.evaluate(jc);
	}

	/**
	 * Evaluate an ingredient against a BurritoProduct to determine if the
	 * Burrito would be valid after the ingredient is added.
	 *
	 * @param product the product to be evaluated
	 * @param ingredient the ingredient to be added
	 * @param expression the expression defining a valid burrito
	 * @return if the ingredient is valid
	 */
	protected static boolean isValidIngredient(final BurritoProduct product,
			final Ingredient ingredient, String expression) {
		boolean valid = false;
		if (!ingredient.isInitial()) {
			Map<IngredientType, List<Ingredient>> ingredients = product
					.getBurritoIngredients();

			JexlEngine jexl = new JexlEngine();
			Expression exp = jexl.createExpression(expression);

			JexlContext jc = new MapContext();
			int w = ingredientCount(ingredients, IngredientType.BASE,
					ingredient.getType());
			int x = ingredientCount(ingredients, IngredientType.MEAT,
					ingredient.getType());
			int y = ingredientCount(ingredients, IngredientType.SALSA,
					ingredient.getType());
			int z = ingredientCount(ingredients, IngredientType.TOPPINGS,
					ingredient.getType());

			jc.set("base", w);
			jc.set("meat", x);
			jc.set("salsa", y);
			jc.set("toppings", z);

			valid = (Boolean) exp.evaluate(jc);
		}
		return valid;
	}

	/**
	 * Evaluate a burrito product against an expression to determine if the
	 * product is valid.
	 *
	 * @param product the product to be evaluated
	 * @param expression the expression to be used for evaluation
	 * @return is the product is valid
	 */
	protected static boolean isValidBurrito(final BurritoProduct product,
			String expression) {
		boolean valid = false;

		if(isInitialized(product)) {
			Map<IngredientType, List<Ingredient>> ingredients = product
					.getBurritoIngredients();

			JexlEngine jexl = new JexlEngine();
			Expression exp = jexl.createExpression(expression);

			JexlContext jc = new MapContext();
			int w = (ingredients.get(IngredientType.BASE) != null) ? ingredients
					.get(IngredientType.MEAT).size() : 0;
			int x = (ingredients.get(IngredientType.MEAT) != null) ? ingredients
					.get(IngredientType.MEAT).size() : 0;
			int y = (ingredients.get(IngredientType.SALSA) != null) ? ingredients
					.get(IngredientType.SALSA).size() : 0;
			int z = (ingredients.get(IngredientType.TOPPINGS) != null) ? ingredients
					.get(IngredientType.TOPPINGS).size() : 0;

			jc.set("base", w);
			jc.set("meat", x);
			jc.set("salsa", y);
			jc.set("toppings", z);

			valid = (Boolean) exp.evaluate(jc);
		}

		return valid;
	}

	/**
     * Support validation for addition ingredients.
     * Count number of ingredients, add one if the target ingredient is the same as the source ingredient.
     *
	 * @param ingredients the map of ingredients in a product
	 * @param source an ingredient type
	 * @param target the ingredient to be added
	 * @return count of ingredients
	 */
	private static int ingredientCount(
			final Map<IngredientType, List<Ingredient>> ingredients,
			final IngredientType source, final IngredientType target) {

		int count = (ingredients.get(source) != null) ? ingredients.get(source)
				.size() : 0;
		if (source.equals(target)) {
			count++;
		}

		return count;
	}

	/**
	 * Evaluates a product for completeness against the three ingredient
	 * expression. A complete products can be purchased.
	 *
	 * @param product
	 *            to be evaluated
	 * @return boolean result of the evaluation.
	 *
	 */
	protected static boolean isCompleteThreeIngredient(
			final BurritoProduct product) {
		Map<IngredientType, List<Ingredient>> ingredients = product
				.getBurritoIngredients();

		JexlEngine jexl = new JexlEngine();
		Expression expression = jexl
				.createExpression(RuleUtils.THREE_ING_COMPLETE);

		JexlContext jc = new MapContext();
		int x = (ingredients.get(IngredientType.MEAT) != null) ? ingredients
				.get(IngredientType.MEAT).size() : 0;
		int y = (ingredients.get(IngredientType.SALSA) != null) ? ingredients
				.get(IngredientType.SALSA).size() : 0;
		int z = (ingredients.get(IngredientType.TOPPINGS) != null) ? ingredients
				.get(IngredientType.TOPPINGS).size() : 0;

		jc.set("meat", x);
		jc.set("salsa", y);
		jc.set("toppings", z);

		return (Boolean) expression.evaluate(jc);
	}

	/**
	 * Check that a burrito has been initialized (has a bowl or tortilla).
	 *
	 * @param product product to be evaluated
	 * @return if the product has been initialized
	 */
	protected static boolean isInitialized(final BurritoProduct product) {
		Map<IngredientType, List<Ingredient>> ingredients = product
				.getBurritoIngredients();

		int bowls = 0;
		int wraps = 0;
		List<Ingredient> list = ingredients.get(IngredientType.BASE);
		if (list != null) {
			for (Ingredient ing : list) {
				if (ing.isBowl()) {
					bowls++;
				}
				if (ing.isWrap()) {
					wraps++;
				}
			}
		}

		JexlEngine jexl = new JexlEngine();
		String exp = product.isBowl() ? BOWL : WRAP;
		Expression expression = jexl.createExpression(exp);

		JexlContext jc = new MapContext();

		jc.set("bowl", bowls);
		jc.set("wrap", wraps);

		return (Boolean) expression.evaluate(jc);
	}

	/**
	 * Based on the product constraint and the ingredient could the
	 * ingredient serve as a base for the burrito.
	 * @param product product to be evaluated
	 * @param ingredient ingredient to be evaluated
	 * @return if the ingredient can be an initial ingredient
	 */
	protected static boolean isValidInitialIngredient(BurritoProduct product,
			Ingredient ingredient) {
		boolean valid = false;
		if (ingredient.isInitial()) {
			Map<IngredientType, List<Ingredient>> ingredients = product
					.getBurritoIngredients();

			int bowls = 0;
			int wraps = 0;
			List<Ingredient> list = ingredients.get(IngredientType.BASE);
			if (list != null) {
				for (Ingredient ing : list) {
					if (ing.isBowl()) {
						bowls++;
					}
					if (ing.isWrap()) {
						wraps++;
					}
				}
			}

			if (ingredient.isBowl()) {
				bowls++;
			} else {
				wraps++;
			}

			JexlEngine jexl = new JexlEngine();
			String exp = product.isBowl() ? BOWL : WRAP;
			Expression expression = jexl.createExpression(exp);

			JexlContext jc = new MapContext();

			jc.set("bowl", bowls);
			jc.set("wrap", wraps);

			valid = (Boolean) expression.evaluate(jc);

		}
		return valid;
	}

}


text:
This script is intended to be used to demonstrate the key features of
Simdem.

When you hit 'spacebar' a command will be displayed and
executed. Actually you can hit almost any key but we recommend
'spacebar' here because we've not told you about the special keys yet
and spacebar is not one of them.

```
echo "Hello World"
```

That's cool, lets try again:

```
echo "It might look like this was typed into the terminal (even more so if you ran SimDem with the '--style simulate' flag, that simulates a person typing), bit it really comes from a markdown file."
```

The date command will show that these commands are being executed in real time.

```
date
```

Results:

```expected_similarity=0.3
Sat Mar 12 08:59:01 UTC 2016
```

You can run almost any shell command this way.

# Special keys

Although we said "spacebar" above, in reality you can hit almost any
key. There are a few exceptions though:

## 'd' for description

Hitting 'd' will print all the text since the last command, that is it
will print the description of the next command to be executed.

```
echo "Hitting 'd' now will display the description for this command."
```

## 'b' for break

Hitting 'b' will "break" from the current script. This allows you to
type in commands that are not part of the script. This is particularly
useful when running in demo mode as it alllows you to respond to
questions by entering an unscripted command.

```
echo "Give it a go, why not hit 'b' and type 'ls', or some other command"
```

NOTE: at the time of writing it is not possible to use interactive
commands or commands.

# Next Steps

It's possible to provide a branching point a the end of a script. The
user can select one of a selection of options or they can enter "quit"
(or just "q") to exit SimDem.

  1. [Write SimDem documents](../syntax/README.md)
  2. [SimDem Index](../README.md)
  3. [Modes of operation](../modes/README.md)


text:
@interface ReducedMotionAnimator
    : NSObject<UIViewControllerAnimatedTransitioning>

// YES if the animation presents a tab; NO if it dismisses it.
@property(nonatomic, assign) BOOL presenting;

@end

#endif  // IOS_CHROME_BROWSER_UI_TAB_GRID_TRANSITIONS_REDUCED_MOTION_ANIMATOR_H_


text:
===========
URL Routing
===========

.. module:: werkzeug.routing

When it comes to combining multiple controller or view functions (however
you want to call them), you need a dispatcher.  A simple way would be
applying regular expression tests on ``PATH_INFO`` and call registered
callback functions that return the value.

Werkzeug provides a much more powerful system, similar to `Routes`_.  All the
objects mentioned on this page must be imported from :mod:`werkzeug.routing`, not
from :mod:`werkzeug`!

.. _Routes: https://routes.readthedocs.io/en/latest/

Quickstart
==========

Here is a simple example which could be the URL definition for a blog::

    from werkzeug.routing import Map, Rule, NotFound, RequestRedirect

    url_map = Map([
        Rule('/', endpoint='blog/index'),
        Rule('/<int:year>/', endpoint='blog/archive'),
        Rule('/<int:year>/<int:month>/', endpoint='blog/archive'),
        Rule('/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive'),
        Rule('/<int:year>/<int:month>/<int:day>/<slug>',
             endpoint='blog/show_post'),
        Rule('/about', endpoint='blog/about_me'),
        Rule('/feeds/', endpoint='blog/feeds'),
        Rule('/feeds/<feed_name>.rss', endpoint='blog/show_feed')
    ])

    def application(environ, start_response):
        urls = url_map.bind_to_environ(environ)
        try:
            endpoint, args = urls.match()
        except HTTPException, e:
            return e(environ, start_response)
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [f'Rule points to {endpoint!r} with arguments {args!r}']

So what does that do?  First of all we create a new :class:`Map` which stores
a bunch of URL rules.  Then we pass it a list of :class:`Rule` objects.

Each :class:`Rule` object is instantiated with a string that represents a rule
and an endpoint which will be the alias for what view the rule represents.
Multiple rules can have the same endpoint, but should have different arguments
to allow URL construction.

The format for the URL rules is straightforward, but explained in detail below.

Inside the WSGI application we bind the url_map to the current request which will
return a new :class:`MapAdapter`.  This url_map adapter can then be used to match
or build domains for the current request.

The :meth:`MapAdapter.match` method can then either return a tuple in the form
``(endpoint, args)`` or raise one of the three exceptions
:exc:`~werkzeug.exceptions.NotFound`, :exc:`~werkzeug.exceptions.MethodNotAllowed`,
or :exc:`~werkzeug.exceptions.RequestRedirect`.  For more details about those
exceptions have a look at the documentation of the :meth:`MapAdapter.match` method.

Rule Format
===========

Rule strings are URL paths with placeholders for variable parts in the
format ``<converter(arguments):name>``. ``converter`` and ``arguments``
(with parentheses) are optional. If no converter is given, the
``default`` converter is used (``string`` by default). The available
converters are discussed below.

Rules that end with a slash are "branches", others are "leaves". If
``strict_slashes`` is enabled (the default), visiting a branch URL
without a trailing slash will redirect to the URL with a slash appended.

Many HTTP servers merge consecutive slashes into one when receiving
requests. If ``merge_slashes`` is enabled (the default), rules will
merge slashes in non-variable parts when matching and building. Visiting
a URL with consecutive slashes will redirect to the URL with slashes
merged. If you want to disable ``merge_slashes`` for a :class:`Rule` or
:class:`Map`, you'll also need to configure your web server
appropriately.

Built-in Converters
===================

Converters for common types of URL variables are built-in. The available
converters can be overridden or extended through :attr:`Map.converters`.

.. autoclass:: UnicodeConverter

.. autoclass:: PathConverter

.. autoclass:: AnyConverter

.. autoclass:: IntegerConverter

.. autoclass:: FloatConverter

.. autoclass:: UUIDConverter

Maps, Rules and Adapters
========================

.. autoclass:: Map
   :members:

   .. attribute:: converters

      The dictionary of converters.  This can be modified after the class
      was created, but will only affect rules added after the
      modification.  If the rules are defined with the list passed to the
      class, the `converters` parameter to the constructor has to be used
      instead.

.. autoclass:: MapAdapter
   :members:

.. autoclass:: Rule
   :members: empty

Rule Factories
==============

.. autoclass:: RuleFactory
   :members: get_rules

.. autoclass:: Subdomain

.. autoclass:: Submount

.. autoclass:: EndpointPrefix

Rule Templates
==============

.. autoclass:: RuleTemplate

Custom Converters
=================

You can add custom converters that add behaviors not provided by the
built-in converters. To make a custom converter, subclass
:class:`BaseConverter` then pass the new class to the :class:`Map`
``converters`` parameter, or add it to
:attr:`url_map.converters <Map.converters>`.

The converter should have a ``regex`` attribute with a regular
expression to match with. If the converter can take arguments in a URL
rule, it should accept them in its ``__init__`` method.

It can implement a ``to_python`` method to convert the matched string to
some other object. This can also do extra validation that wasn't
possible with the ``regex`` attribute, and should raise a
:exc:`werkzeug.routing.ValidationError` in that case. Raising any other
errors will cause a 500 error.

It can implement a ``to_url`` method to convert a Python object to a
string when building a URL. Any error raised here will be converted to a
:exc:`werkzeug.routing.BuildError` and eventually cause a 500 error.

This example implements a ``BooleanConverter`` that will match the
strings ``"yes"``, ``"no"``, and ``"maybe"``, returning a random value
for ``"maybe"``. ::

    from random import randrange
    from werkzeug.routing import BaseConverter, ValidationError

    class BooleanConverter(BaseConverter):
        regex = r"(?:yes|no|maybe)"

        def __init__(self, url_map, maybe=False):
            super().__init__(url_map)
            self.maybe = maybe

        def to_python(self, value):
            if value == "maybe":
                if self.maybe:
                    return not randrange(2)
                raise ValidationError
            return value == 'yes'

        def to_url(self, value):
            return "yes" if value else "no"

    from werkzeug.routing import Map, Rule

    url_map = Map([
        Rule("/vote/<bool:werkzeug_rocks>", endpoint="vote"),
        Rule("/guess/<bool(maybe=True):foo>", endpoint="guess")
    ], converters={'bool': BooleanConverter})

If you want to change the default converter, assign a different
converter to the ``"default"`` key.

Host Matching
=============

.. versionadded:: 0.7

Starting with Werkzeug 0.7 it's also possible to do matching on the whole
host names instead of just the subdomain.  To enable this feature you need
to pass ``host_matching=True`` to the :class:`Map` constructor and provide
the `host` argument to all routes::

    url_map = Map([
        Rule('/', endpoint='www_index', host='www.example.com'),
        Rule('/', endpoint='help_index', host='help.example.com')
    ], host_matching=True)

Variable parts are of course also possible in the host section::

    url_map = Map([
        Rule('/', endpoint='www_index', host='www.example.com'),
        Rule('/', endpoint='user_index', host='<user>.example.com')
    ], host_matching=True)

WebSockets
==========

.. versionadded:: 1.0

If a :class:`Rule` is created with ``websocket=True``, it will only
match if the :class:`Map` is bound to a request with a ``url_scheme`` of
``ws`` or ``wss``.

.. note::

   Werkzeug has no further WebSocket support beyond routing. This
   functionality is mostly of use to ASGI projects.

.. code-block:: python

    url_map = Map([
        Rule("/ws", endpoint="comm", websocket=True),
    ])
    adapter = map.bind("example.org", "/ws", url_scheme="ws")
    assert adapter.match() == ("comm", {})

If the only match is a WebSocket rule and the bind is HTTP (or the
only match is HTTP and the bind is WebSocket) a
:exc:`WebsocketMismatch` (derives from
:exc:`~werkzeug.exceptions.BadRequest`) exception is raised.

As WebSocket URLs have a different scheme, rules are always built with a
scheme and host, ``force_external=True`` is implied.

.. code-block:: python

    url = adapter.build("comm")
    assert url == "ws://example.org/ws"


text:
<?php

namespace Digital\PointageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * History
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Digital\PointageBundle\Entity\HistoryRepository")
 */
class History
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="datetime", type="datetime")
     */
    private $datetime;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255)
     */
    private $type;

    /**
     * @var integer
     *
     * @ORM\Column(name="id_user", type="integer")
     */
    private $idUser;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set datetime
     *
     * @param \DateTime $datetime
     * @return History
     */
    public function setDatetime($datetime)
    {
        $this->datetime = $datetime;

        return $this;
    }

    /**
     * Get datetime
     *
     * @return \DateTime
     */
    public function getDatetime()
    {
        return $this->datetime;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return History
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set idUser
     *
     * @param integer $idUser
     * @return History
     */
    public function setIdUser($idUser)
    {
        $this->idUser = $idUser;

        return $this;
    }

    /**
     * Get idUser
     *
     * @return integer
     */
    public function getIdUser()
    {
        return $this->idUser;
    }
}


text:
package liquibase.sqlgenerator.core;

import liquibase.Scope;
import liquibase.database.Database;
import liquibase.database.core.AbstractDb2Database;
import liquibase.database.core.Db2zDatabase;
import liquibase.database.core.InformixDatabase;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.database.core.SQLiteDatabase;
import liquibase.database.core.SybaseASADatabase;
import liquibase.database.core.SybaseDatabase;
import liquibase.datatype.DatabaseDataType;
import liquibase.exception.DatabaseException;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.AutoIncrementConstraint;
import liquibase.statement.DatabaseFunction;
import liquibase.statement.ForeignKeyConstraint;
import liquibase.statement.NotNullConstraint;
import liquibase.statement.UniqueConstraint;
import liquibase.statement.*;
import liquibase.statement.core.CreateTableStatement;
import liquibase.structure.core.ForeignKey;
import liquibase.structure.core.Relation;
import liquibase.structure.core.Schema;
import liquibase.structure.core.Sequence;
import liquibase.structure.core.Table;
import liquibase.util.StringUtil;

import java.math.BigInteger;
import java.util.*;

public class CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> {

    @Override
    public ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        ValidationErrors validationErrors = new ValidationErrors();
        validationErrors.checkRequiredField("tableName", createTableStatement.getTableName());
        validationErrors.checkRequiredField("columns", createTableStatement.getColumns());
        return validationErrors;
    }

    @Override
    public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {

        List<Sql> additionalSql = new ArrayList<>();

        StringBuilder buffer = new StringBuilder();
        buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(),
                statement.getSchemaName(), statement.getTableName())).append(" ");
        buffer.append("(");

        boolean isSinglePrimaryKeyColumn = (statement.getPrimaryKeyConstraint() != null) && (statement
                .getPrimaryKeyConstraint().getColumns().size() == 1);

        boolean isPrimaryKeyAutoIncrement = false;

        Iterator<String> columnIterator = statement.getColumns().iterator();

        BigInteger mysqlTableOptionStartWith = null;

        /* We have reached the point after "CREATE TABLE ... (" and will now iterate through the column list. */
        while (columnIterator.hasNext()) {
            String column = columnIterator.next();
            DatabaseDataType columnType = statement.getColumnTypes().get(column).toDatabaseDataType(database);
            buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, true));

            buffer.append(" ").append(columnType);

            AutoIncrementConstraint autoIncrementConstraint = null;

            for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
                if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
                    autoIncrementConstraint = currentAutoIncrementConstraint;
                    break;
                }
            }

            boolean isAutoIncrementColumn = autoIncrementConstraint != null;
            boolean isPrimaryKeyColumn = (statement.getPrimaryKeyConstraint() != null) && statement
                    .getPrimaryKeyConstraint().getColumns().contains(column);
            isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || (isPrimaryKeyColumn && isAutoIncrementColumn);

            if ((database instanceof SQLiteDatabase) &&
                    isSinglePrimaryKeyColumn &&
                    isPrimaryKeyColumn &&
                    isAutoIncrementColumn) {
                String pkName = StringUtil.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
                if (pkName == null) {
                    pkName = database.generatePrimaryKeyName(statement.getTableName());
                }
                if (pkName != null) {
                    buffer.append(" CONSTRAINT ");
                    buffer.append(database.escapeConstraintName(pkName));
                }
                buffer.append(" PRIMARY KEY");
            }

            // for the serial data type in postgres, there should be no default value
            if (!columnType.isAutoIncrement() && (statement.getDefaultValue(column) != null)) {
                Object defaultValue = statement.getDefaultValue(column);
                if (database instanceof MSSQLDatabase) {
                    String constraintName = statement.getDefaultValueConstraintName(column);
                    if (constraintName == null) {
                        constraintName = ((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column);
                    }
                    buffer.append(" CONSTRAINT ").append(database.escapeObjectName(constraintName, ForeignKey.class));
                }
                if ((database instanceof OracleDatabase) && statement.getDefaultValue(column).toString().startsWith
                        ("GENERATED ALWAYS ")) {
                    buffer.append(" ");
                } else if (database instanceof Db2zDatabase && statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP")
                        || statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
                    buffer.append(" ");
                } else {
                    buffer.append(" DEFAULT ");
                }

                if (defaultValue instanceof DatabaseFunction) {
                    buffer.append(database.generateDatabaseFunctionValue((DatabaseFunction) defaultValue));
                } else if (database instanceof Db2zDatabase) {
                    if (statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP")) {
                        buffer.append("");
                    }
                    if (statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
                        buffer.append("GENERATED BY DEFAULT AS IDENTITY");
                    }
                    if (statement.getDefaultValue(column).toString().contains("CURRENT USER")) {
                        buffer.append("SESSION_USER ");
                    }
                    if (statement.getDefaultValue(column).toString().contains("CURRENT SQLID")) {
                        buffer.append("CURRENT SQLID ");
                    }
                } else {
                    buffer.append(statement.getColumnTypes().get(column).objectToSql(defaultValue, database));
                }
            }

            if (isAutoIncrementColumn) {
                // TODO: check if database supports auto increment on non primary key column
                if (database.supportsAutoIncrement()) {
                    String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy(), autoIncrementConstraint.getGenerationType(), autoIncrementConstraint.getDefaultOnNull());

                    if (!"".equals(autoIncrementClause)) {
                        buffer.append(" ").append(autoIncrementClause);
                    }

                    if (autoIncrementConstraint.getStartWith() != null) {
                        if (database instanceof PostgresDatabase) {
                            int majorVersion = 9;
                            try {
                                majorVersion = database.getDatabaseMajorVersion();
                            } catch (DatabaseException e) {
                                // ignore
                            }
                            if (majorVersion < 10) {
                                String sequenceName = statement.getTableName() + "_" + column + "_seq";
                                additionalSql.add(new UnparsedSql("alter sequence " + database.escapeSequenceName(statement.getCatalogName(), statement.getSchemaName(), sequenceName) + " start with " + autoIncrementConstraint.getStartWith(), new Sequence().setName(sequenceName).setSchema(statement.getCatalogName(), statement.getSchemaName())));
                            }
                        } else if (database instanceof MySQLDatabase) {
                            mysqlTableOptionStartWith = autoIncrementConstraint.getStartWith();
                        }
                    }
                } else {
                    Scope.getCurrentScope().getLog(getClass()).warning(database.getShortName()+" does not support autoincrement columns as requested for "+(database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())));
                }
            }

            // Do we have a NOT NULL constraint for this column?
            if (statement.getNotNullColumns().get(column) != null) {
                if (!database.supportsNotNullConstraintNames()) {
                    buffer.append(" NOT NULL");
                } else {
                    /* Determine if the NOT NULL constraint has a name. */
                    NotNullConstraint nnConstraintForThisColumn = statement.getNotNullColumns().get(column);
                    String nncName = StringUtil.trimToNull(nnConstraintForThisColumn.getConstraintName());
                    if (nncName == null) {
                        buffer.append(" NOT NULL");
                    } else {
                        buffer.append(" CONSTRAINT ");
                        buffer.append(database.escapeConstraintName(nncName));
                        buffer.append(" NOT NULL");
                    }

                    if (!nnConstraintForThisColumn.shouldValidateNullable()) {
                        if (database instanceof OracleDatabase) {
                            buffer.append(" ENABLE NOVALIDATE ");
                        }
                    }
                } // does the DB support constraint names?
            } else {
                if ((database instanceof SybaseDatabase) || (database instanceof SybaseASADatabase) || (database
                        instanceof MySQLDatabase) || ((database instanceof MSSQLDatabase) && columnType.toString()
                        .toLowerCase().contains("timestamp"))) {
                    buffer.append(" NULL");
                } // Do we need to specify NULL explicitly?
            } // Do we have a NOT NULL constraint for this column?

            if ((database instanceof MySQLDatabase) && (statement.getColumnRemarks(column) != null)) {
                buffer.append(" COMMENT '" + database.escapeStringForDatabase(statement.getColumnRemarks(column)) + "'");
            }

            if (columnIterator.hasNext()) {
                buffer.append(", ");
            }
        }

        buffer.append(",");

        if (!((database instanceof SQLiteDatabase) &&
                isSinglePrimaryKeyColumn &&
                isPrimaryKeyAutoIncrement)) {

            if ((statement.getPrimaryKeyConstraint() != null) && !statement.getPrimaryKeyConstraint().getColumns()
                    .isEmpty()) {
                if (database.supportsPrimaryKeyNames()) {
                    String pkName = StringUtil.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
                    if (pkName == null) {
                        // TODO ORA-00972: identifier is too long
                        // If tableName lenght is more then 28 symbols
                        // then generated pkName will be incorrect
                        pkName = database.generatePrimaryKeyName(statement.getTableName());
                    }
                    if (pkName != null) {
                        buffer.append(" CONSTRAINT ");
                        buffer.append(database.escapeConstraintName(pkName));
                    }
                }
                buffer.append(" PRIMARY KEY (");
                buffer.append(database.escapeColumnNameList(StringUtil.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
                buffer.append(")");
                // Setting up table space for PK's index if it exist
                if (((database instanceof OracleDatabase) || (database instanceof PostgresDatabase)) && (statement
                        .getPrimaryKeyConstraint().getTablespace() != null)) {
                    buffer.append(" USING INDEX TABLESPACE ");
                    buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
                }
                buffer.append(!statement.getPrimaryKeyConstraint().shouldValidatePrimaryKey() ? " ENABLE NOVALIDATE " : "");
                buffer.append(",");
            }
        }

        for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
            if (!(database instanceof InformixDatabase)) {
                buffer.append(" CONSTRAINT ");
                buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
            }
            String referencesString = fkConstraint.getReferences();

            buffer.append(" FOREIGN KEY (")
                    .append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
                    .append(") REFERENCES ");
            if (referencesString != null) {
                if (!referencesString.contains(".") && (database.getDefaultSchemaName() != null) && database
                        .getOutputDefaultSchema()) {
                    referencesString = database.escapeObjectName(database.getDefaultSchemaName(), Schema.class) + "." + referencesString;
                }
                buffer.append(referencesString);
            } else {
                buffer.append(database.escapeObjectName(fkConstraint.getReferencedTableCatalogName(), fkConstraint.getReferencedTableSchemaName(), fkConstraint.getReferencedTableName(), Table.class))
                        .append("(")
                        .append(database.escapeColumnNameList(fkConstraint.getReferencedColumnNames()))
                        .append(")");

            }

            if (fkConstraint.isDeleteCascade()) {
                buffer.append(" ON DELETE CASCADE");
            }

            if ((database instanceof InformixDatabase)) {
                buffer.append(" CONSTRAINT ");
                buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
            }

            if (fkConstraint.isInitiallyDeferred()) {
                buffer.append(" INITIALLY DEFERRED");
            }
            if (fkConstraint.isDeferrable()) {
                buffer.append(" DEFERRABLE");
            }

            if (database instanceof OracleDatabase) {
                buffer.append(!fkConstraint.shouldValidateForeignKey() ? " ENABLE NOVALIDATE " : "");
            }

            buffer.append(",");
        }

        /*
         * In the current syntax, UNIQUE constraints can only be set per column on table creation.
         * To alleviate this problem we combine the columns of unique constraints that have the same name.
         */
        LinkedHashMap<String, UniqueConstraint> namedUniqueConstraints = new LinkedHashMap<>();
        List<UniqueConstraint> unnamedUniqueConstraints = new LinkedList<>();
        for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
            if (uniqueConstraint.getConstraintName() == null) {  // Only combine uniqueConstraints that have a name.
                unnamedUniqueConstraints.add(uniqueConstraint);
            } else {
                String constraintName = uniqueConstraint.getConstraintName();
                UniqueConstraint existingConstraint = namedUniqueConstraints.get(constraintName);

                if (existingConstraint != null) {
                    if (uniqueConstraint.shouldValidateUnique()) {
                        //if validateUnique = true on only one column, make sure it is true
                        existingConstraint.setValidateUnique(true);
                    }

                    existingConstraint.getColumns().addAll(uniqueConstraint.getColumns());
                } else {
                    // if we haven't seen the constraint before put it in the map.
                    namedUniqueConstraints.put(constraintName, uniqueConstraint);
                }
            }
        }

        unnamedUniqueConstraints.addAll(namedUniqueConstraints.values());

        for (UniqueConstraint uniqueConstraint : unnamedUniqueConstraints) {
            if (uniqueConstraint.getConstraintName() != null) {
                buffer.append(" CONSTRAINT ");
                buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
            }
            buffer.append(" UNIQUE (");
            buffer.append(database.escapeColumnNameList(StringUtil.join(uniqueConstraint.getColumns(), ", ")));
            buffer.append(")");
            if (database instanceof OracleDatabase) {
                buffer.append(!uniqueConstraint.shouldValidateUnique() ? " ENABLE NOVALIDATE " : "");
            }
            buffer.append(",");
        }

        /*
         * Here, the list of columns and constraints in the form
         * ( column1, ..., columnN, constraint1, ..., constraintN,
         * ends. We cannot leave an expression like ", )", so we remove the last comma.
         */
        String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";

        if ((database instanceof MySQLDatabase) && (mysqlTableOptionStartWith != null)) {
            Scope.getCurrentScope().getLog(getClass()).info("[MySQL] Using last startWith statement ("+mysqlTableOptionStartWith.toString()+") as table option.");
            sql += " " + ((MySQLDatabase) database).getTableOptionAutoIncrementStartWithClause(mysqlTableOptionStartWith);
        }

        if ((statement.getTablespace() != null) && database.supportsTablespaces()) {
            if ((database instanceof MSSQLDatabase) || (database instanceof SybaseASADatabase)) {
                sql += " ON " + statement.getTablespace();
            } else if ((database instanceof AbstractDb2Database) || (database instanceof InformixDatabase)) {
                sql += " IN " + statement.getTablespace();
            } else {
                sql += " TABLESPACE " + statement.getTablespace();
            }
        }

        if ((database instanceof MySQLDatabase) && (statement.getRemarks() != null)) {
            sql += " COMMENT='" + database.escapeStringForDatabase(statement.getRemarks()) + "' ";
        }
        additionalSql.add(0, new UnparsedSql(sql, getAffectedTable(statement)));
        return additionalSql.toArray(new Sql[additionalSql.size()]);
    }

    protected Relation getAffectedTable(CreateTableStatement statement) {
        return new Table().setName(statement.getTableName()).setSchema(new Schema(statement.getCatalogName(), statement.getSchemaName()));
    }

}


text:
classdef masivPreLoader<handle
    properties
        parent
        position

        nBefore
        nAfter
        hMainPanel

        hEnabledCheckBox

        hViewChangedListener
        hKeyboardListener
    end

    methods
        function obj=masivPreLoader(parent, position)
            obj.parent=parent;
            obj.position=position;

            fSize=masivSetting('font.name');
            if fSize>1
                fSize=0.85;
            end

            %% Settings
            try
                masivSetting('preLoader');
            catch
                masivSetting('preLoader.nBefore', 10)
                masivSetting('preLoader.nAfter', 10)
                masivSetting('preLoader.position', [1000 500 200 200]);
            end
            obj.hMainPanel=uipanel(...
                'Units', 'normalized', ...
                'Position',obj.position , ...
                'BackgroundColor', masivSetting('viewer.panelBkgdColor'), ...
                'HitTest', 'off');

             uicontrol(...
                'Parent', obj.hMainPanel, ...
                'Style', 'text', ...
                'Units', 'normalized', ...
                'Position', [0.02 0.8 0.96 0.17], ...
                'FontUnits','normalized', ...
                'FontSize',fSize, ...
                'FontName', masivSetting('font.name'), ...
                'FontWeight', 'bold', ...
                'String', 'Z-PreCaching', ...
                'HorizontalAlignment', 'center', ...
                'BackgroundColor', masivSetting('viewer.panelBkgdColor'), ...
                'ForegroundColor', masivSetting('viewer.textMainColor'), ...
                'HitTest', 'off');

           setUpSettingBox('Before:', 'preLoader.nBefore', 0.35, obj, 'nBefore')
           setUpSettingBox('After:', 'preLoader.nAfter', 0.05, obj, 'nAfter')

           obj.hEnabledCheckBox=uicontrol(...
               'Style', 'checkbox', ...
               'Parent', obj.hMainPanel, ...
               'Units', 'normalized', ...
               'Position', [0.05 0.4 0.45 0.15], ...
               'HorizontalAlignment', 'center', ...
               'FontName', masivSetting('font.name'), ...
               'FontUnits','normalized', ...
               'FontSize',fSize, ...
               'BackgroundColor', masivSetting('viewer.panelBkgdColor'), ...
               'ForegroundColor', masivSetting('viewer.textMainColor'), ...
               'String', 'Enable (p)', ...
               'Value', 0, ...
               'Callback', {@enabledCheckboxValueChange, obj});

           obj.hViewChangedListener=event.listener(obj.parent, 'ViewChanged', @obj.viewChangedListenerCallback);
           obj.hKeyboardListener=event.listener(obj.parent, 'KeyPress', @obj.handleMainWindowKeyPress);

           obj.viewChangedListenerCallback;
        end

        function doPreLoading(obj)
            if obj.hEnabledCheckBox.Value

                masivDebugTimingInfo(1, 'PreLoader: starting', toc, 's')

                currentView_spec=getCurrentView(obj);
                newViewsToCreate_spec=createNewViewSpecs(obj, currentView_spec);
                newViewsToCreate_spec=excludeViewSpecsMatchingAlreadyLoadedGZV(obj, newViewsToCreate_spec);
                 masivDebugTimingInfo(1, 'PreLoader: Views to create calculated', toc, 's')

                if ~isempty(newViewsToCreate_spec)
                    newViewsToCreate_spec=sortByDistanceFromCurrentPlace(newViewsToCreate_spec, currentView_spec);
                    % Initialise
                    newViews(numel(newViewsToCreate_spec))=masivZoomedView;

                    for ii=1:numel(newViewsToCreate_spec)
                        newViews(ii)=createGZV(obj, newViewsToCreate_spec(ii));
                        startLoading(newViews(ii));
                        prepareTimer(newViews(ii), 1);
                    end

                    masivDebugTimingInfo(1, 'PreLoader: Views created', toc, 's')
                    addNewViewsToZVMArray(obj, newViews)

                    for ii=1:numel(newViews)
                        start(newViews(ii).checkForLoadedImageTimer);
                    end
                    masivDebugTimingInfo(1, 'PreLoader: All timers started', toc, 's')
                else
                    masivDebugTimingInfo(1, 'PreLoader: All views in memory', toc, 's')
                end

            end
        end
        %% Destructor
        function delete(obj)
            delete(obj.hMainPanel)
        end
    end

    %% Listener Callbacks
    methods(Access=protected)
        function viewChangedListenerCallback(obj, ~,~)
            if obj.parent.mainDisplay.zoomedViewNeeded
                obj.doPreLoading
            end
        end
        function handleMainWindowKeyPress(obj, ~,ev)
            keyPress([], ev.KeyPressData, obj)
        end

    end
end

%% Other callbacks
function enabledCheckboxValueChange(chckbx, ~, parentObj)
    if chckbx.Value
        parentObj.doPreLoading;
    end
end

function keyPress(~, eventdata, obj)
    key=eventdata.Key;
    ctrlMod=ismember('control', eventdata.Modifier);

    if strcmp(key, 'p') && ~ctrlMod
        obj.hEnabledCheckBox.Value=~obj.hEnabledCheckBox.Value;
        enabledCheckboxValueChange(obj.hEnabledCheckBox, [], obj)
    end
end

%% Settings changes
function setUpSettingBox(displayName, settingName, yPosition, parentObject, objectFieldName)
    fn=masivSetting('font.name');
    fs=masivSetting('font.size');
    if fs>1
        fs=0.85;
    end

    hEdit=uicontrol(...
        'Style', 'edit', ...
        'Parent', parentObject.hMainPanel, ...
        'Units', 'normalized', ...
        'Position', [0.76 yPosition 0.2 0.24], ...
        'FontName', fn, ...
        'FontUnits','normalized', ...
        'FontSize', fs, ...
        'BackgroundColor', masivSetting('viewer.panelBkgdColor'), ...
        'ForegroundColor', masivSetting('viewer.textMainColor'), ...
        'UserData', settingName);

    hEdit.String=num2str(masivSetting(settingName));
    if nargin>4 && ~isempty(objectFieldName)
        hEdit.Callback={@checkAndUpdateNewNumericSetting, parentObject, objectFieldName};
        parentObject.(objectFieldName)=masivSetting(settingName);
    else
         hEdit.Callback=@checkAndUpdateNewNumericSetting;
    end

    uicontrol(...
        'Style', 'text', ...
        'Parent', parentObject.hMainPanel, ...
        'Units', 'normalized', ...
        'Position', [0.5 yPosition+0.04 0.24 0.14], ...
        'HorizontalAlignment', 'right', ...
        'FontName', fn, ...
        'FontUnits','normalized', ...
        'FontSize', fs, ...
        'BackgroundColor', masivSetting('viewer.panelBkgdColor'), ...
        'ForegroundColor', masivSetting('viewer.textMainColor'), ...
        'String', displayName);

end

function checkAndUpdateNewNumericSetting(obj,ev, parentObject, fieldName)
    numEquiv=(str2num(ev.Source.String)); %#ok<ST2NM>
    if ~isempty(numEquiv)
        masivSetting(obj.UserData, numEquiv)
        if nargin>3&&~isempty(fieldName)
            parentObject.(fieldName)=numEquiv;
        end
    else
        obj.String=num2str(masivSetting(obj.UserData));
    end
end

%% View spec calculations

function v=getCurrentView(obj)
    gDisplay=obj.parent.mainDisplay;

    v.X=xlim(gDisplay.axes);
    v.Y=ylim(gDisplay.axes);
    v.Z=gDisplay.currentZPlaneOriginalVoxels;
    v.DS=gDisplay.downSamplingForCurrentZoomLevel;

end

function newViews_spec=createNewViewSpecs(obj, currentViewSpec)

    % Work out which Z voxels will be needed
    sliceZ=calculateZVoxels_ofSlicesToLoad(obj, currentViewSpec.Z);
    % Pre-initialise
    newViews_spec=repmat(currentViewSpec, numel(sliceZ), 1);

    for ii=1:numel(sliceZ)
         %% Set up new spec: same as old spec, but with a different Z.
         newViews_spec(ii).Z=sliceZ(ii);
         newViews_spec(ii).region=[floor(newViews_spec(ii).X(1)) floor(newViews_spec(ii).Y(1))...
                                    ceil(range(newViews_spec(ii).X)) ceil(range(newViews_spec(ii).Y))];
     end

end

function z=calculateZVoxels_ofSlicesToLoad(obj, currentViewZ)
    % Converts number of slices before and after in to original voxel
    % address in Z, so it's easy to find the right file
    currentViewZIdx=find(obj.parent.MainStack.idx==currentViewZ);
    idx=currentViewZIdx+[-obj.nBefore:-1 1:obj.nAfter];
    idx(idx<1 | idx>obj.parent.MainStack.idx(end))=[]; %remove index values that aren't real
    z=obj.parent.MainStack.idx(idx);
end

function specsToCreate=excludeViewSpecsMatchingAlreadyLoadedGZV(obj,specsToCreate)
    masivDebugTimingInfo(1, 'PreLoader: Checking for existing matching views', toc, 's')
    viewsInMemory_spec=getLoadedViewSpecs(obj);
    masivDebugTimingInfo(1, 'PreLoader: existing matching viewspecs retrieved', toc, 's')
    specsThatAlreadyExist=[];

    for ii=1:numel(specsToCreate)
        if checkForMatchingView(clipRegionSpecBorder(specsToCreate(ii)), viewsInMemory_spec)
            specsThatAlreadyExist=[specsThatAlreadyExist ii]; %#ok<AGROW>
        end
    end
    specsToCreate(specsThatAlreadyExist)=[];
end

function newViewsToCreate_spec=sortByDistanceFromCurrentPlace(newViewsToCreate_spec, currentView_spec)
    [~, sortOrder]=sort(abs([newViewsToCreate_spec.Z]-currentView_spec.Z));
    newViewsToCreate_spec=newViewsToCreate_spec(sortOrder);
end

%% New view creation and loading
function newView=createGZV(obj, spec)

    updateFcn={@updateIfShowingThisZoomedView, obj, 'newObj'};

    %% Create new view
    newView=obj.parent.mainDisplay.zoomedViewManager.createNewView(spec.region,spec.Z, spec.DS, updateFcn);

end

function startLoading(gv)
     %% Load in background
    gv.backgroundLoad([], 0)
end

function prepareTimer(gv, timerDelay)
    gv.checkForLoadedImageTimer.StartDelay=timerDelay; %1 second lockout stops the fucker jamming
end

function addNewViewsToZVMArray(obj, newViews)
    zvm=obj.parent.mainDisplay.zoomedViewManager;
    zvm.addViewsToArray(newViews);
end

%% Region spec
function v=clipRegionSpecBorder(v)
%% Allow a slightly smaller image (5xdownsampling) to be considered a match
    %    (Takes care of rounding errors)
    allowablePixelsSmallerThanView=5*v.DS;
    v.X=v.X+[1 -1]*allowablePixelsSmallerThanView;
    v.Y=v.Y+[1 -1]*allowablePixelsSmallerThanView;

    v.X=round(v.X);
    v.Y=round(v.Y);
end

function v=getLoadedViewSpecs(obj)
    gDisplayManager=obj.parent.mainDisplay.zoomedViewManager;

    v.X=gDisplayManager.planesInMemX;
    v.Y=gDisplayManager.planesInMemY;
    v.Z=gDisplayManager.planesInMemZ;
    v.DS=gDisplayManager.planesInMemDS;

end

function vIdx=checkForMatchingView(viewSpec, viewsInMemory)
    zMatch=find(viewSpec.Z==viewsInMemory.Z);
    if any(zMatch)
        inMemX=viewsInMemory.X(zMatch);
        xzMatch=find((cellfun(@min, inMemX)<=viewSpec.X(1))&(cellfun(@max, inMemX)>=viewSpec.X(2)));
        if any(xzMatch)
            inMemY=viewsInMemory.Y(zMatch);
            yxzMatch=find((cellfun(@min, inMemY)<=viewSpec.Y(1))&(cellfun(@max, inMemY)>=viewSpec.Y(2)));
            if any(yxzMatch)
                dsyxzMatch=find(viewSpec.DS==viewsInMemory.DS(zMatch));
                if any(dsyxzMatch)
                    vIdx=zMatch(xzMatch(yxzMatch(dsyxzMatch(1))));
                else
                    vIdx=[];
                end
            else
                vIdx=[];
            end
        else
            vIdx=[];
        end
    else
        vIdx=[];
    end
end

%% Utility functions

function n=getNumericInput(prompt, title)
    n=inputdlg(prompt, title, 1, {'10'});
    if isempty(n)
        n=-1;
    else
        n=str2double(n);
        if isnan(n)
            n=getNumericInput(prompt, title);
        end
    end
end

%% Created view updater

function updateIfShowingThisZoomedView(obj, newlyCreatedGZV)
    zvm=obj.parent.mainDisplay.zoomedViewManager;
    mainDisplay=obj.parent.mainDisplay;

    if mainDisplay.currentZPlaneOriginalVoxels==newlyCreatedGZV.z
        zvm.updateView()
    end

end


text:
package me.denley.wearpreferenceactivity.sample;

import android.os.Bundle;

import preference.WearPreferenceActivity;

public class MainActivity extends WearPreferenceActivity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
    }

}


text:
require 'test_helper'

class ShellSessionTest < Test::Unit::TestCase
  include Travis::Worker

  Shell::Session.send :public, *Shell::Session.protected_instance_methods

  attr_reader :session

  def setup
    super
    Shell::Session.any_instance.stubs(:start_shell)
    Shell::Session.any_instance.stubs(:start_sandbox)
    @session = Shell::Session.new(Mock::VM.new, nil)
  end

  test 'echoize: echo the command before executing it (1)' do
    assert_equal "echo \\$\\ rake\nrake", session.echoize('rake')
  end

  test 'echoize: echo the command before executing it (2)' do
    assert_equal "echo \\$\\ rvm\\ use\\ 1.9.2\nrvm use 1.9.2\necho \\$\\ FOO\\=bar\\ rake\\ ci\nFOO=bar rake ci", session.echoize(['rvm use 1.9.2', 'FOO=bar rake ci'])
  end

  test 'echoize: removes a timetrap prefix from the echo command' do
    assert_equal "echo \\$\\ rake\ntimetrap -t 900 rake", session.echoize('timetrap -t 900 rake')
  end

  test 'timetrap wraps a command without env vars into a timetrap command without a timeout' do
    assert_equal 'timetrap rake', session.timetrap('rake')
  end

  test 'timetrap wraps a command without env vars into a timetrap command with a timeout' do
    assert_equal 'timetrap -t 900 rake', session.timetrap('rake', :timeout => 900)
  end

  test 'timetrap wraps a command with env vars into a timetrap command without a timeout' do
    assert_equal 'FOO=bar timetrap rake', session.timetrap('FOO=bar rake')
  end

  test 'timetrap wraps a command with env vars into a timetrap command with a timeout' do
    assert_equal 'FOO=bar timetrap -t 900 rake', session.timetrap('FOO=bar rake', :timeout => 900)
  end

  # This breaks scripts that contain SQL statements with a ;, e.g. 'mysql -e "create database foo;"'.
  # Would need a more sophisticated parser :/
  #
  # test 'timetrap wraps multiple commands with env vars into a timetrap command with a timeout' do
  #   assert_equal 'FOO=bar timetrap -t 900 rake ci:prepare; timetrap -t 900 rake', session.timetrap('FOO=bar rake ci:prepare; rake', :timeout => 900)
  # end

  test 'parse_cmd: given a command that contains env vars it returns an array containing env vars and the command' do
    assert_equal ['FOO=bar', 'rake'], session.parse_cmd('FOO=bar rake')
  end

  test 'parse_cmd: given a command that contains not env vars it returns an array containing nil and the command' do
    assert_equal [nil, 'rake'], session.parse_cmd('rake')
  end

  test 'vbox_snapshots returns the UUIDs of all snapshots in this box' do
    session.stubs(:vm_name).returns('travis-worker_1308835149')
    session.stubs(:`).returns(FIXTURES[:vboxmanage])

    expected = %w(
      fc54e7fe-7af2-496d-925a-9b29fa5d0234
      f15bc668-c09c-46c0-82b4-b621226c8bd3
      6c08e3b2-1c9c-4d9a-99eb-5abd2b2d0bdc
      1fbd6ddb-733b-4711-a1b3-05206f4396f0
      df764451-0b17-4492-974a-9f20077fc70d
      edbd462c-9fb9-40c7-aef9-8bf4978adf60
    )
    assert_equal expected, session.vbox_snapshots
  end
end


text:
<?php

namespace App\Http\Controllers;

use App\AspiranteAplicacion;
use Illuminate\Http\Request;
use App\Aspirante;
use App\Actas;

use App\Http\Requests;
use Excel;
use Carbon\Carbon;

class reportesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        return view('admin.reportes.index');
    }

    public function reporteGeneral(){

        Excel::create('ReporteAspirantes_'.Carbon::now(), function($excel) {

            // Set the title
            $excel->setTitle('Reporte de aprobados');

            // Chain the setters
            $excel->setCreator('Javier Carpio y Daniel Chavarría')
                ->setCompany('Plataforma de aspirantes, facultad de Arquitectura USAC');

            // Call them separately
            $excel->setDescription('Reporte auto generado con propósito de estudio sobre los datos de todas las aplicaciones realizadas.');

            $excel->sheet('First sheet', function($sheet) {
                $consulta = AspiranteAplicacion::
                join('aspirantes','aspirantes_aplicaciones.aspirante_id','=','aspirantes.NOV')
                    ->join('aplicaciones_salones_horarios','aplicaciones_salones_horarios.id','=','aspirantes_aplicaciones.aplicacion_salon_horario_id')
                    ->join('aplicaciones','aplicaciones_salones_horarios.aplicacion_id','=','aplicaciones.id')
                    ->leftJoin('actas','aspirantes_aplicaciones.acta_id','=','actas.id')
                    ->leftJoin('formularios','aspirantes.NOV','=','formularios.NOV')
                    ->get();
                //dd($consulta);

                //$sheet->fromArray($consulta);
                $data = [];
                foreach($consulta as $tupla){
                    $data[] = [
                        'Número de Orientación Vocacional' => $tupla->NOV,
                        'Nombres' => $tupla->nombre,
                        'Apellidos' => $tupla->apellido,
                        'RA' => $tupla->nota_RA,
                        'APE' => $tupla->nota_APE,
                        'RV' => $tupla->nota_RV,
                        'APN' => $tupla->nota_APN,
                        'RA evaluado Arquitectura' => $tupla->percentil_RA,
                        'APE evaluado Arquitectura' => $tupla->percentil_APE,
                        'RV evaluado Arquitectura' => $tupla->percentil_RV,
                        'APN evaluado Arquitectura' => $tupla->percentil_APN,
                        'RA evaluado Diseño' => $tupla->percentil_RA_disenio,
                        'APE evaluado Diseño' => $tupla->percentil_APE_disenio,
                        'RV evaluado Diseño' => $tupla->percentil_RV_disenio,
                        'APN evaluado Diseño' => $tupla->percentil_APN_disenio,
                        'Año de aplicacion' => $tupla->year,
                        'Número de aplicación' => $tupla->naplicacion,
                        'No. Acta' => $tupla->acta_id,
                        'Resultado' => $tupla->resultado,
                        'Correo' => $tupla->email,
                        'Estado del acta' => $tupla->estado,
                        'Residencia' => $tupla->residencia,
                        'Departamento' => $tupla->departamento,
                        'Municipio' => $tupla->municipio,
                        'Estado Civil' => $tupla->estado_civil,
                        'Estado Laboral' => $tupla->estado_laboral,
                        'Título' => $tupla->titulo,
                        'Teléfono' => $tupla->telefono,
                        'Celular' => $tupla->celular,
                        'Año del título' => $tupla->anio_titulo,
                        'Número de dependientes' => $tupla->dependientes,
                        'Centro educativo' => $tupla->centro_educativo,
                        'Dirección de centro educativo' => $tupla->direccion_centro_educativo,
                        'Sector del centro educativo' => $tupla->sector,
                        'Carrera de interés' => $tupla->carrera,
                        'Jornada de interés' => $tupla->jornada,
                        'Confirmó sus intereses' => (isset($tupla->confirmacion_intereses)?'Si':'No'),
                        'Caso especial' => (isset($tupla->irregular)?'Si':'No'),
                        'Fecha de inicio de asignaciones' => $tupla->fecha_inicio_asignaciones,
                        'Fecha de fin de asignaciones' => $tupla->fecha_fin_asignaciones,
                    ];

                }

                $sheet->fromArray($data);
            });

        })->store('xls', storage_path('reportes/general').'['.Carbon::now().']')->download('xls');

    }
}