text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Swift containers and value types</title>

<address align=right>
Howard Hinnant

2013-09-17
</address>

Swift containers and value types

Introduction

One of the best things about Cocoa is that it has very strong
conventions. These conventions allow Cocoa programmers to reason about
high-level designs without language support. In the case of containers,
the conventions strongly encourage Cocoa programmers to think of these
objects as values, despite the Objective-C language not having built-in
support for value types. This strong convention is best observed in the
advice we give to class designers. When exposing a container as a
property, programmers are strongly encouraged to use the immutable
version of the container, and to specify the "copy" attribute on the
property. Now, in Swift, we do have formal value types and we should
strongly consider formalizing the Cocoa conventions and make our
containers be value types. Now, in theory, formalizing this semantic for
containers could be disruptive to the day-to-day experience of Cocoa
programmers and therefore we have been doing research to prove that this
isn't the case. We will be reviewing the public API implications and the
internal design implications.

The public API implications are rather simple. If we model containers as
value types, we dramatically simplify the life of public API designers.
We no longer need to specify "copy" on each and every property, and we
also don't need to model immutability as a subclassing relationship (we
wouldn't want to either for reasons this paper won't go into).
Furthermore, computed properties don't need to defensive copy in either
their getter or setter. This is a huge win for safety, and for
performance, because we can defer these problems completely to the
compiler.

Now, let's consider the implications for class implementors. We have
been doing a lot of research to prove that value semantics would be a
net win, with improved syntax and compile-time error detection, and with
no noticeable performance downside.

Swift Parameter Passing Syntax

In Swift, function parameters can be passed by value or by reference.  The
simpler (default) syntax is by value:

func foo(_ c : Character, i : Int)  // define foo

// ...

foo(c, i)  // call foo

If one wants foo to pass by reference, both the author of foo
and the client of foo agree to use an alternate syntax, for each
individual parameter:

func foo(_ c : Character, i : [inout] Int)  // define foo

// ...

foo(c, &i)  // call foo

In the latter example above, the author of foo specifies
that the second parameter is to be passed by reference, instead of by
value. And if the caller of foo does not realize which
arguments of foo the author of foo intends to
modify (e.g. intends as out-parameters), then the Swift compiler
will catch this miscommunication and flag a compile-time error.

For a moment, imagine that Swift did not require modified syntax
at the call site:

func doWork() {
  // ...
  foo(c, i)
  bar(i)
  // ...
}

Now, when a human reads the code for doWork(), it is ambiguous
whether or not i is modified by foo, and thus difficult
to know what value of i is sent to bar.  One first has to
first look at the signature of foo to discover that it intends
to modify its last argument:

func foo(_ c : Character, i : [inout] Int)

Or alternatively just trust that the author of foo chose a
sufficiently descriptive name for the function so that the human reader
can tell in doWork() whether or not foo
modifies i without looking up the signature of
foo.

An even worse scenario would be for Swift to implicitly pass everything by
reference:

func foo(_ c : Character, i : Int)

Now in doWork:

func doWork() {
  // ...
  foo(c, i)
  bar(i)
  // ...
}

... we have to not only look at the signature of foo, we
have to examine the entire definition of foo to
discover if we are sending a modified i to bar
or not.  And if foo calls any other functions with
i each of those function definitions would also have
to be examined in order to answer this question.

Effectively, if Swift were designed to implicitly pass i by
reference in this example, the programmer must effectively and manually
perform a whole-program-analysis just to reason about the behavior of
do_Work.

Fortunately this is not how Swift was designed.  Instead the programmer
can analyze the behavior of doWork by looking only
at the definition of doWork.  Either i will be
explicitly passed by reference, or it will be passed by value, and thus
one immediately knows whether further uses of i are getting
a modified value or not:

func doWork() {
  // ...
  foo(c, i)
  bar(i)  // i is unchanged by foo
  // ...
}

func doOtherWork() {
  // ...
  foo(c, &i)
  bar(i)  // i is most likely modified by foo
  // ...
}

The Impact on Mutable Containers

The ability to locally reason about the behavior of doWork
in the previous section applies to mutable containers such as
Array and String just as much as it applies
to the Int parameter.

For performance reasons, we need to have mutable containers.  Otherwise
operations such as continuously appending become too expensive.  But we
need to be able to locally reason about code which uses these
containers.  If we make Array a reference type, then Swift
will compile this code:

func foo(_ v : Array, i : Int)  // define foo

func doWork() {
  // ...
  foo(v, i)
  bar(v)
  // ...
}

But the human reader of this code will have to perform a non-local
analysis to figure out what doWork is doing with the
Array (whether or not it is modified in or under
foo, and thus what value is used in bar). Or
rely on a high quality and strictly followed naming conventions such as
those used in Cocoa.  Now there is absolutely nothing wrong with high
quality, strictly followed naming conventions. But they aren't checked
by the compiler.  Having the compiler be able to confirm: yes, this
argument can be modified / no, that argument cannot be modified; is a
tremendous productivity booster.

If Array has value semantics, then we only need to glance at
doWork() to discover that both foo and bar
receive the same value in v (just like i).

Swift containers should have value semantics to enable programmers to
locally reason about their code using compiler-enforced syntax.

The Impact of Value Semantics Containers on Cocoa Programmers

I have spent the last couple of weeks looking at a lot of Apple's use of
NSMutableArray, NSMutableDictionary and
NSMutableSet.  I've looked at Foundation, AppKit, CoreData,
Mail, etc.  Everything I've looked at has shown that the programmers are
going out of their way to reduce and even eliminate sharing between
containers (avoid reference semantics).  I am seeing customer-written
DeepCopy methods.

-(NSMutableArray *)mutableDeepCopy;

I am seeing factory functions that return mutable containers which
share with nothing but a local within the factory function.

+ (NSMutableDictionary*) defaultWindowStateForNode: (const TFENode&) inTarget
{
    NSMutableDictionary* result = [NSMutableDictionary dictionary];

    // result is just filled, it shares with nothing...
    if (inTarget.IsVolume()
        && (inTarget.IsDiskImage() || inTarget.IsOnReadOnlyVolume())
        && inTarget != TFENodeFactory::GetHomeNode()
        && !inTarget.IsPlaceholderAliasTarget())
    {
        [result setBoolFE: NO forKey: kShowToolbarKey];
    }
    else
    {
        [result setBoolFE: YES forKey: kShowToolbarKey];
    }

    [result setBoolFE: [[self class] shouldShowStatusBar]
               forKey: UDefaults::StrKey(UDefaults::kShowStatusBar).PassNSString()];
    [result setBoolFE: [[self class] shouldShowTabView]
               forKey: UDefaults::StrKey(UDefaults::kShowTabView).PassNSString()];

    [result addEntriesFromDictionary: [TBrowserContainerController defaultContainerStateForNode: inTarget]];

    return result;
}

For the above factory function, it makes absolutely no difference whether value
semantics or reference semantics is used for NSMutableDictionary.

On occasion, I am seeing NSMutable* being passed into
functions just for the purpose of having in/out parameters, not creating
any sharing within the function.  For example:

- (void)_checkPathForArchive:(DVTFilePath *)archivePath andAddToArray:(NSMutableArray *)archives
{
   if ([self _couldBeArchivePath: archivePath]) {
       IDEArchive *archive = [IDEArchive archiveWithArchivePath:archivePath];
       if (archive != nil) {
           [archives addObject:archive];
       }
   }
}

And called like this:

[self _checkPathForArchive: archivePath andAddToArray: archives];

Such code is typically used as a private function and called from only
one or two places.  Note that here is an example that the human reader
is greatly depending on really good names to make the semantics clear:
andAddToArray. In Swift such code is easily translated to
something like:

_checkPathForArchiveAndAddToArray(archivePath, &archives)

Note that now the code not only has a great name, but the compiler is helping
the programmer ensure that both the client and function both agree that
archives is an in-out argument.  And just as importantly,
that archivePath is not to be modified within
_checkPathForArchiveAndAddToArray.  However if
archivePath is a mutable object with reference semantics, we lose
that ability to locally reason about this code, even in Swift.

The most worrisome code I see looks like this:

- (_FilteredListInfo *)_backgroundSortNewFilteredMessages:(NSMutableArray *)messages {
   MCAssertNotMainThread();
   // lots and lots of code here involving messages... and then near the bottom:

   res.filteredMessages = messages;  // share here!
   ...
   return res;
}

I.e. this is sharing a mutable container!  However if you then
go to the trouble to track down how this method is used, you find that
messages is only bound to a temporary, or to a local variable in the
calling function.  So, actually there is no permanent sharing after all.

But the programmer has to do non-local code analysis to figure out that
the above is actually safe.  Additionally there is nothing to stop this
function from being misused in the future.  This is just a ticking time
bomb in the code.

It would be far easier to reason about this code if messages was
passed, semantically, by-value.

func _backgroundSortNewFilteredMessages(_ messages : Array) -> _FilteredListInfo {
    // ...
    res.filteredMessages = messages;  // copy here!
    // ...
    return res
}

This need not imply a performance penalty with reference counting and
copy-on-write.  Especially when the argument is a temporary as is the
case in this example.

I'm seeing the same patterns, over and over, after surveying tens of
thousands of lines of code across multiple applications.  Cocoa programmers are:

Avoiding accidental sharing with manual deep copies where necessary.

Avoiding accidental sharing through the use of simple factory functions and
ordinary in/out parameters for functions that do not hold lasting
references internally.

In a few cases, being really careful to only pass temporaries or locals to
a function that does form a permanent reference.  And these functions can
not be reasoned about by only looking at the local function itself.

It appears to me that Cocoa programmers are already using value
semantics for their containers.  But they are getting no help at all
from their programming environment in doing so.  Instead they are
relying solely on good coding conventions and very descriptive method
names.  Cocoa programmers will not undergo a painful paradigm
shift by giving Swift containers value semantics.

Performance

The most concern I hear when talking about "large" objects having value
semantics is that of performance.  One understandably does not want to
be copying tons of data around. The plan for Swift containers is to
implement them with the reference-counted copy-on-write idiom.  In doing
so, the Swift programmer is freed from the tedious task of writing "deep
copy" functions, and yet the type behaves just like an Int.
 Additionally the type can be passed by reference, just like an
Int, in the relatively few places where pass-by-reference
is the desired behavior.

Generics

In making Swift containers behave just like Int, not only
is the overall Swift API simplified, but this is also a boon to generic
algorithms. For example one can confidently write a generic sorting
algorithm that works for sequences of Int, and for
sequences of Array<Int>. The generic code need not
concern itself with the question of whether or not the type has value
semantics or reference semantics.

Summary

Cocoa programmers already view and use containers as value types, even though
to achieve this they have to rely only on strong coding conventions.
They get no help from ObjC in this regard.

Swift can have both reference and by-value parameters, and the latter
has the simpler syntax.  This helps programmers to locally reason about
their code when using value types by making it clear that most arguments
passed to functions are not modified.  Function results tend to be
returned from the function.

In the relatively infrequent case that the programmer intends to modify
a function argument (i.e. as an out-parameter), if value semantics are
used, Swift makes the modification explicit in the client code through
use of '&' at the call site.  Thus the programmer can
more easily spot the few cases where this is desired.

Swift cannot provide such protection for types with reference semantics.

Performance is not compromised by formally adopting value semantics for
containers in Swift.

Swift containers should have value semantics to enable programmers to
locally reason about their code using compiler-enforced syntax.

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE CPP, DeriveDataTypeable #-}

-- |
-- Module      : Data.Text.Internal.Functions
-- Copyright   : 2010 Bryan O'Sullivan
--
-- License     : BSD-style
-- Maintainer  : bos@serpentine.com
-- Stability   : experimental
-- Portability : GHC
--
-- /Warning/: this is an internal module, and does not have a stable
-- API or name. Functions in this module may not check or enforce
-- preconditions expected by public modules. Use at your own risk!
--
-- Useful functions.

module Data.Text.Internal.Functions
    (
      intersperse
    ) where

-- | A lazier version of Data.List.intersperse.  The other version
-- causes space leaks!
intersperse :: a -> [a] -> [a]
intersperse _   []     = []
intersperse sep (x:xs) = x : go xs
  where
    go []     = []
    go (y:ys) = sep : y: go ys
{-# INLINE intersperse #-}


text:
package br.inpe.cap.evolution.processor;

import static br.inpe.cap.evolution.parser.XmlMavenParser.replaceLineFeedAndComma;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.repodriller.domain.Commit;
import org.repodriller.persistence.PersistenceMechanism;
import org.repodriller.scm.RepositoryFile;
import org.repodriller.scm.SCMRepository;

import br.inpe.cap.evolution.domain.MavenDependency;
import br.inpe.cap.evolution.domain.MavenProject;
import br.inpe.cap.evolution.maven.CommitLine;
import br.inpe.cap.evolution.maven.ConfigurableMavenEffectivePom;
import br.inpe.cap.evolution.maven.ConfigurableMavenEffectivePom.OS;
import br.inpe.cap.evolution.maven.UnparsableEffectivePomException;
import br.inpe.cap.evolution.parser.XmlMavenParser;

public class EffectivePomSynchronousCheckoutProcessor extends SynchronousCheckOutRepositoryProcessor {

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

	private final PersistenceMechanism writer;
	private final int totalCommits;
	private int currentHashPosition;
	private float percent;
	private final VersionEvolutionDetectorPostProcessor versionEvolutionDetector = new VersionEvolutionDetectorPostProcessor();
	private final ConfigurableMavenEffectivePom mavenEffectivePom;
	private final XmlMavenParser parser = new XmlMavenParser();
	private final Logger logger;

	public EffectivePomSynchronousCheckoutProcessor(final CheckoutObserver observer, final PersistenceMechanism writer, final int totalCommits, final Logger logger, final OS osType) {
		super(observer);
		this.writer = writer;
		this.totalCommits = totalCommits;
		this.logger = logger;
		this.versionEvolutionDetector.writeCsvHeader(writer);
		this.mavenEffectivePom = new ConfigurableMavenEffectivePom(osType);
	}

	@Override
	protected void processFile(final SCMRepository repo, final Commit commit, final RepositoryFile file) {
//		setupCurrentThread(file.getFullName(), repo.getLastDir());
		final MavenProject mavenProject = parser.readPOM(getEffectiveOrOriginalPom(file));
		for (MavenDependency dependency : mavenProject.getDependencies()) {
			versionEvolutionDetector.processLine(
				writer, this.obtainCsvLine(repo.getLastDir(), commit, this.currentHashPosition, this.totalCommits, this.percent, file.getFullName(), dependency));
		}
	}

	private void setupCurrentThread(final String fileFullName, final String repositoryName) {
		try {
			final Thread currentThread = Thread.currentThread();
			currentThread.setName(fileFullName.substring(fileFullName.indexOf(repositoryName)));
			currentThread.setPriority(Thread.MIN_PRIORITY);
//			Thread.sleep(TimeUnit.SECONDS.toMillis(10));
		} catch (Exception e) {}
	}

	private String getEffectiveOrOriginalPom(final RepositoryFile file) {
		String effectivePom = "";
		try {
			effectivePom = mavenEffectivePom.resolveEffectivePom(file.getFile());
		} catch (final UnparsableEffectivePomException e) {
			logger.error("Effective POM from file " + file.getFullName()
						+ " could not be extracted. Proceeding with original POM."
//						+ " See result:\n"
//						+ e.getMessage()
						);
			effectivePom = getOriginalPom(file, effectivePom);
		}
		return effectivePom;
	}

	private String getOriginalPom(final RepositoryFile file, String effectivePom) {
		try {
			effectivePom = FileUtils.readFileToString(file.getFile());
		} catch (final IOException ioe) {
			logger.error("Error reading POM from file " + file.getFullName());
		}
		return effectivePom;
	}

	public void setCurrentHashPosition(final int currentHashPosition) {
		this.currentHashPosition = currentHashPosition;
	}

	public void setPercent(final float percent) {
		this.percent = percent;
	}

	private String obtainCsvLine(final String repositoryName, final Commit commit, final int currentHashPosition, final int totalCommits, final float percent, final String fileName, final MavenDependency mavenDependency) {
		final StringBuilder sb = new StringBuilder();
		sb.append(commit.getHash());								sb.append(",");
		sb.append(DATE_FORMAT.format(commit.getDate().getTime()));	sb.append(",");
		sb.append(repositoryName);									sb.append(",");
		sb.append(fileName);										sb.append(",");
		sb.append(currentHashPosition);								sb.append(",");
		sb.append(totalCommits);									sb.append(",");
		sb.append(CommitLine.roundFiveDigits(percent));				sb.append(",");
		sb.append(mavenDependency.isDependencyManaged());			sb.append(",");
		sb.append(mavenDependency.getGroupId());					sb.append(",");
		sb.append(mavenDependency.getArtifactId());					sb.append(",");
		sb.append(mavenDependency.getVersion());					sb.append(",");
		sb.append(replaceLineFeedAndComma(commit.getMsg()));
		return sb.toString();
	}

}


text:
//
//  XAmsDelegate.h
//  xFace
//
//

#import <Foundation/Foundation.h>

@protocol XApplication;

@protocol XAmsDelegate <NSObject>

/**
	启动application
	@param app 待启动的application
 */
-(void) startApp:(id<XApplication>) app;

/**
	关闭application
	@param app 待关闭的application
 */
-(void) closeApp:(id<XApplication>) app;

@end


text:
package com.pearson.statsagg.utilities.json_utils;

import com.pearson.statsagg.utilities.math_utils.MathUtilities;
import java.math.BigDecimal;

/**
 * @author Jeffrey Schmidt
 */
public class JsonBigDecimal extends BigDecimal {

    public JsonBigDecimal(String val) {
        super(val);
    }

    public JsonBigDecimal(BigDecimal bigDecimal) {
        super(bigDecimal.toPlainString());
    }

    @Override
    public String toString() {
        return MathUtilities.getFastPlainStringWithNoTrailingZeros(this);
    }

}


text:
package org.pocketserver.api.event.entity.vehicle;

import org.pocketserver.api.entity.vehicle.Vehicle;

/**
 * This event is called when an entity gets mounted onto a vehicle.
 */
public class VehicleMountEvent extends VehicleEvent {

    public VehicleMountEvent(Vehicle vehicle) {
        super(vehicle);
    }
}


text:
<?php

namespace CachetHQ\Cachet\Presenters;

use CachetHQ\Cachet\Models\Incident;
use Jenssegers\Date\Date;
use McCool\LaravelAutoPresenter\BasePresenter;

class IncidentPresenter extends BasePresenter
{
    /**
     * Create a incident presenter instance.
     *
     * @param \CachetHQ\Cachet\Models\Incident $incident
     */
    public function __construct(Incident $incident)
    {
        $this->resource = $incident;
    }

    /**
     * Present diff for humans date time.
     *
     * @return string
     */
    public function created_at_diff()
    {
        return (new Date($this->resource->created_at))->diffForHumans();
    }

    /**
     * Present formated date time.
     *
     * @return string
     */
    public function created_at_formated()
    {
        return ucfirst((new Date($this->resource->created_at))->format('l j F Y H:i:s'));
    }

    /**
     * Present formated date time.
     *
     * @return string
     */
    public function created_at_iso()
    {
        return $this->resource->created_at->toISO8601String();
    }
}


text:
 0" class="form-group table table-hover table-striped" >

                Name
                SSN/Tax ID
                Acct #
                Phone Number(Phone Usage)
                Address
                City
                State
                Zip Code

                {{result.CustomerName}}
                {{!!result.SSN?result.SSN:result.TaxID}}
                {{result.AccountNumber}}

                    {{phone.PhoneNumber}}({{phone.PhoneUsage}})

                    {{result.AddressDetails.AddressLineList}}

                    {{result.AddressDetails.City}}

                    {{result.AddressDetails.State}}

                    {{result.AddressDetails.PostalCode}}
                    {{result.AddressDetails.ProvinceCode}}

 0 " class="form-group table table-hover table-striped" >

                Name
                Employee ID
                Email
                Phone
                Location
                Status

                {{result.EmployeeName}}
                {{result.EmployeeID}}
                {{result.Email}}
                {{result.PrimaryPhone}}
                {{result.Location}}
                {{result.Status}}

        No Match Found


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::Migration</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            Class
            ActiveRecord::Migration

                <

                    Object

/Users/tony/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb

/Users/tony/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/command_recorder.rb

/Users/tony/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration/join_table.rb

Active Record Migrations

Migrations can manage the evolution of a schema used by several physical
databases. It's a solution to the common problem of adding a field to
make a new feature work in your local database, but being unsure of how to
push that change to other developers and to the production server. With
migrations, you can describe the transformations in self-contained classes
that can be checked into version control systems and executed against
another database that might be one, two, or five versions behind.

Example of a simple migration:

class AddSsl < ActiveRecord::Migration
  def up
    add_column :accounts, :ssl_enabled, :boolean, default: true
  end

  def down
    remove_column :accounts, :ssl_enabled
  end
end

This migration will add a boolean flag to the accounts table and remove it
if you're backing out of the migration. It shows how all migrations
have two methods up and down that describes the
transformations required to implement or remove the migration. These
methods can consist of both the migration specific methods like
add_column and remove_column, but may also
contain regular Ruby code for generating data needed for the
transformations.

Example of a more complex migration that also needs to initialize data:

class AddSystemSettings < ActiveRecord::Migration
  def up
    create_table :system_settings do |t|
      t.string  :name
      t.string  :label
      t.text    :value
      t.string  :type
      t.integer :position
    end

    SystemSetting.create  name:  'notice',
                          label: 'Use notice?',
                          value: 1
  end

  def down
    drop_table :system_settings
  end
end

This migration first adds the system_settings table, then
creates the very first row in it using the Active Record model that relies
on the table. It also uses the more advanced create_table
syntax where you can specify a complete table schema in one block call.

Available transformations

create_table(name, options): Creates a table called
name and makes the table object available to a block that can
then add columns to it, following the same format as
add_column. See example above. The options hash is for
fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
table definition.

drop_table(name): Drops the table called name.

change_table(name, options): Allows to make column alterations
to the table called name. It makes the table object available
to a block that can then add/remove columns, indexes or foreign keys to it.

rename_table(old_name, new_name): Renames the table called
old_name to new_name.

add_column(table_name, column_name, type, options): Adds a new
column to the table called table_name named
column_name specified to be one of the following types:
:string, :text, :integer,
:float, :decimal, :datetime,
:timestamp, :time, :date,
:binary, :boolean. A default value can be
specified by passing an options hash like { default: 11
}. Other options include :limit and :null
(e.g. { limit: 50, null: false }) – see ActiveRecord::ConnectionAdapters::TableDefinition#column
for details.

rename_column(table_name, column_name, new_column_name):
Renames a column but keeps the type and content.

change_column(table_name, column_name, type, options):
Changes the column to a different type using the same parameters as
add_column.

remove_column(table_name, column_name, type, options): Removes
the column named column_name from the table called
table_name.

add_index(table_name, column_names, options): Adds a new index
with the name of the column. Other options include :name,
:unique (e.g. { name: 'users_name_index',
unique: true }) and :order (e.g. { order: { name:
:desc } }).

remove_index(table_name, column: column_name): Removes the
index specified by column_name.

remove_index(table_name, name: index_name): Removes the index
specified by index_name.

Irreversible transformations

Some transformations are destructive in a manner that cannot be reversed.
Migrations of that kind should raise an
ActiveRecord::IrreversibleMigration exception in their
down method.

Running migrations from within Rails

The Rails package has several tools to help create and apply migrations.

To generate a new migration, you can use

rails generate migration MyNewMigration

where MyNewMigration is the name of your migration. The generator will
create an empty migration file timestamp_my_new_migration.rb
in the db/migrate/ directory where timestamp is
the UTC formatted date and time that the migration was generated.

There is a special syntactic shortcut to generate migrations that add
fields to a table.

rails generate migration add_fieldname_to_tablename fieldname:string

This will generate the file
timestamp_add_fieldname_to_tablename, which will look like
this:

class AddFieldnameToTablename < ActiveRecord::Migration
  def change
    add_column :tablenames, :field, :string
  end
end

To run migrations against the currently configured database, use rake
db:migrate. This will update the database by running all of the
pending migrations, creating the schema_migrations table (see
"About the schema_migrations table" section below) if missing. It will also
invoke the db:schema:dump task, which will update your db/schema.rb file to
match the structure of your database.

To roll the database back to a previous migration version, use rake
db:migrate VERSION=X where X is the version to which
you wish to downgrade. Alternatively, you can also use the STEP option if
you wish to rollback last few migrations. rake db:migrate
STEP=2 will rollback the latest two migrations.

If any of the migrations throw an
ActiveRecord::IrreversibleMigration exception, that step will
fail and you'll have some manual work to do.

Database support

Migrations are currently supported in MySQL, PostgreSQL, SQLite, SQL
Server, and Oracle (all supported databases except DB2).

More examples

Not all migrations change the schema. Some just fix the data:

class RemoveEmptyTags < ActiveRecord::Migration
  def up
    Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
  end

  def down
    # not much we can do to restore deleted data
    raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
  end
end

Others remove columns when they migrate up instead of down:

class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
  def up
    remove_column :items, :incomplete_items_count
    remove_column :items, :completed_items_count
  end

  def down
    add_column :items, :incomplete_items_count
    add_column :items, :completed_items_count
  end
end

And sometimes you need to do something in SQL not abstracted directly by
migrations:

class MakeJoinUnique < ActiveRecord::Migration
  def up
    execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
  end

  def down
    execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
  end
end

Using a model after changing its table

Sometimes you'll want to add a column in a migration and populate it
immediately after. In that case, you'll need to make a call to
Base#reset_column_information in order to ensure that the
model has the latest column data from after the new column was added.
Example:

class AddPeopleSalary < ActiveRecord::Migration
  def up
    add_column :people, :salary, :integer
    Person.reset_column_information
    Person.all.each do |p|
      p.update_attribute :salary, SalaryCalculator.compute(p)
    end
  end
end

Controlling verbosity

By default, migrations will describe the actions they are taking, writing
them to the console as they happen, along with benchmarks describing how
long each step took.

You can quiet them down by setting ActiveRecord::Migration.verbose = false.

You can also insert your own messages and benchmarks by using the
say_with_time method:

def up
  ...
  say_with_time "Updating salaries..." do
    Person.all.each do |p|
      p.update_attribute :salary, SalaryCalculator.compute(p)
    end
  end
  ...
end

The phrase "Updating salaries…" would then be printed, along with the
benchmark for the block when the block completes.

About the schema_migrations table

Rails versions 2.0 and prior used to create a table called
schema_info when using migrations. This table contained the
version of the schema as of the last applied migration.

Starting with Rails 2.1, the schema_info table is
(automatically) replaced by the schema_migrations table, which
contains the version numbers of all the migrations applied.

As a result, it is now possible to add migration files that are numbered
lower than the current schema version: when migrating up, those
never-applied "interleaved" migrations will be automatically applied, and
when migrating down, never-applied "interleaved" migrations will be
skipped.

Timestamped Migrations

By default, Rails generates migrations that look like:

20080717013526_your_migration_name.rb

The prefix is a generation timestamp (in UTC).

If you'd prefer to use numeric prefixes, you can turn timestamped
migrations off by setting:

config.active_record.timestamped_migrations = false

In application.rb.

Reversible Migrations

Starting with Rails 3.1, you will be able to define reversible migrations.
Reversible migrations are migrations that know how to go down
for you. You simply supply the up logic, and the Migration system will figure out how to execute
the down commands for you.

To define a reversible migration, define the change method in
your migration like this:

class TenderloveMigration < ActiveRecord::Migration
  def change
    create_table(:horses) do |t|
      t.column :content, :text
      t.column :remind_at, :datetime
    end
  end
end

This migration will create the horses table for you on the way up, and
automatically figure out how to drop the table on the way down.

Some commands like remove_column cannot be reversed.  If you
care to define how to move up and down in these cases, you should define
the up and down methods as before.

If a command cannot be reversed, an
ActiveRecord::IrreversibleMigration exception will be raised
when the migration is moving down.

For a list of commands that are reversible, please see
ActiveRecord::Migration::CommandRecorder.

Transactional Migrations

If the database adapter supports DDL transactions, all migrations will
automatically be wrapped in a transaction. There are queries that you
can't execute inside a transaction though, and for these situations you
can turn the automatic transactions off.

class ChangeEnum < ActiveRecord::Migration
  disable_ddl_transaction!

  def up
    execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  end
end

Remember that you can still open your own transactions, even if you are in
a Migration with
self.disable_ddl_transaction!.

Namespace

          CLASS
          ActiveRecord::Migration::CheckPending

          CLASS
          ActiveRecord::Migration::CommandRecorder

Methods

A

                announce

C

                check_pending!,

                connection,

                copy

D

                disable_ddl_transaction!,

                down

E

                exec_migration

L

                load_schema_if_pending!

M

                method_missing,

                migrate,

                migrate

N

                new,

                next_migration_number

P

                proper_table_name

R

                reversible,

                revert,

                reverting?,

                run

S

                say,

                say_with_time,

                suppress_messages

T

                table_name_options

U

                up

W

                write

Attributes

              [RW]

            name

              [RW]

            version

Class Public methods

              check_pending!(connection = Base.connection)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 392
def check_pending!(connection = Base.connection)
  raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
end

              disable_ddl_transaction!()

            Link

Disable DDL transactions for this migration.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 425
def disable_ddl_transaction!
  @disable_ddl_transaction = true
end

              load_schema_if_pending!()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 396
def load_schema_if_pending!
  if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations?
    # Roundrip to Rake to allow plugins to hook into database initialization.
    FileUtils.cd Rails.root do
      current_config = Base.connection_config
      Base.clear_all_connections!
      system("bin/rake db:test:prepare")
      # Establish a new connection, the old database may be gone (db:test:prepare uses purge)
      Base.establish_connection(current_config)
    end
    check_pending!
  end
end

              migrate(direction)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 420
def migrate(direction)
  new.migrate direction
end

              new(name = self.class.name, version = nil)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 437
def initialize(name = self.class.name, version = nil)
  @name       = name
  @version    = version
  @connection = nil
end

Instance Public methods

              announce(message)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 619
def announce(message)
  text = "#{version} #{name}: #{message}"
  length = [0, 75 - text.length].max
  write "== %s %s" % [text, "=" * length]
end

              connection()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 645
def connection
  @connection || ActiveRecord::Base.connection
end

              copy(destination, sources, options = {})

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 666
def copy(destination, sources, options = {})
  copied = []

  FileUtils.mkdir_p(destination) unless File.exist?(destination)

  destination_migrations = ActiveRecord::Migrator.migrations(destination)
  last = destination_migrations.last
  sources.each do |scope, path|
    source_migrations = ActiveRecord::Migrator.migrations(path)

    source_migrations.each do |migration|
      source = File.binread(migration.filename)
      inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
      if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
        # If we have a magic comment in the original migration,
        # insert our comment after the first newline(end of the magic comment line)
        # so the magic keep working.
        # Note that magic comments must be at the first line(except sh-bang).
        source[/\n/] = "\n#{inserted_comment}"
      else
        source = "#{inserted_comment}#{source}"
      end

      if duplicate = destination_migrations.detect { |m| m.name == migration.name }
        if options[:on_skip] && duplicate.scope != scope.to_s
          options[:on_skip].call(scope, migration)
        end
        next
      end

      migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
      new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
      old_path, migration.filename = migration.filename, new_path
      last = migration

      File.binwrite(migration.filename, source)
      copied << migration
      options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
      destination_migrations << migration
    end
  end

  copied
end

              down()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 572
def down
  self.class.delegate = self
  return unless self.class.respond_to?(:down)
  self.class.down
end

              exec_migration(conn, direction)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 600
def exec_migration(conn, direction)
  @connection = conn
  if respond_to?(:change)
    if direction == :down
      revert { change }
    else
      change
    end
  else
    send(direction)
  end
ensure
  @connection = nil
end

              method_missing(method, *arguments, &block)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 649
def method_missing(method, *arguments, &block)
  arg_list = arguments.map{ |a| a.inspect } * ', '

  say_with_time "#{method}(#{arg_list})" do
    unless @connection.respond_to? :revert
      unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method)
        arguments[0] = proper_table_name(arguments.first, table_name_options)
        if [:rename_table, :add_foreign_key].include?(method)
          arguments[1] = proper_table_name(arguments.second, table_name_options)
        end
      end
    end
    return super unless connection.respond_to?(method)
    connection.send(method, *arguments, &block)
  end
end

              migrate(direction)

            Link

Execute this migration in the named direction

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 579
def migrate(direction)
  return unless respond_to?(direction)

  case direction
  when :up   then announce "migrating"
  when :down then announce "reverting"
  end

  time   = nil
  ActiveRecord::Base.connection_pool.with_connection do |conn|
    time = Benchmark.measure do
      exec_migration(conn, direction)
    end
  end

  case direction
  when :up   then announce "migrated (%.4fs)" % time.real; write
  when :down then announce "reverted (%.4fs)" % time.real; write
  end
end

              next_migration_number(number)

            Link

Determines the version number of the next migration.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 723
def next_migration_number(number)
  if ActiveRecord::Base.timestamped_migrations
    [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
  else
    SchemaMigration.normalize_migration_number(number)
  end
end

              proper_table_name(name, options = {})

            Link

Finds the correct table name given an Active Record object. Uses the Active
Record object's own table_name, or pre/suffix from the options passed
in.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 714
def proper_table_name(name, options = {})
  if name.respond_to? :table_name
    name.table_name
  else
    "#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}"
  end
end

              reversible()

            Link

Used to specify an operation that can be run in one direction or another.
Call the methods up and down of the yielded
object to run a block only in one given direction. The whole block will be
called in the right order within the migration.

In the following example, the looping on users will always be done when the
three columns 'first_name', 'last_name' and
'full_name' exist, even when migrating down:

class SplitNameMigration < ActiveRecord::Migration
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string

    reversible do |dir|
      User.reset_column_information
      User.all.each do |u|
        dir.up   { u.first_name, u.last_name = u.full_name.split(' ') }
        dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
        u.save
      end
    end

    revert { add_column :users, :full_name, :string }
  end
end

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 543
def reversible
  helper = ReversibleBlockHelper.new(reverting?)
  execute_block{ yield helper }
end

              revert(*migration_classes)

            Link

Reverses the migration commands for the given block and the given
migrations.

The following migration will remove the table 'horses' and create
the table 'apples' on the way up, and the reverse on the way down.

class FixTLMigration < ActiveRecord::Migration
  def change
    revert do
      create_table(:horses) do |t|
        t.text :content
        t.datetime :remind_at
      end
    end
    create_table(:apples) do |t|
      t.string :variety
    end
  end
end

Or equivalently, if TenderloveMigration is defined as in the
documentation for Migration:

require_relative '2012121212_tenderlove_migration'

class FixupTLMigration < ActiveRecord::Migration
  def change
    revert TenderloveMigration

    create_table(:apples) do |t|
      t.string :variety
    end
  end
end

This command can be nested.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 484
def revert(*migration_classes)
  run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
  if block_given?
    if @connection.respond_to? :revert
      @connection.revert { yield }
    else
      recorder = CommandRecorder.new(@connection)
      @connection = recorder
      suppress_messages do
        @connection.revert { yield }
      end
      @connection = recorder.delegate
      recorder.commands.each do |cmd, args, block|
        send(cmd, *args, &block)
      end
    end
  end
end

              reverting?()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 503
def reverting?
  @connection.respond_to?(:reverting) && @connection.reverting
end

              run(*migration_classes)

            Link

Runs the given migration classes. Last argument can specify options:

:direction (default is :up)

:revert (default is false)

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 552
def run(*migration_classes)
  opts = migration_classes.extract_options!
  dir = opts[:direction] || :up
  dir = (dir == :down ? :up : :down) if opts[:revert]
  if reverting?
    # If in revert and going :up, say, we want to execute :down without reverting, so
    revert { run(*migration_classes, direction: dir, revert: true) }
  else
    migration_classes.each do |migration_class|
      migration_class.new.exec_migration(@connection, dir)
    end
  end
end

              say(message, subitem=false)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 625
def say(message, subitem=false)
  write "#{subitem ? "   ->" : "--"} #{message}"
end

              say_with_time(message)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 629
def say_with_time(message)
  say(message)
  result = nil
  time = Benchmark.measure { result = yield }
  say "%.4fs" % time.real, :subitem
  say("#{result} rows", :subitem) if result.is_a?(Integer)
  result
end

              suppress_messages()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 638
def suppress_messages
  save, self.verbose = verbose, false
  yield
ensure
  self.verbose = save
end

              table_name_options(config = ActiveRecord::Base)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 731
def table_name_options(config = ActiveRecord::Base)
  {
    table_name_prefix: config.table_name_prefix,
    table_name_suffix: config.table_name_suffix
  }
end

              up()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 566
def up
  self.class.delegate = self
  return unless self.class.respond_to?(:up)
  self.class.up
end

              write(text="")

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/migration.rb, line 615
def write(text="")
  puts(text) if verbose
end


text:
require 'spec_helper'

describe SlactionMailer::DeliveryMethod do
  before do

    Mail.defaults do
      delivery_method SlactionMailer::DeliveryMethod,
        :webhook => "https://hooks.slack.com/services/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",
        :channel => "#bottesting",
        :username => "SlactionMailer"
    end
  end

  it 'raises an error if initalized wrong' do
    expect { SlactionMailer::DeliveryMethod.new }.to raise_exception(SlactionMailer::DeliveryMethod::InvalidOption)
  end

  context 'integration' do
    it 'sends a message successfully' do
      pending "Need to spec out an actionmailer message"
    end

    it 'sends a message with a template' do
      Mail.defaults do
        delivery_method SlactionMailer::DeliveryMethod,
          :webhook => "https://hooks.slack.com/services/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",
          :channel => "#bottesting",
          :username => "SlactionMailer",
          :template => File.read('spec/examples/template.text.erb')
      end
      expect {
        Mail.deliver do
          from "Feaux feaux@example.com"
          to "Bar bar@example.com"
          subject "Hello World!"
          body "I'm a message body!"
        end
      }.not_to raise_error
    end
  end
end


text:
using System;

namespace Avalonia.Platform
{
    /// <summary>
    /// Hint for Window Chrome when ClientArea is Extended.
    /// </summary>
    [Flags]
    public enum ExtendClientAreaChromeHints
    {
        /// <summary>
        /// The will be no chrome at all.
        /// </summary>
        NoChrome,

        /// <summary>
        /// The default for the platform.
        /// </summary>
        Default = SystemChrome,

        /// <summary>
        /// Use SystemChrome
        /// </summary>
        SystemChrome = 0x01,

        /// <summary>
        /// Use system chrome where possible. OSX system chrome is used, Windows managed chrome is used.
        /// This is because Windows Chrome can not be shown ontop of user content.
        /// </summary>
        PreferSystemChrome = 0x02,

        /// <summary>
        /// On OSX the titlebar is the thicker toolbar kind. Causes traffic lights to be positioned
        /// slightly lower than normal.
        /// </summary>
        OSXThickTitleBar = 0x08,
    }
}


text:
package controller;

import util.Teclado;

public class Ex10 {
	public static void main(String[] args){
		String nomes [] = new String [5];
		String telefones [] = new String [5];
		String enderecos [] = new String [5];
		int op;
		for (int i = 0; i < 5; i++){
		nomes[i] = Teclado.lerTexto("Digite um nome");
		telefones[i] = Teclado.lerTexto("Digite um telefone");
		enderecos[i] = Teclado.lerTexto("Digite um endereço");
		}
		op = Teclado.lerInt("Digite a posição dos dados no vetor");
		if((op >= 0) && (op < 5)){
			System.out.println("Nome: "+nomes[op] + "\n" + "Telefone: "+telefones[op]+"\n" + " Endereço:" + enderecos[op]);
		}else{
			System.out.println("Posição inválida");
		}
	}

}


text:
from . import ExplorationTechnique

from ..sim_options import EFFICIENT_STATE_MERGING

class Veritesting(ExplorationTechnique):
    """
    Enable veritesting. This technique, described in a paper[1] from CMU, attempts to address the problem of state
    explosions in loops by performing smart merging.

    [1] https://users.ece.cmu.edu/~aavgerin/papers/veritesting-icse-2014.pdf
    """
    def __init__(self, **options):
        super(Veritesting, self).__init__()
        self.options = options

    def step_state(self, simgr, state, successor_func=None, **kwargs):

        if EFFICIENT_STATE_MERGING not in state.options:
            state.options.add(EFFICIENT_STATE_MERGING)

        vt = self.project.analyses.Veritesting(state, **self.options)
        if vt.result and vt.final_manager:
            simgr2 = vt.final_manager
            simgr2.stash(from_stash='deviated', to_stash='active')
            simgr2.stash(from_stash='successful', to_stash='active')

            return {
                    'active': simgr2.active,
                    'unconstrained': simgr2.stashes.get('unconstrained', []),
                    'unsat': simgr2.stashes.get('unsat', []),
                    'pruned': simgr2.stashes.get('pruned', []),
                    'errored': simgr2.errored,
                    }

        return simgr.step_state(state, successor_func=successor_func, **kwargs)


text:
<?php declare(strict_types=1);

namespace Nugato\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20181112103514 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE nucms_taxon ADD image INT DEFAULT NULL');
        $this->addSql('ALTER TABLE nucms_taxon ADD CONSTRAINT FK_EA58EE27C53D045F FOREIGN KEY (image) REFERENCES nucms_file (id) ON DELETE CASCADE');
        $this->addSql('CREATE INDEX IDX_EA58EE27C53D045F ON nucms_taxon (image)');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE nucms_taxon DROP FOREIGN KEY FK_EA58EE27C53D045F');
        $this->addSql('DROP INDEX IDX_EA58EE27C53D045F ON nucms_taxon');
        $this->addSql('ALTER TABLE nucms_taxon DROP image');
    }
}


text:
//------------------------------------------------------------------------------
// Contributor(s): RJH 08/07/2009, mb 10/20/2010.
//------------------------------------------------------------------------------

namespace Nop.Plugin.Shipping.USPS.Domain
{
    /// <summary>
    /// Class for USPS V3 XML rate class -holds services offered by USPS
    /// </summary>
    public class USPSServices
    {
        /// <summary>
        /// V3 USPS Domestic Services
        /// </summary>
        private string[] _domesticServices = {
                                                "NONE (disable all domestic services)",
                                                "First-Class",
                                                "Priority Mail Express Sunday/Holiday Guarantee",
                                                "Priority Mail Express Flat-Rate Envelope Sunday/Holiday Guarantee",
                                                "Priority Mail Express Hold For Pickup",
                                                "Priority Mail Express Flat Rate Envelope Hold For Pickup",
                                                "Priority Mail Express",
                                                "Priority Mail Express Flat Rate Envelope",
                                                "Priority Mail",
                                                "Priority Mail Flat Rate Envelope",
                                                "Priority Mail Small Flat Rate Box",
                                                "Priority Mail Medium Flat Rate Box",
                                                "Priority Mail Large Flat Rate Box",
                                                "Standard Post",
                                                "Bound Printed Matter",
                                                "Media Mail",
                                                "Library Mail"
                                                };

        /// <summary>
        /// V3 USPS International services
        /// </summary>
        private string[] _internationalServices = {
                                                    "NONE (disable all international services)",
                                                    "Global Express Guaranteed (GXG)",
                                                    "Global Express Guaranteed Non-Document Rectangular",
                                                    "Global Express Guaranteed Non-Document Non-Rectangular",
                                                    "USPS GXG Envelopes",
                                                    "Priority Mail Express International Flat Rate Envelope",
                                                    "Priority Mail International",
                                                    "Priority Mail International Large Flat Rate Box",
                                                    "Priority Mail International Medium Flat Rate Box",
                                                    "Priority Mail International Small Flat Rate Box",
                                                    "First-Class Mail International Large Envelope",
                                                    "Priority Mail Express International",
                                                    "Priority Mail International Flat Rate Envelope",
                                                    "First-Class Package International Service"
                                                    };

        #region Properties

        /// <summary>
        /// USPS Domestic services string names
        /// </summary>
        public string[] DomesticServices
        {
            get { return _domesticServices; }
        }

        /// <summary>
        /// USPS International services string names
        /// </summary>
        public string[] InternationalServices
        {
            get { return _internationalServices; }
        }

        #endregion

        #region Utilities

        /// <summary>
        /// Gets the Service ID for a domestic service
        /// </summary>
        /// <param name="service">service name</param>
        /// <returns>service id or empty string if not found</returns>
        public static string GetServiceIdDomestic(string service)
        {
            string serviceId = string.Empty;
            switch (service)
            {
                case "NONE (disable all domestic services)":
                    serviceId = "NONE";
                    break;
                case "First-Class":
                    serviceId = "0";
                    break;
                case "Priority Mail Express Sunday/Holiday Guarantee":
                    serviceId = "23";
                    break;
                case "Priority Mail Express Flat-Rate Envelope Sunday/Holiday Guarantee":
                    serviceId = "25";
                    break;
                case "Priority Mail Express Hold For Pickup":
                    serviceId = "2";
                    break;
                case "Priority Mail Express Flat Rate Envelope Hold For Pickup":
                    serviceId = "27";
                    break;
                case "Priority Mail Express":
                    serviceId = "3";
                    break;
                case "Priority Mail Express Flat Rate Envelope":
                    serviceId = "13";
                    break;
                case "Priority Mail":
                    serviceId = "1";
                    break;
                case "Priority Mail Flat Rate Envelope":
                    serviceId = "16";
                    break;
                case "Priority Mail Small Flat Rate Box":
                    serviceId = "28";
                    break;
                case "Priority Mail Medium Flat Rate Box":
                    serviceId = "17";
                    break;
                case "Priority Mail Large Flat Rate Box":
                    serviceId = "22";
                    break;
                case "Standard Post":
                    serviceId = "4";
                    break;
                case "Bound Printed Matter":
                    serviceId = "5";
                    break;
                case "Media Mail":
                    serviceId = "6";
                    break;
                case "Library Mail":
                    serviceId = "7";
                    break;
                default:
                    break;
            }
            return serviceId;
        }

        /// <summary>
        /// Gets the Service ID for an International service
        /// </summary>
        /// <param name="service">service name</param>
        /// <returns>service id or emtpy string</returns>
        public static string GetServiceIdInternational(string service)
        {
            string serviceId = string.Empty;
            switch (service)
            {
                case "NONE (disable all international services)":
                    serviceId = "NONE";
                    break;
                case "Global Express Guaranteed (GXG)":
                    serviceId = "4";
                    break;
                case "Global Express Guaranteed Non-Document Rectangular":
                    serviceId = "6";
                    break;
                case "Global Express Guaranteed Non-Document Non-Rectangular":
                    serviceId = "7";
                    break;
                case "USPS GXG Envelopes":
                    serviceId = "12";
                    break;
                case "Priority Mail Express International Flat Rate Envelope":
                    serviceId = "10";
                    break;
                case "Priority Mail International":
                    serviceId = "2";
                    break;
                case "Priority Mail International Large Flat Rate Box":
                    serviceId = "11";
                    break;
                case "Priority Mail International Medium Flat Rate Box":
                    serviceId = "9";
                    break;
                case "Priority Mail International Small Flat Rate Box":
                    serviceId = "16";
                    break;
                case "First-Class Mail International Large Envelope":
                    serviceId = "14";
                    break;
                case "Priority Mail Express International":
                    serviceId = "1";
                    break;
                case "Priority Mail International Flat Rate Envelope":
                    serviceId = "8";
                    break;
                case "First-Class Package International Service":
                    serviceId = "15";
                    break;
                default:
                    break;
            }
            return serviceId;
        }

        #endregion
    }
}


text:
import { CellCanvasRendererProps, HeatMapDatum } from './types'

export const renderRect = <Datum extends HeatMapDatum>(
    ctx: CanvasRenderingContext2D,
    {
        cell: { x, y, width, height, color, borderColor, opacity, labelTextColor, label },
        borderWidth,
        enableLabels,
        theme,
    }: CellCanvasRendererProps<Datum>
) => {
    ctx.save()
    ctx.globalAlpha = opacity

    ctx.fillStyle = color
    if (borderWidth > 0) {
        ctx.strokeStyle = borderColor
        ctx.lineWidth = borderWidth
    }

    ctx.fillRect(x - width / 2, y - height / 2, width, height)
    if (borderWidth > 0) {
        ctx.strokeRect(x - width / 2, y - height / 2, width, height)
    }

    if (enableLabels) {
        ctx.fillStyle = labelTextColor
        ctx.font = `${theme.labels.text.fontWeight ? `${theme.labels.text.fontWeight} ` : ''}${
            theme.labels.text.fontSize
        }px ${theme.labels.text.fontFamily}`
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(label, x, y)
    }

    ctx.restore()
}

export const renderCircle = <Datum extends HeatMapDatum>(
    ctx: CanvasRenderingContext2D,
    {
        cell: { x, y, width, height, color, borderColor, opacity, labelTextColor, label },
        borderWidth,
        enableLabels,
        theme,
    }: CellCanvasRendererProps<Datum>
) => {
    ctx.save()
    ctx.globalAlpha = opacity

    const radius = Math.min(width, height) / 2

    ctx.fillStyle = color
    if (borderWidth > 0) {
        ctx.strokeStyle = borderColor
        ctx.lineWidth = borderWidth
    }

    ctx.beginPath()
    ctx.arc(x, y, radius, 0, 2 * Math.PI)

    ctx.fill()
    if (borderWidth > 0) {
        ctx.stroke()
    }

    if (enableLabels) {
        ctx.fillStyle = labelTextColor
        ctx.font = `${theme.labels.text.fontWeight ? `${theme.labels.text.fontWeight} ` : ''}${
            theme.labels.text.fontSize
        }px ${theme.labels.text.fontFamily}`
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(label, x, y)
    }

    ctx.restore()
}


text:
/**
 * @file px4same70xplained_led.c
 *
 * PX4_SAME70XPLAINED_V1 LED backend.
 */

#include <px4_config.h>

#include <stdbool.h>

#include "sam_gpio.h"
#include <nuttx/board.h>
#include <arch/board/board.h>
#include "board_config.h"

/*
 * Ideally we'd be able to get these from up_internal.h,
 * but since we want to be able to disable the NuttX use
 * of leds for system indication at will and there is no
 * separate switch, we need to build independent of the
 * CONFIG_ARCH_LEDS configuration switch.
 */
__BEGIN_DECLS
extern void led_init(void);
extern void led_on(int led);
extern void led_off(int led);
extern void led_toggle(int led);
__END_DECLS

__EXPORT void led_init()
{
	/* Configure LED1 GPIO for output */

	sam_configgpio(GPIO_LED1);
}

__EXPORT void led_on(int led)
{
	if (led == 1) {
		/* Pull down to switch on */
		sam_gpiowrite(GPIO_LED1, false);
	}
}

__EXPORT void led_off(int led)
{
	if (led == 1) {
		/* Pull up to switch off */
		sam_gpiowrite(GPIO_LED1, true);
	}
}

__EXPORT void led_toggle(int led)
{
	if (led == 1) {
		if (sam_gpioread(GPIO_LED1)) {
			sam_gpiowrite(GPIO_LED1, false);

		} else {
			sam_gpiowrite(GPIO_LED1, true);
		}
	}
}

#if defined(CONFIG_ARCH_LEDS)
/****************************************************************************
 * Name: board_autoled_initialize
 ****************************************************************************/

void board_autoled_initialize(void)
{
	led_init();
}

/****************************************************************************
 * Name: board_autoled_on
 ****************************************************************************/

void board_autoled_on(int led)
{
	if (led == 1 || led == 3) {
		sam_gpiowrite(GPIO_LED1, false); /* Low illuminates */
	}
}

/****************************************************************************
 * Name: board_autoled_off
 ****************************************************************************/

void board_autoled_off(int led)
{
	if (led == 3) {
		sam_gpiowrite(GPIO_LED1, true);  /* High extinguishes */
	}
}
#endif


text:
namespace blink {

// Tests that hash tables of Member<ScopedCSSName> hash the names
// themselves, not the wrapper pointers.

TEST(ScopedCSSNameTest, HashInsertDuplicate) {
  ScopedCSSName* foo = MakeGarbageCollected<ScopedCSSName>("foo", nullptr);

  HeapHashSet<Member<ScopedCSSName>> hash_set;
  EXPECT_TRUE(hash_set.insert(foo).is_new_entry);
  EXPECT_FALSE(hash_set.insert(foo).is_new_entry);
  EXPECT_NE(hash_set.find(foo), hash_set.end());
  EXPECT_EQ(*hash_set.find(foo), foo);
}

TEST(ScopedCSSNameTest, HashDifferentNames) {
  ScopedCSSName* foo = MakeGarbageCollected<ScopedCSSName>("foo", nullptr);
  ScopedCSSName* bar = MakeGarbageCollected<ScopedCSSName>("bar", nullptr);
  EXPECT_NE(foo->GetHash(), bar->GetHash());

  HeapHashSet<Member<ScopedCSSName>> hash_set;
  EXPECT_TRUE(hash_set.insert(foo).is_new_entry);
  EXPECT_TRUE(hash_set.insert(bar).is_new_entry);
}

TEST(ScopedCSSNameTest, HashEqualNames) {
  ScopedCSSName* foo1 = MakeGarbageCollected<ScopedCSSName>("foo", nullptr);
  ScopedCSSName* foo2 = MakeGarbageCollected<ScopedCSSName>("foo", nullptr);
  ScopedCSSName* foo3 = MakeGarbageCollected<ScopedCSSName>("foo", nullptr);
  EXPECT_EQ(foo1->GetHash(), foo2->GetHash());
  EXPECT_EQ(foo2->GetHash(), foo3->GetHash());

  HeapHashSet<Member<ScopedCSSName>> hash_set;
  EXPECT_TRUE(hash_set.insert(foo1).is_new_entry);
  EXPECT_FALSE(hash_set.insert(foo2).is_new_entry);
  EXPECT_FALSE(hash_set.insert(foo3).is_new_entry);
}

}  // namespace blink


text:
using System;

namespace Nitkin.Ankh.Redmine.Extension
{
    static class AppConstants
	{
		public const string PackageGUID = GuidList.guidAnkhSampleExtensionPkgString;
		public const string ServiceGUID = GuidList.guidAnkhSampleExtensionConnectorString;

        public const string CompanyName = "Nitkin";
        public const string PackageName = "AnkhRedminePlugin";
        public const string ConnectorName = "Nitkin Ankh Redmine connector";
    };
}


text:
BEGIN;

ALTER TABLE org_user_associations DROP CONSTRAINT org_user_associations_org_id_key;
ALTER TABLE org_user_associations DROP CONSTRAINT org_user_associations_user_id_key;
CREATE INDEX org_user_associations_index_user_id_key ON org_user_associations(user_id);

COMMIT;


text:
/**
 * @fileOverview The [Mathematical Formulas](http://ckeditor.com/addon/mathjax) plugin that allows you to create and modify mathematical equations written in TeX directly in CKEditor..
 */

'use strict';

( function() {
	CKEDITOR.plugins.add( 'mathjax', {
		lang: 'af,ar,az,bg,ca,cs,cy,da,de,de-ch,el,en,en-gb,eo,es,es-mx,eu,fa,fi,fr,gl,he,hr,hu,id,it,ja,km,ko,ku,lt,nb,nl,no,oc,pl,pt,pt-br,ro,ru,sk,sl,sq,sv,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
		requires: 'widget,dialog',
		icons: 'mathjax',
		hidpi: true, // %REMOVE_LINE_CORE%

		init: function( editor ) {
			var cls = editor.config.mathJaxClass || 'math-tex';

			if ( !editor.config.mathJaxLib ) {
				CKEDITOR.error( 'mathjax-no-config' );
			}

			editor.widgets.add( 'mathjax', {
				inline: true,
				dialog: 'mathjax',
				button: editor.lang.mathjax.button,
				mask: true,
				allowedContent: 'span(!' + cls + ')',
				// Allow style classes only on spans having mathjax class.
				styleToAllowedContentRules: function( style ) {
					var classes = style.getClassesArray();
					if ( !classes )
						return null;
					classes.push( '!' + cls );

					return 'span(' + classes.join( ',' ) + ')';
				},
				pathName: editor.lang.mathjax.pathName,

				template: '',

				parts: {
					span: 'span'
				},

				defaults: {
					math: '\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)'
				},

				init: function() {
					var iframe = this.parts.span.getChild( 0 );

					// Check if span contains iframe and create it otherwise.
					if ( !iframe || iframe.type != CKEDITOR.NODE_ELEMENT || !iframe.is( 'iframe' ) ) {
						iframe = new CKEDITOR.dom.element( 'iframe' );
						iframe.setAttributes( {
							style: 'border:0;width:0;height:0',
							scrolling: 'no',
							frameborder: 0,
							allowTransparency: true,
							src: CKEDITOR.plugins.mathjax.fixSrc
						} );
						this.parts.span.append( iframe );
					}

					// Wait for ready because on some browsers iFrame will not
					// have document element until it is put into document.
					// This is a problem when you crate widget using dialog.
					this.once( 'ready', function() {
						// Src attribute must be recreated to fix custom domain error after undo
						// (see iFrame.removeAttribute( 'src' ) in frameWrapper.load).
						if ( CKEDITOR.env.ie )
							iframe.setAttribute( 'src', CKEDITOR.plugins.mathjax.fixSrc );

						this.frameWrapper = new CKEDITOR.plugins.mathjax.frameWrapper( iframe, editor );
						this.frameWrapper.setValue( this.data.math );
					} );
				},

				data: function() {
					if ( this.frameWrapper )
						this.frameWrapper.setValue( this.data.math );
				},

				upcast: function( el, data ) {
					if ( !( el.name == 'span' && el.hasClass( cls ) ) )
						return;

					if ( el.children.length > 1 || el.children[ 0 ].type != CKEDITOR.NODE_TEXT )
						return;

					data.math = CKEDITOR.tools.htmlDecode( el.children[ 0 ].value );

					// Add style display:inline-block to have proper height of widget wrapper and mask.
					var attrs = el.attributes;

					if ( attrs.style )
						attrs.style += ';display:inline-block';
					else
						attrs.style = 'display:inline-block';

					// Add attribute to prevent deleting empty span in data processing.
					attrs[ 'data-cke-survive' ] = 1;

					el.children[ 0 ].remove();

					return el;
				},

				downcast: function( el ) {
					el.children[ 0 ].replaceWith( new CKEDITOR.htmlParser.text( CKEDITOR.tools.htmlEncode( this.data.math ) ) );

					// Remove style display:inline-block.
					var attrs = el.attributes;
					attrs.style = attrs.style.replace( /display:\s?inline-block;?\s?/, '' );
					if ( attrs.style === '' )
						delete attrs.style;

					return el;
				}
			} );

			// Add dialog.
			CKEDITOR.dialog.add( 'mathjax', this.path + 'dialogs/mathjax.js' );

			// Add MathJax script to page preview.
			editor.on( 'contentPreview', function( evt ) {
				evt.data.dataValue = evt.data.dataValue.replace(
					/<\/head>/,
					'' +

								// Load MathJax lib.
								'' +
							'' +
							'' +
								'' +

								// Render everything here and after that copy it to the preview.
								'' +
							'' +
							'' );
			}

			// Run MathJax parsing Tex.
			function update() {
				isRunning = true;

				value = newValue;

				editor.fire( 'lockSnapshot' );

				buffer.setHtml( value );

				// Set loading indicator.
				preview.setHtml( '' );

				iFrame.setStyles( {
					height: '16px',
					width: '16px',
					display: 'inline',
					'vertical-align': 'middle'
				} );

				editor.fire( 'unlockSnapshot' );

				// Run MathJax.
				doc.getWindow().$.update( value );
			}

			return {
				/**
				 * Sets the TeX value to be displayed in the `iframe` element inside
				 * the editor. This function will activate the MathJax
				 * library which interprets TeX expressions and converts them into
				 * their representation that is displayed in the editor.
				 *
				 * @param {String} value TeX string.
				 */
				setValue: function( value ) {
					newValue = CKEDITOR.tools.htmlEncode( value );

					if ( isInit && !isRunning )
						update();
				}
			};
		};
	} else {
		// In IE8 MathJax does not work stable so instead of using standard
		// frame wrapper it is replaced by placeholder to show pure TeX in iframe.
		CKEDITOR.plugins.mathjax.frameWrapper = function( iFrame, editor ) {
			iFrame.getFrameDocument().write( '<!DOCTYPE html>' +
				'' +
				'' +
					'<meta charset="utf-8">' +
				'' +
				'' +
					'' +
				'' +
				'' );

			return {
				setValue: function( value ) {
					var doc = iFrame.getFrameDocument(),
						tex = doc.getById( 'tex' );

					tex.setHtml( CKEDITOR.plugins.mathjax.trim( CKEDITOR.tools.htmlEncode( value ) ) );

					CKEDITOR.plugins.mathjax.copyStyles( iFrame, tex );

					editor.fire( 'lockSnapshot' );

					iFrame.setStyles( {
						width: Math.min( 250, tex.$.offsetWidth ) + 'px',
						height: doc.$.body.offsetHeight + 'px',
						display: 'inline',
						'vertical-align': 'middle'
					} );

					editor.fire( 'unlockSnapshot' );
				}
			};
		};
	}
} )();

/**
 * Sets the path to the MathJax library. It can be both a local resource and a location different than the default CDN.
 *
 * Please note that this must be a full or absolute path.
 *
 * Read more in the [documentation](#!/guide/dev_mathjax)
 * and see the [SDK sample](http://sdk.ckeditor.com/samples/mathjax.html).
 *
 *		config.mathJaxLib = '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML';
 *
 * **Note:** Since CKEditor 4.5 this option does not have a default value, so it must
 * be set in order to enable the MathJax plugin.
 *
 * @since 4.3
 * @cfg {String} mathJaxLib
 * @member CKEDITOR.config
 */

/**
 * Sets the default class for `span` elements that will be
 * converted into [Mathematical Formulas](http://ckeditor.com/addon/mathjax)
 * widgets.
 *
 * If you set it to the following:
 *
 *		config.mathJaxClass = 'my-math';
 *
 * The code below will be recognized as a Mathematical Formulas widget.
 *
 *		\( \sqrt{4} = 2 \)
 *
 * Read more in the [documentation](#!/guide/dev_mathjax)
 * and see the [SDK sample](http://sdk.ckeditor.com/samples/mathjax.html).
 *
 * @cfg {String} [mathJaxClass='math-tex']
 * @member CKEDITOR.config
 */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TTF.Models.Tree.Leaf
{
    /// <summary>
    /// !A && B && C
    /// </summary>
    public class BaseXequalsT : Calculation
    {
        public override float GetY(float D, float E, float F)
        {
            return D - (D * F / 100);
        }
    }
}


text:
@section('scripts')

@extends('layout')

@section('content')

    <form name="test-form" method="POST" action="#">

            Tags
            <select name="tags[]" class="form-control" multiple="multiple" id="tags"></select>

    </form>

@endsection


text:
require './memento'
require './myobject'

def main
  my_object = MyObject.new
  memento = Memento.new

  my_object.value = "first value"
  puts my_object.value
  memento.include my_object

  my_object.value = "second value"
  puts my_object.value
  memento.include my_object

  my_object.value = "third value"
  puts my_object.value
  memento.include my_object

  memento.undo
  my_object = memento.current
  puts my_object.value

  memento.undo
  my_object = memento.current
  puts my_object.value

  memento.redo
  my_object = memento.current
  puts my_object.value
end

main


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.homedrop.core.FtpHandler</title>
<meta name="date" content="2016-01-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.homedrop.core.FtpHandler

Packages that use FtpHandler

Package
Description

org.homedrop.core

Uses of FtpHandler in org.homedrop.core

Classes in org.homedrop.core that implement FtpHandler

Modifier and Type
Class and Description

class
HomeDrop

Main system class

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">Microservices</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />

  <link rel="stylesheet" href="../../static/lib/bootstrap-3.3.5/css/bootstrap.css" th:href="@{/lib/bootstrap-3.3.5/css/bootstrap.min.css}" />

  <link rel="stylesheet" href="../../static/lib/font-awesome-4.4.0/css/font-awesome.css" th:href="@{/lib/font-awesome-4.4.0/css/font-awesome.min.css}" />

  <link rel="stylesheet" href="../../static/lib/ionicons-2.0.1/css/ionicons.css" th:href="@{/lib/ionicons-2.0.1/css/ionicons.min.css}" />

  <link rel="stylesheet" href="../../static/css/AdminLTE.min.css" th:href="@{/css/AdminLTE.min.css}" />

  <link rel="stylesheet" href="../../static/css/skins/_all-skins.min.css" th:href="@{/css/skins/_all-skins.min.css}" />

      ALT

      AdminLTE

        Toggle navigation

              4

You have 4 messages

                        Support Team
                         5 mins

Why not buy a new awesome theme?

                        AdminLTE Design Team
                         2 hours

Why not buy a new awesome theme?

                        Developers
                         Today

Why not buy a new awesome theme?

                        Sales Department
                         Yesterday

Why not buy a new awesome theme?

                        Reviewers
                         2 days

Why not buy a new awesome theme?

See All Messages

              10

You have 10 notifications

                       5 new members joined today

                       Very long description here that may not fit into the
                      page and may cause design problems

                       5 new members joined

                       25 sales made

                       You changed your username

View all

              9

You have 9 tasks

                        Design some buttons
                        20%

                          20% Complete

                        Create a nice theme
                        40%

                          40% Complete

                        Some task I need to do
                        60%

                          60% Complete

                        Make beautiful transitions
                        80%

                          80% Complete

                View all tasks

              Alexander Pierce

                  Alexander Pierce - Web Developer
                  Member since Nov. 2012

                    Followers

                    Sales

                    Friends

                  Profile

                  Sign out

Alexander Pierce

           Online

      <form action="#" method="get" class="sidebar-form">

          <input type="text" name="q" class="form-control" placeholder="Search..." />

                <button type="submit" name="search" id="search-btn" class="btn btn-flat">
                </button>

      </form>

MAIN NAVIGATION

             Dashboard

 Dashboard v1

 Dashboard v2

            Layout Options
            4

 Top Navigation

 Boxed

 Fixed

 Collapsed Sidebar

             Widgets
            new

            Charts

 ChartJS

 Morris

 Flot

 Inline charts

            UI Elements

 General

 Icons

 Buttons

 Sliders

 Timeline

 Modals

             Forms

 General Elements

 Advanced Elements

 Editors

             Tables

 Simple tables

 Data tables

             Calendar
            3

             Mailbox
            12

             Examples

 Invoice

 Profile

 Login

 Register

 Lockscreen

 404 Error

 500 Error

 Blank Page

 Pace Page

             Multilevel

 Level One

               Level One

 Level Two

                   Level Two

 Level Three

 Level Three

 Level One

 Documentation

LABELS

 Important

 Warning

 Information

        Dashboard
        Version 2.0

 Home

Dashboard

      Version 2.3.2

    Copyright © 2014-2015 Almsaeed Studio. All rights
    reserved.

Recent Activity

Langdon's Birthday

Will be 23 on April 24th

Frodo Updated His Profile

New phone +1(800)555-1234

Nora Joined Mailing List

nora@example.com

Cron Job 254 Executed

Execution time 5 seconds

Tasks Progress

                Custom Template Design
                70%

                Update Resume
                95%

                Laravel Integration
                50%

                Back End Framework
                68%

        <form method="post">

General Settings

              Report panel usage
              <input type="checkbox" class="pull-right" checked="checked" />

              Some information about this general settings option

              Allow mail redirect
              <input type="checkbox" class="pull-right" checked="checked" />

              Other sets of options are available

              Expose author name in posts
              <input type="checkbox" class="pull-right" checked="checked" />

              Allow the user to show his name in blog posts

Chat Settings

              Show me as online
              <input type="checkbox" class="pull-right" checked="checked" />

              Turn off notifications
              <input type="checkbox" class="pull-right" />

              Delete chat history

        </form>


text:
package dbx_error

func NewErrorAuth(de ErrorInfo) ErrorAuth {
	return &errorAuthImpl{
		de: de,
	}
}

type errorAuthImpl struct {
	de ErrorInfo
}

func (z errorAuthImpl) IsInvalidAccessToken() bool {
	return z.de.HasPrefix("invalid_access_token")
}

func (z errorAuthImpl) IsInvalidSelectUser() bool {
	return z.de.HasPrefix("invalid_select_user")
}

func (z errorAuthImpl) IsInvalidSelectAdmin() bool {
	return z.de.HasPrefix("invalid_select_admin")
}

func (z errorAuthImpl) IsUserSuspended() bool {
	return z.de.HasPrefix("user_suspended")
}

func (z errorAuthImpl) IsExpiredAccessToken() bool {
	return z.de.HasPrefix("expired_access_token")
}

func (z errorAuthImpl) IsMissingScope() bool {
	return z.de.HasPrefix("missing_scope")
}

func (z errorAuthImpl) IsRouteAccessDenied() bool {
	return z.de.HasPrefix("route_access_denied")
}