text:
package Reblog::Import;

use base qw( Class::ErrorHandler );

use strict;
use warnings;

use POSIX;

use Date::Parse;

use MT::Author;
use MT::Blog;
use MT::Util qw( offset_time ts2epoch epoch2ts dirify );

use URI::Fetch;
use XML::XPath;
use XML::XPath::XMLParser;

use Carp;
use Encode;

use constant SPLIT_TOKEN => chr(28);

sub iso2dt {

    # TAKEN FROM XML::Atom::Util
    my ($iso) = @_;
    return
        unless $iso
            =~ /^(\d{4})(?:-?(\d{2})(?:-?(\d\d?)(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-]\d{2}:\d{2}))?)?)?)?/;
    my ( $y, $mo, $d, $h, $m, $s, $zone )
        = ( $1, $2 || 1, $3 || 1, $4 || 0, $5 || 0, $6 || 0, $7 );
    require DateTime;
    my $dt = DateTime->new(
        year      => $y,
        month     => $mo,
        day       => $d,
        hour      => $h,
        minute    => $m,
        second    => $s,
        time_zone => 'UTC',
    );
    if ( $zone && $zone ne 'Z' ) {
        my $seconds = DateTime::TimeZone::offset_as_seconds($zone);
        $dt->subtract( seconds => $seconds );
    }
    $dt;
}

sub assign_categories {
    my ($arg_ref) = @_;
    my $entry      = $arg_ref->{entry};
    my $blog       = $arg_ref->{blog};
    my $author     = $arg_ref->{author};
    my $categories = $arg_ref->{cats};
    my $feed_title = $arg_ref->{feed_title};

    my $res     = [];
    my $plugin  = MT->component('reblog');
    my $blog_id = $blog->id;

    # Load the Plugin setting that determines if categories are to be created
    # based on the metadata in the entries appearing in the feed.
    my $import_categories = $plugin->get_config_value( 'import_categories',
        'blog:' . $blog_id );
    my $feed_title_to_cat = $plugin->get_config_value(
        'import_feed_title_as_category',
        'blog:' . $blog_id
    );

    # Exit this subroutine if the configuration doesn't require categories to
    # be created.
    unless ($import_categories || $feed_title_to_cat) {
        return $res;
    }

    # Create a string of whatever categories are needed based on the
    # configuration selections.
    my @saved_cats;
    push @saved_cats, $feed_title
        if $feed_title_to_cat;
    push @saved_cats, $categories
        if $import_categories;

    my $saved_categories = join( SPLIT_TOKEN, @saved_cats);

    # Load the categories that already exist in this blog into @cats.
    my (@cats) = MT::Category->load( { blog_id => $blog_id } );
    my ( $cat, $place );

    # Create %cat_hash with Category label keys.
    my %cat_hash;
    foreach my $cat (@cats) {
        $cat_hash{ lc( $cat->label ) } = $cat;
    }

    # Grab the placement entries from the database for this entry.
    my (@placements) = MT::Placement->load( { entry_id => $entry->id } );

    my %place_hash;

    # Create %place_hash with Category id keys.
    foreach $place (@placements) {
        $place_hash{ $place->category_id } = $place;
    }

    # Break the categories up into individual array elements in @subs.
    my @subs;
    ($saved_categories) && ( @subs = split( SPLIT_TOKEN, $saved_categories ) );

    # Iterate through the categories in @subs.
    my $primary = 0;

    foreach my $sub (@subs) {

        # Break up this subject into Category labels.
        (@cats) = split( /\:\:/, $sub );

        # $parent is set to 0 at this stage because this is either the only
        # category label or the first category label in a hierarchy that's
        # being processed.

        # $cat_depth represents the place in the Category label hierarchy we
        # are currently processing. If $cat_depth == $#cats, then the category
        # belongs in the $place_hash shown below.
        my $parent = 0;
        my $cat_depth = 0;

        # Iterate through the Category labels.
        foreach my $cat_label (@cats) {
            $cat_label =~ s/\+/ /igs;
            my ($existing_category);

            # If $parent is not set, attempt to load the Category according to
            # its label. If $parent is set, attempt to load the Category
            # according to its label as a subcategory of $parent->id.
            if ($parent == 0) {
                $existing_category = MT::Category->load({
                    blog_id => $blog_id,
                    label   => $cat_label,
                });
            } else {
                $existing_category = MT::Category->load({
                    blog_id => $blog_id,
                    label   => $cat_label,
                    parent  => $parent->id,
                });
            }

            # If the Category exists already, assign it to $cat, otherwise
            # create the category, assign it to $cat, and add it to the
            # $cat_hash.
            if ($existing_category) {
                $cat = $existing_category;
            } else {

                # Try harder to find a matching category with a basename match.
                if ($parent == 0) {
                    $existing_category = MT::Category->load({
                        blog_id  => $blog_id,
                        basename => dirify($cat_label),
                    });
                } else {
                    $existing_category = MT::Category->load({
                        blog_id  => $blog_id,
                        basename => dirify($cat_label),
                        parent   => $parent->id,
                    });
                }

                if ($existing_category) {
                    $cat = $existing_category;
                }
                else {
                    # No category with the existing label or basename could be found. Therefore, a new category needs to be created.
                    $cat = create_category( $cat_label, $blog, $author, $parent );
                    $cat_hash{ lc( $cat->label ) } = $cat;
                }
            }

            # If $cat_depth is equal to the number of elements in @cats, add it
            # to the $place_hash if it doesn't already exist.
            #
            # When $cat_depth == $#cats, this means that the Category was
            # specified in the $categories and isn't just a parent category that
            # needed to be created because it didn't exist.
            if ( $cat_depth == $#cats ) {
                if ( exists( $place_hash{ $cat->id } ) ) {
                    $place = $place_hash{ $cat->id };
                }
                else {
                    $place = create_placement( $entry, $cat, 0 );
                    $place_hash{ $cat->id } = $place;
                }

                # If there is no Primary Category yet, set it to this Category.
                if ( !$primary ) {
                    $primary = $place;
                    $primary->is_primary(1);
                    $primary->save() or die $primary->errstr;
                }
            }

            # Set the current Category to be the parent, add it to @res, and
            # bump $cat_depth.
            $parent = $cat;
            push( @$res, $cat );
            $cat_depth++;
        }
    }

    my %curr_cats;

    # Iterate through @res, to build %curr_cats.
    foreach $cat (@$res) {
        $curr_cats{ $cat->id } = $cat;
    }

    # Iterate through %place_hash, making sure that each placement exists in
    # $curr_cats.
    foreach $place ( values %place_hash ) {
        if ( !exists( $curr_cats{ $place->category_id } ) ) {
            $place->remove() or die $place->errstr;
        }
    }

    # If the Primary Category isn't designated already, set it to the first
    # Category listed on the entry in the feed.
    if ( !$primary && scalar(@$res) > 0 ) {
        my @vals = values(%place_hash);
        $primary = $place_hash{ $vals[0] };
        $primary->is_primary(1);
        $primary->save() or die $primary->errstr;
    }

    # Return the data structure representing the Categories.
    return $res;
}

# When importing, if a category doesn't exist it should be created.
sub create_category {
    my ( $label, $blog, $author, $parent ) = @_;

    my $author_id;
    if ( $author == -1 ) {
        $author_id = 0;
    }
    else {
        $author_id = $author->id;
    }

    my $cat = MT::Category->new();
    my $original = $cat->clone;

    $cat->blog_id( $blog->id );
    $cat->allow_pings( $blog->allow_pings_default );
    $cat->label($label);
    $cat->author_id($author_id);
    $cat->parent( ( $parent ? $parent->id : 0 ) );

    $cat->save() or die $cat->errstr;

    MT->log({
       message => MT->translate(
            "Category '[_1]' created by '[_2]'", $cat->label,
            $author->name
        ),
        blog_id  => $cat->blog_id,
        level    => MT::Log::INFO(),
        class    => 'category',
        category => 'new',
    });

    return MT::Category->load( $cat->id );
}

sub create_placement {
    my ( $entry, $cat, $is_primary ) = @_;

    my $place = MT::Placement->new();
    $place->entry_id( $entry->id );
    $place->blog_id( $entry->blog_id );
    $place->category_id( $cat->id );
    $place->is_primary($is_primary);
    $place->save() or die $place->errstr;

    return MT::Placement->load( $place->id );
}

sub import_entries {
    my $class = shift;
    my ( $sourcefeed, $args ) = @_;
    my $app = MT->instance;

    my ( $blog_id, $author, $suppress, $cache_ttl );
    $blog_id   = $args->{blog_id};
    $author    = $args->{author};
    $suppress  = $args->{suppress};
    $cache_ttl = $args->{cache_ttl};

    unless ( $cache_ttl && $cache_ttl =~ m|^\d+$| ) {
        $cache_ttl ||= 15 * 60;
    }

    my $author_id;
    my ( $blog, $cache, $source_rss );
    my $config = MT::ConfigMgr->instance;

    if ($suppress) {    # Indicating a validation test
        $source_rss = $sourcefeed;
        undef $sourcefeed;
        use MT::Cache::Null;
        $cache = MT::Cache::Null->new;
    }
    else {
        if ( $author == -1 ) {
            $author_id = 0;
        }
        else {
            if ( !ref($author) ) {
                $author = MT::Author->load($author);
            }
            $author_id = $author->id;
        }
        $source_rss = $sourcefeed->url;
        $blog       = MT::Blog->load($blog_id);

        # Someday perhaps we can have config directives allowing us to choose
        # between MT::Cache::Negotiate, MT::Cache::Null, and a file-based
        # caching system
        use MT::Cache::Negotiate;
        $cache = MT::Cache::Negotiate->new( ttl => $cache_ttl );
    }
    unless ($source_rss) {
        return $class->error("No sourcefeed selected for validation");
    }
    my $mt_vers = MT->version_number;
    my (@entries);
    my $plugin = MT->component('reblog');

    require LWP::UserAgent;
    my $ua = MT->new_ua( { timeout => 20 } );
    $ua->env_proxy;
    $ua->max_size('1048576'); # 1MB
    my $res;

    unless (
        $res = URI::Fetch->fetch(
            $source_rss,
            UserAgent => $ua,
            Cache     => $cache
        )
        )
    {

        if ($sourcefeed) {
            $sourcefeed->increment_error( URI::Fetch->errstr );
        }
        return $class->error(
            "Error fetching feed ($source_rss): " . URI::Fetch->errstr );
    }
    my $rss = $res->content;

    if ( MT->config('HTTPProxy') ) {    # For XML::XPath's DTD fetching
        $ENV{HTTP_PROXY} = MT->config('HTTPProxy');
    }

    if ( defined($rss) && $rss ) {
        my $xp = XML::XPath->new( xml => $rss );
        my $map = {
            'body'          => 'description',
            'title'         => 'title',
            'link'          => 'link',
            'guid'          => 'rb:guid',
            'via_link'      => 'rb:via_url',
            'orig_date'     => 'rb:source_published_date',
            'source_author' => 'rb:source_author',
            'source_name'   => 'rb:source',
            'source_url'    => 'rb:source_url',
            'summary'       => 'summary',
        };

        my $enclosure_url    = "";
        my $enclosure_length = "";
        my $enclosure_type   = "";
        my $gen;
        eval { $gen = $xp->findvalue('/feed/generator'); };
        my $flagged = 0;
        if ($@) {
            $flagged = 1;
        }
        if ($flagged) {
            my $unliberal_error = $@;
            eval "require XML::LibXML";
            eval "require XML::Liberal;";
            if ($@) {
                $@ = $unliberal_error;
            }
            else {
                $@ = $unliberal_error;
                XML::Liberal->globally_override('LibXML');
                my $parser = XML::LibXML->new;              # isa XML::Liberal
                my $doc    = $parser->parse_string($rss);
                $xp = XML::XPath->new( $doc->toString );
                eval { $gen = $xp->findvalue('/feed/generator'); };
            }
            if ($@) {

                if ($sourcefeed) {
                    $sourcefeed->increment_error($@);
                }
                return $class->error(
                    "Error parsing feed ($source_rss): " . $@ );
            }
        }
        my $type;
        if ( $xp->exists("/rss") ) {
            $type              = "rss";
            $map->{'date'}     = 'pubDate';
            #$map->{'subjects'} = 'dc:subject';
            $map->{'subjects'} = 'category';
        }
        elsif ( $xp->exists("/rdf:RDF") ) {
            $type              = "rdf";
            $map->{'date'}     = 'dc:date';
            $map->{'subjects'} = 'dc:subject';
        }
        elsif ( $gen eq 'Google Reader' ) {
            $type              = "atom";
            $map->{'date'}     = 'published';
            $map->{'subjects'} = 'category/@term';
            $map->{'body'}     = 'content';
            $map->{'summary'}  = 'summary';

            $map->{'link'} = 'link[@rel="alternate"]/@href';
            if ( !$map->{link} ) {
                $map->{'link'} = 'link/@href';
            }

            $map->{'guid'}          = 'id';
            $map->{'orig_date'}     = 'updated';
            $map->{'source_author'} = 'author/name';
            $map->{'source_name'}   = 'source/title';
            $map->{'source_url'}    = 'source/link/@href';
        }
        elsif ( $xp->exists("/feed") ) {
            $type               = "atom";
            $map->{'date'}      = 'updated';
            $map->{'orig_date'} = 'published';
            $map->{'body'}      = 'content';
            $map->{'summary'}   = 'summary';
            $map->{'subjects'}  = 'category/@term';

            $map->{'link'} = 'link[@rel="alternate"]/@href';
            if ( !$map->{link} ) {
                $map->{'link'} = 'link/@href';
            }
            $map->{'guid'}          = 'id';
            $map->{'source_author'} = 'author/name';
        }
        else {
            if ($sourcefeed) {
                $sourcefeed->increment_error(
                    "Feed was neither RDF (RSS 1.0) nor RSS (2.0) nor Atom");
            }
            return $class->error(
                "Feed was neither RDF (RSS 1.0) nor RSS (2.0) nor Atom");
        }

        my ( $channeltitle, $channellink );
        if ( $type eq 'rss' ) {
            $channeltitle = $xp->findvalue('/rss/channel/title');
            $channellink  = $xp->findvalue('/rss/channel/link');
        }
        elsif ( $type eq 'rdf' ) {
            $channeltitle = $xp->findvalue('/rdf:RDF/channel/title');
            $channellink  = $xp->findvalue('/rdf:RDF/channel/link');
        }
        elsif ( $type eq 'atom' ) {
            $channeltitle = $xp->findvalue('/feed/title');
            $channellink
                = $xp->findvalue('/feed/link[@rel="alternate"]/@href');
        }
        my $nodeset;
        if ( $type eq 'atom' ) {
            $nodeset = $xp->findnodes("//entry");
        }
        else {
            $nodeset = $xp->findnodes("//item");
        }

        while ( my $node = $nodeset->shift() ) {
            my $body;
            $body = &_clean_html( $xp->findvalue( $map->{'body'}, $node ) );
            unless ($body) {
                $body = &_clean_html(
                    $xp->findvalue( $map->{'summary'}, $node ) );
            }
            my $title
                = &_clean_html( $xp->findvalue( $map->{'title'}, $node ) );
            my $link = $xp->findvalue( $map->{'link'}, $node );
            my $date = $xp->findvalue( $map->{'date'}, $node );
            if ( !$date && $map->{'date'} eq 'pubDate' ) {

                # RSS 0.91 properly treats pubDate as a channel-level item
                $date = $xp->findvalue("/rss/channel/pubDate");
            }
            my $subjects
                = &_clean_html( $xp->findvalue( $map->{'subjects'}, $node ) );

            my $guid     = $xp->findvalue( $map->{'guid'},     $node );
            # Use only the last 255 characters of the link, to fit the
            # size of the column in the ReblogData datasource.
            $guid = substr $guid, -255;

            my $via_link = $xp->findvalue( $map->{'via_link'}, $node );
            my $orig_date;
            $orig_date = $xp->findvalue( $map->{'orig_date'}, $node );

            my $source_author = &_clean_html(
                $xp->findvalue( $map->{'source_author'}, $node ) );
            my $source_name = &_clean_html(
                $xp->findvalue( $map->{'source_name'}, $node ) );
            my $source_url = $xp->findvalue( $map->{'source_url'}, $node );
            my $source_title
                = &_clean_html( $xp->findvalue( $map->{'title'}, $node ) );
            my $summary
                = &_clean_html( $xp->findvalue( $map->{'summary'}, $node ) );

            # it may not be in the map hash, so if there's no value, that's OK.
            my $modifiedTime = $xp->findvalue( 'updated', $node );

            # Tricky to get the enclosures tag because it has no value,
            # so you can't call $xp->findvalue().  it only has attributes.
            # instead, call findnodes within this current node for enclosure,
            # grab the first one, and regard it as your winner.
            my $enclosures = $xp->findnodes( 'enclosure', $node );

            # $enclosures now is a nodelist.  just grab the first one.
            if ($enclosures) {
                $enclosures = $enclosures->shift();

                $enclosure_url  = $enclosures->getAttribute('url');
                $enclosure_type = $enclosures->getAttribute('type');
                if ( !$enclosure_type ) {
                    $enclosure_type = determine_file_type($enclosure_url);
                }
                $enclosure_length = $enclosures->getAttribute('length');
            }

            # Deal with the case of multiple categories in Atom and RSS
            if ( $type eq 'atom' || $type eq 'rss' ) {
                my @subjects;
                my @subjectnodes
                    = ( $xp->findnodes( $map->{'subjects'}, $node ) );
                foreach my $catnode (@subjectnodes) {
                    if ( $type eq 'atom' ) {
                        push @subjects,
                            &_clean_html( $catnode->getNodeValue );
                    }
                    elsif ( $type eq 'rss' ) {
                        push @subjects,
                            &_clean_html( $catnode->string_value );
                    }
                }
                if ( scalar @subjects > 1 ) {
                    $subjects = join SPLIT_TOKEN, @subjects;
                }
            }

            # Let's plug in some sensible values if these are missing
            # which will imply that we're not using a reblog feed but
            # rather just a standard RSS feed
            # We want to pick up: GUID, Source Author, Via Link, Source,
            #                     Source Title, Source Feed URL
            if ( !$guid ) {
                $guid = $xp->findvalue( 'guid', $node );
                if ( !$guid ) {
                    $guid = $link;

                    # This is questionable, as links are not assuredly GUIDs;
                    # this actually doesn't work for google reader feeds
                }
            }
            if ( !$via_link ) {
                $via_link = $link;
            }
            if ( !$source_author ) {
                $source_author
                    = $xp->findvalue( 'dc:creator', $node );    # dc:creator
            }
            if ( !$source_name ) {
                $source_name = $channeltitle;
            }
            if ( !$source_title ) {
                $source_title = $channeltitle;
            }
            if ( !$source_url ) {
                $source_url = $channellink;
            }

            my $ts = str2time($date);

            if ($modifiedTime) {
                $ts = str2time($modifiedTime);
            }

            $date = POSIX::strftime( "%Y%m%d%H%M%S",
                gmtime( offset_time( $ts, $blog ) ) );

            if ($orig_date) {
                my $orig_ts = str2time($orig_date);
                $orig_date = POSIX::strftime(
                    ( $mt_vers < 3.2 ? "%Y-%m-%d %H:%M:%S" : "%Y%m%d%H%M%S" ),
                    gmtime( offset_time( $orig_ts, $blog ) )
                );
            }
            else {
                $orig_date = $date;
            }

            # $suppress means the feed is being validated, or that it should
            # otherwise not save the data that was just processed. Items with
            # the $source_title set to '<please insert title>' are incomplete.
            return $class->error('Feed is still being validated')
		if $suppress;
            return $class->error('Feed is incomplete')
		if $source_title eq '<please insert title>';

            my $entry;

            # Use only the last 255 characters of the GUID to fit the
            # size of the column in the ReblogData datasource. (It could be
            # longer if it was supplied rather than calculated by Reblog.)
            $guid = substr $guid, -255;

            # If we're updating an old reblogged row, we need this entry but
            # can't use MT::Object join for this circumstance, so do it manually
            my (@rb_data) = Reblog::ReblogData->load( { guid => "$guid" },
                { sort => 'created_on', direction => 'ascend' } );

            my $rb_data;
            foreach my $rbd (@rb_data) {
                $entry = MT::Entry->load(
                    { id => $rbd->entry_id, blog_id => $blog_id } );
                if ($entry) {
                    $rb_data = $rbd;
                }
            }

            if ( !$rb_data ) {
                $rb_data = Reblog::ReblogData->new;
                $rb_data->created_on($date);
            }

            $rb_data->sourcefeed_id( $sourcefeed->id );
            $rb_data->blog_id( $sourcefeed->blog_id  );
            $rb_data->link(           $link          );
            $rb_data->guid(           $guid          );
            $rb_data->via_link(       $via_link      );
            $rb_data->src_created_on( $orig_date     );
            $rb_data->src_author(     $source_author );
            $rb_data->src(            $source_name   );
            $rb_data->src_url(        $source_url    );
            $rb_data->src_feed_url(   $source_rss    );
            $rb_data->src_title(      $source_title  );
            $rb_data->encl_url(    $enclosure_url    );
            $rb_data->encl_length( $enclosure_length );
            $rb_data->encl_type(   $enclosure_type   );

            # If we're not updating an existing entry, we're creating an new one
            # if this is the case, we will be creating an reblog_data row

            if (!(  $rb_data->entry_id
                    && ($entry = MT::Entry->load(
                            { id => $rb_data->entry_id, blog_id => $blog_id }
                        )
                    )
                )
                )
            {
                $entry = MT::Entry->new();
                $entry->blog_id($blog_id);
                $entry->status( $blog->status_default );
                $entry->allow_comments( $blog->allow_comments_default );
                $entry->allow_pings( $blog->allow_pings_default );
                $entry->convert_breaks(0);
                $entry->author_id($author_id);
                my $kw    = $subjects;
                my $token = SPLIT_TOKEN;
                $kw && $kw =~ s/$token/, /g;
                $entry->keywords($kw);
                $entry->authored_on($orig_date);
                $entry->created_on($orig_date);
                $entry->reblog_reblogged(1);

                if ( $author_id == 0 ) {
                    $entry->reblog_anonymous(1);
                }
                else {
                    $entry->reblog_anonymous(0);
                }
                $entry->reblog_lbl( $sourcefeed->label );
            }

            my $ts_modified = 0;
            if ( $entry->modified_on ) {
                $ts_modified = ts2epoch( $blog, $entry->modified_on );
            }
            unless ($ts) {
                $ts = 1;    # RSS 0.91, no pubDate found
            }

            my $status = 'old';

            my $categories = [];

            # No problem, now that ts_modified is correct.
            if (   ( !$entry->id )
                || ( POSIX::floor($ts) > POSIX::floor($ts_modified) ) )
            {
                $status = ( $entry->id ? 'update' : 'new' );
                if ( $entry->id ) {
                    use MT::Util;
                    $entry->modified_on( MT::Util::epoch2ts( undef, time ) );
                }
                if ($title) {
                    $entry->title($title);
                }
                else {
                    $entry->title('Untitled');
                }
                $entry->text($body);
                $entry->excerpt($summary);
                $entry->basename( MT::Util::make_unique_basename($entry) )
                    if ( $status eq 'new' );

                # load SourceFeed by source_rss. If it's excerpted, then
                # transform the $body and $created extended appropriately.
                my $so = Reblog::ReblogSourcefeed->load(
                    {   url       => $source_rss,
                        is_active => '1',
                        blog_id   => $blog_id
                    }
                );

                if ( $so->is_excerpted ) {

                    # chop body with regex
                    $body =~ m|(.*?</p>.*?</p>)(.*)|ms;

                    $entry->text($1);
                    $entry->text_more($2);
                }

                $entry->save || die "ENTRY SAVE FAILURE: " . $entry->errstr;

                # NOTE: The new entry save creates an rbd row, per our
                # post_save callback, so we need to sync the ID. But sometimes,
                # that doesn't happen, but it's overzealous to die.
                my $entry_rb_data;
                if (
                    $entry_rb_data
                        = Reblog::ReblogData->load({ entry_id => $entry->id })
                ) {
                    $rb_data->id( $entry_rb_data->id );
                }

                $categories
                    = assign_categories({
                        entry      => $entry,
                        blog       => $blog,
                        author     => $author,
                        cats       => $subjects,
                        feed_title => $channeltitle,
                    });

                $rb_data->modified_on($date);
                $rb_data->entry_id( $entry->id );

                $rb_data->save
                    or die $app->log({
                        level   => MT::Log::ERROR(),
                        blog_id => $blog->id,
                        message => 'Reblog Data save error: ' . $rb_data->errstr,
                        class   => 'reblog',
                    });
                    # || die $class->error(
                    #     "RBDATA SAVE FAILURE: " . $rb_data->errstr
                    # );

                $app->log({
                    message  => $app->translate(
                        "Entry '[_1]' (ID:[_2]) added by Reblog for user '[_3]'",
                        $entry->title, $entry->id, $author->name
                    ),
                    level    => MT::Log::INFO(),
                    blog_id  => $blog->id,
                    class    => 'entry',
                    category => 'new', # A new entry.
                    metadata => $entry->id,
                });

                MT->run_callbacks( 'plugin_reblog_new_or_changed_entry_parsed', $entry, $rb_data,
                    { parser_type => 'XML::XPath', parser => $xp, node => $node }
                );
            }

            MT->run_callbacks( 'plugin_reblog_entry_parsed', $entry, $rb_data,
                { parser_type => 'XML::XPath', parser => $xp, node => $node }
            );

            my $eRec = {
                entry       => $entry,
                status      => $status,
                reblog_data => $rb_data,
            };

            push( @entries, $eRec );

        }
    }
    elsif ( $res->http_status != 304 ) {
        if ($sourcefeed) {
            $sourcefeed->increment_error(
                "Failed to fetch RSS feed from $source_rss");
        }
        return $class->error("Failed to fetch RSS feed from $source_rss");
    }
    return (@entries);
}

sub determine_file_type {
    my $url = shift;
    my ($ext) = $url =~ m/\.(\w+)$/;
    $ext = lc $ext;
    my %listing = (
        mp3     => 'audio/mpeg',
        m4a     => 'audio/mp4',
        wma     => 'audio/wma',
        midi    => 'audio/midi',
        aa      => 'audio/aa',
        wav     => 'audio/wav',
        ogg     => 'application/ogg',
        torrent => 'application/x-bittorrent',
        exe     => 'application/octet-stream',
        bmp     => 'image/bmp',
        jpg     => 'image/jpeg',
        jpeg    => 'image/jpeg',
        gif     => 'image/gif',
        tiff    => 'image/tiff',
        tif     => 'image/tiff',
        png     => 'image/png',
        mp4     => 'video/mp4',
        mp4v    => 'video/mp4',
        mpeg    => 'video/mpeg',
        avi     => 'video/msvideo',
        mov     => 'video/quicktime',
        wmv     => 'video/x-ms-wmv',
    );

    return $listing{$ext} || 'unknown';
}

sub _clean_html {
    my $text = shift;
    return unless ($text);
    $text =~ s/([^\x00-\x7f])/'&#' . ord($1) . ';'/ge;
    $text = decode_utf8($text);
    return $text;
}

1;


text:
module Data.GitParser.Parser
    (parseCommits)
where
import Control.Monad.State
import Data.Char
import Data.List
import Data.Time.Format
import Data.Time.LocalTime
import System.Locale
import Data.GitParser.Types

getRight,getLeft :: GitParser [String]
getRight = fmap psRight get
getLeft  = fmap psLeft  get

putBlock bl = do ps <- get
                 put $ ps { psBlocks = psBlocks ps ++ [bl] }

getNextLine :: GitParser String
getNextLine = do r <- getRight
                 if null r then return [] else return (head r)

shift = do ps <- get
           if null (psRight ps)
              then return ()
              else do
                nl <- getNextLine
                put $ ps { psLeft = psLeft ps ++ [nl], psRight = tail $ psRight ps }

clear = do ps <- get
           put $ ps { psLeft = [] }

parseCommit :: GitParser ()
parseCommit = do nl <- getRight
                 if null nl
                   then return ()
                   else do getNextLine >>= findNext
                           parseCommit
    where
      findNext x | "commit"  `isPrefixOf` x = parseSHA
                 | "Merge:"  `isPrefixOf` x = parseMerge
                 | "Author:" `isPrefixOf` x = parseAuthor
                 | "Date:"   `isPrefixOf` x = parseDate
                 | "    "    `isPrefixOf` x = parseMessage
      findNext x = shift >> clear

parseSHA = do r <- getNextLine
              let sha = takeWhile (not . isSpace) . tail . dropWhile (/= ' ') $ r
              putBlock (SHA sha)
              shift >> clear

colonParse x  = takeWhile (/= '\n') . tail . dropWhile (/= ':') $ x
colonBlock con = do r <- getNextLine
                    putBlock (con $ strip . colonParse $ r)
                    shift >> clear

parseMerge   = shift >> clear
parseAuthor  = colonBlock Author
parseDate    = colonBlock Date

parseMessage = do r <- getNextLine
                  l <- getLeft
                  if "    " `isPrefixOf` r
                    then shift >> parseMessage
                    else putBlock (Message $ unlines . map (drop 4) $ l) >> clear

strip = reverse . fn . reverse . fn
        where fn = dropWhile isSpace

splitCommits l = filter (not . null) $  splitCommits (lines l) [] []
               where
                 splitCommits [] ls final = final ++ [unlines ls]
                 splitCommits (x:xs) ls final = if "commit" `isPrefixOf` x
                                                  then splitCommits xs [x] (final ++ [unlines ls])
                                                  else splitCommits xs (ls ++ [x]) final

toCommit = foldl af emptyCommit
    where af c (SHA a)     = c { getSHA     = a }
          af c (Author a)  = c { getAuthor  = toAuthor a }
          af c (Date a)    = c { getDate    = toLocalTime a }
          af c (Message a) = c { getMessage = a }

toLocalTime = parseTime defaultTimeLocale "%a %b %e %H:%M:%S %Y %z"
toAuthor x = let name = strip . takeWhile (/= '<') $ x
                 emal = tail . takeWhile (/= '>') . dropWhile (/= '<') $ x
             in CommitAuthor name emal

parseCommits = map (toCommit . psBlocks . execState parseCommit . mkParserState) . splitCommits

redpajama_set_name: RedPajamaGithub


text:
package com.oprisnik.semdroid.grouper.opcode;

import com.googlecode.dex2jar.util.DexOpcodeDump;
import com.oprisnik.semdroid.app.Opcode;
import com.oprisnik.semdroid.config.Configurable;
import com.oprisnik.semdroid.utils.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;

/**
 * Opcode grouper.
 */
public abstract class OpcodeGrouper implements Configurable {

    /**
     * Opcode group to ignore given opcodes.
     */
    public static final int OP_IGNORE = -1;
    public static final String OP_IGNORE_STRING = "IGNORE";

    /**
     * Returns the opcode group for the given opcode or OP_IGNORE if the opcode
     * should be ignored.
     *
     * @param opcode the opcode to group
     * @return grouped opcode name or OP_IGNORE if to be ignored
     */
    public abstract int getOpcodeGroup(int opcode);

    /**
     * Returns the opcode group for the given opcode or null if the opcode
     * should be ignored.
     *
     * @param opcode the opcode to group
     * @return grouped opcode name or null if to be ignored
     */
    public abstract String getOpcodeGroupName(int opcode);

    /**
     * Returns the opcode group for the given opcode or OP_IGNORE if the opcode
     * should be ignored.
     *
     * @param opcode the opcode to group
     * @return grouped opcode name or OP_IGNORE if to be ignored
     */
    public int getOpcodeGroup(Opcode opcode) {
        return getOpcodeGroup(opcode.getInt());
    }

    /**
     * Returns the opcode group for the given opcode or null if the opcode
     * should be ignored.
     *
     * @param opcode the opcode to group
     * @return grouped opcode name or null if to be ignored
     */
    public String getOpcodeGroupName(Opcode opcode) {
        return getOpcodeGroupName(opcode.getInt());
    }

    /**
     * Get a set of all possible opcode groups
     *
     * @return all possible opcode groups
     */
    public abstract SortedSet<Integer> getPossibleOpcodeGroups();

    /**
     * Return a grouped list of the given opcode list.
     *
     * @param opcodes the opcode list to group
     * @return grouped opcode list
     */
    public List<Integer> getGroupedList(List<Opcode> opcodes) {
        List<Integer> grouped = new ArrayList<Integer>();
        for (Opcode opcode : opcodes) {
            grouped.add(getOpcodeGroup(opcode));
        }
        return grouped;
    }

    protected static Map<Integer, String> getDexOpcodeMap() {
        try {
            // TODO: since DexOpcodeDump.map is private, we need to use reflection - maybe use own impl.
            Field field = DexOpcodeDump.class.getDeclaredField("map");
            field.setAccessible(true);
            Map<Integer, String> map = (Map<Integer, String>) field.get(null);
            field.setAccessible(false);
            return map;
        } catch (IllegalAccessException e) {
            Log.e(DefaultOpcodeGrouper.class.getName(), e.getMessage());
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            Log.e(DefaultOpcodeGrouper.class.getName(), e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}


text: Stereographic


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.sling</groupId>
    <artifactId>sling</artifactId>
    <version>26</version>
    <relativePath/>
  </parent>

  <artifactId>org.apache.sling.scripting.freemarker</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <name>Apache Sling Scripting FreeMarker</name>
  <description>Support for FreeMarker scripting</description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <sling.java.version>7</sling.java.version>
  </properties>

  <scm>
    <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/contrib/scripting/freemarker</connection>
    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/contrib/scripting/freemarker</developerConnection>
    <url>http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/freemarker</url>
  </scm>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-scr-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Embed-Dependency>freemarker;inline=true</Embed-Dependency>
            <!--
            A few notes on the lines below:
            * Freemarker's SLF4J support depends upon org.slf4j.spi. Grrr. They'll have to use Log4J.
            * If you want XPath support in Freemarker, it appears you need to provide one of Xalan standalone
              Sun's internalized version of Xalan, or Jaxen.
            -->
            <Import-Package>
              !org.slf4j.*,
              com.sun.org.apache.xml.internal.*;
              com.sun.org.apache.xpath.internal.*;
              javax.servlet.jsp.*; javax.swing.*;
              org.apache.log; org.apache.log4j;
              org.apache.tools.ant.*;
              org.apache.xml.utils; org.apache.xpath.*;
              org.dom4j.*; org.jaxen.*; org.jdom.*;
              org.mozilla.javascript;
              org.zeroturnaround.javarebel;
              org.python.*;resolution:=optional, *
            </Import-Package>
            <DynamicImport-Package>
              *
            </DynamicImport-Package>
            <ScriptEngine-Name>${project.name}</ScriptEngine-Name>
            <ScriptEngine-Version>${project.version}</ScriptEngine-Version>
            <_dsannotations>*</_dsannotations>
            <_metatypeannotations>*</_metatypeannotations>
            <_removeheaders>
              Embed-Dependency,
              Private-Package,
              Include-Resource
            </_removeheaders>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
          <!-- No javadocs -->
          <excludePackageNames>
            org.apache.sling.scripting.freemarker
          </excludePackageNames>
        </configuration>
      </plugin>
    </plugins>
  </reporting>

  <dependencies>
    <!-- OSGi -->
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>osgi.core</artifactId>
      <version>6.0.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>osgi.annotation</artifactId>
      <version>6.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.component.annotations</artifactId>
      <version>1.3.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.metatype.annotations</artifactId>
      <version>1.3.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- Apache Sling -->
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.api</artifactId>
      <version>2.0.8</version>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.scripting.api</artifactId>
      <version>2.1.4</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.24-incubating</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <!-- Testing -->
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.commons.testing</artifactId>
      <version>2.0.6</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for Batch.

---

## Getting Started

To build the SDK for Batch, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`

---

## Configuration

### Basic Information

These are the global settings for the Batch API.

``` yaml
title: BatchManagementClient
description: Batch Client
openapi-type: arm
tag: package-2022-10
```

### Tag: package-2022-10

These settings apply only when `--tag=package-2022-10` is specified on the command line.

```yaml $(tag) == 'package-2022-10'
input-file:
  - Microsoft.Batch/stable/2022-10-01/BatchManagement.json
```
### Tag: package-2022-06

These settings apply only when `--tag=package-2022-06` is specified on the command line.

``` yaml $(tag) == 'package-2022-06'
input-file:
  - Microsoft.Batch/stable/2022-06-01/BatchManagement.json
```

### Tag: package-2022-01

These settings apply only when `--tag=package-2022-01` is specified on the command line.

``` yaml $(tag) == 'package-2022-01'
input-file:
  - Microsoft.Batch/stable/2022-01-01/BatchManagement.json
```

### Tag: package-2021-06

These settings apply only when `--tag=package-2021-06` is specified on the command line.

``` yaml $(tag) == 'package-2021-06'
input-file:
  - Microsoft.Batch/stable/2021-06-01/BatchManagement.json
```

### Tag: package-2021-01

These settings apply only when `--tag=package-2021-01` is specified on the command line.

``` yaml $(tag) == 'package-2021-01'
input-file:
  - Microsoft.Batch/stable/2021-01-01/BatchManagement.json
```

### Tag: package-2020-09

These settings apply only when `--tag=package-2020-09` is specified on the command line.

``` yaml $(tag) == 'package-2020-09'
input-file:
  - Microsoft.Batch/stable/2020-09-01/BatchManagement.json
```

### Tag: package-2020-05

These settings apply only when `--tag=package-2020-05` is specified on the command line.

``` yaml $(tag) == 'package-2020-05'
input-file:
  - Microsoft.Batch/stable/2020-05-01/BatchManagement.json
```

### Tag: package-2020-03

These settings apply only when `--tag=package-2020-03` is specified on the command line.

``` yaml $(tag) == 'package-2020-03'
input-file:
  - Microsoft.Batch/stable/2020-03-01/BatchManagement.json
```

### Tag: package-2019-08

These settings apply only when `--tag=package-2019-08` is specified on the command line.

``` yaml $(tag) == 'package-2019-08'
input-file:
  - Microsoft.Batch/stable/2019-08-01/BatchManagement.json
```

### Tag: package-2019-04

These settings apply only when `--tag=package-2019-04` is specified on the command line.

``` yaml $(tag) == 'package-2019-04'
input-file:
  - Microsoft.Batch/stable/2019-04-01/BatchManagement.json
```

### Tag: package-2018-12

These settings apply only when `--tag=package-2018-12` is specified on the command line.

``` yaml $(tag) == 'package-2018-12'
input-file:
  - Microsoft.Batch/stable/2018-12-01/BatchManagement.json
```

### Tag: package-2017-09

These settings apply only when `--tag=package-2017-09` is specified on the command line.

``` yaml $(tag) == 'package-2017-09'
input-file:
- Microsoft.Batch/stable/2017-09-01/BatchManagement.json
```

## Suppression

Note that this setting should be removed once [this GitHub bug](https://github.com/Azure/azure-openapi-validator/issues/68) is fixed.

``` yaml
directive:
  - suppress: R2001
    where: $.definitions.Operation.properties.properties
    reason: Breaking change.

  - suppress: R2017
    where:
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"].put
    reason: Matching service response.

  - suppress: R2063
    reason: Bug in linter

  - suppress: R2066
    where:
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete"].post.operationId
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys"].post.operationId
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys"].post.operationId
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys"].post.operationId
    reason: This is fine as long as the OperationIds are all unique (as they presently are), and fixing it would likely involve a breaking change.

  - suppress: R3018
    where:
     - $.definitions.ApplicationProperties.properties.allowUpdates
     - $.definitions.BatchAccountProperties.properties.dedicatedCoreQuotaPerVMFamilyEnforced
     - $.definitions.CheckNameAvailabilityResult.properties.nameAvailable
     - $.definitions.StartTask.properties.waitForSuccess
     - $.definitions.VMExtension.properties.autoUpgradeMinorVersion
     - $.definitions.WindowsConfiguration.properties.enableAutomaticUpdates
    reason: Breaking change.

  - suppress: R3018
    where:
     - $.definitions.Operation.properties.isDataAction
    reason: Boolean required for operations schema.

  - suppress: R4009
    where:
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}/versions/{versionName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/detectors/{detectorId}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"].put
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"].patch
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}"].get
     - $.paths["/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/privateLinkResources/{privateLinkResourceName}"].get
    reason: Service missing headers.

  - suppress: OBJECT_MISSING_REQUIRED_PROPERTY
    where: $.definitions.UserAccount
    reason: This field contains a secret (password) and is not returned on a get (but is required on a PUT/PATCH). Previous discussions with the modelling team had said that this was the correct way to model this type of field.
```

### Tag: package-2017-05

These settings apply only when `--tag=package-2017-05` is specified on the command line.

``` yaml $(tag) == 'package-2017-05'
input-file:
- Microsoft.Batch/stable/2017-05-01/BatchManagement.json
```

### Tag: package-2017-01

These settings apply only when `--tag=package-2017-01` is specified on the command line.

``` yaml $(tag) == 'package-2017-01'
input-file:
- Microsoft.Batch/stable/2017-01-01/BatchManagement.json
```

### Tag: package-2015-12

These settings apply only when `--tag=package-2015-12` is specified on the command line.

``` yaml $(tag) == 'package-2015-12'
input-file:
- Microsoft.Batch/stable/2015-12-01/BatchManagement.json
```

---

## Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-net-track2
  - repo: azure-sdk-for-python-track2
  - repo: azure-sdk-for-java
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-node
  - repo: azure-sdk-for-js
  - repo: azure-sdk-for-ruby
    after_scripts:
      - bundle install && rake arm:regen_all_profiles['azure_mgmt_batch']
  - repo: azure-resource-manager-schemas
  - repo: azure-powershell
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  # last generated with AutoRest.1.0.0-Nightly20170129 from commit 19f63015ea5a8a0fc64b9d7e2cdfeac447d93eaf
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.Batch
  payload-flattening-threshold: 1
  output-folder: $(csharp-sdks-folder)/batch/Microsoft.Azure.Management.Batch/src/Generated
  clear-output-folder: true
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.batch
license-header: MICROSOFT_MIT_NO_CODEGEN
payload-flattening-threshold: 1
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-batch
```

### Java multi-api

``` yaml $(java) && $(multiapi)
batch:
  - tag: package-2015-12
  - tag: package-2017-09
  - tag: package-2017-01
  - tag: package-2017-05
```

### Tag: package-2015-12 and java

These settings apply only when `--tag=package-2015-12 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2015-12' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2015_12_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2015_12_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-09 and java

These settings apply only when `--tag=package-2017-09 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-09' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_09_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_09_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-01 and java

These settings apply only when `--tag=package-2017-01 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-01' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_01_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_01_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-05 and java

These settings apply only when `--tag=package-2017-05 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-05' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.batch.v2017_05_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/batch/mgmt-v2017_05_01
regenerate-manager: true
generate-interface: true
```

`


text:
package org.apache.commons.digester3.xmlrules;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Test harness object for holding results of digestion.
 */
public class ObjectTestImpl
{

    private final ArrayList<Object> children = new ArrayList<Object>();

    private String value = "";

    private Long longValue = new Long( -1L );

    private String property = "";

    private final HashMap<String, String> mapValue = new HashMap<String, String>();

    private boolean pushed = false;

    public ObjectTestImpl()
    {
    }

    @Override
    public String toString()
    {
        String str = value;
        for ( final Object o : children )
        {
            str += " " + o;
        }
        return str;
    }

    public void add( final Object o )
    {
        children.add( o );
    }

    public void setValue( final String val )
    {
        value = val;
    }

    public void setLongValue( final Long val )
    {
        longValue = val;
    }

    public Long getLongValue()
    {
        return longValue;
    }

    public void setStringValue( final String val )
    {
    }

    public boolean isPushed()
    {
        return pushed;
    }

    public void push()
    {
        pushed = true;
    }

    public void setMapValue( final String name, final String value )
    {
        this.mapValue.put( name, value );
    }

    public String getMapValue( final String name )
    {
        return this.mapValue.get( name );
    }

    public String getProperty()
    {
        return property;
    }

    public void setProperty( final String pProperty )
    {
        property = pProperty;
    }
}


text:
[Alpha](example.ogg)

[Bravo `code` *emphasis*.](example.ogg)

[Charlie](example.wav)

[Delta](example.opus)

[Echo](example.ogg).

[Foxtrot](example.ogg).

[Hotel](example.ogg "Golf")

[India]()


text:
layout: post
date: '2016-03-16'
title: "Weddington Way Dessy 2945 Sleeveless Floor-Length Mermaid/Trumpet"
category: Weddington Way
tags: [Weddington Way,Mermaid/Trumpet,Bateau,Floor-Length,Sleeveless]
---
### Weddington Way Dessy 2945
Just **$109.99**
###   Sleeveless Floor-Length Mermaid/Trumpet

BRANDS	Weddington Way

Silhouette	Mermaid/Trumpet

Neckline	Bateau

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/weddington-way/16199-weddington-way-dessy-2945.html](https://www.readybrides.com/en/weddington-way/16199-weddington-way-dessy-2945.html)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>PostgreSQL JDBC Contributors</title>
	<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8" />
	<meta name="description" content="The official site for the PostgreSQL JDBC Driver" />
	<meta name="copyright" content="The PostgreSQL Global Development Group" />

	<link rel="shortcut icon" href="/media/favicon.ico" />

			Skip site navigation (1)
			Skip section navigation (2)

					<form action="https://www.google.com/search" method="get">
						<input value="jdbc.postgresql.org" name="sitesearch" type="hidden" />
						<input id="q" name="q" type="text" size="20" maxlength="255" onfocus="if( this.value==this.defaultValue ) this.value='';" value="Google Search" accesskey="s" />

                    				<input name="Search" value="Search" type="submit" />
					</form>

						<map name="maplinks">
							<area shape="rect" coords="0,0,231,80" alt="PostgreSQL" href="https://postgresql.org" />
							<area shape="rect" coords="232,0,390,80" alt="PostgreSQL JDBC Driver" href="https://jdbc.postgresql.org" />
						</map>

Home

About

Download

Documentation

Community

Development

Community

Github

Contributors

Contributors

Maintainers

Previous Maintainers

Developers

Translators

Maintainers

							Please do not contact the maintainers directly unless you have
							a specific need to contact just them.  Please use the
							Github discussions
							if at all possible.

Dave Cramer

Vladimir Sitnikov

Sehrope Sarkuni

Brett Okken

Jorge Solórzano

Previous Maintainers

							The original JDBC driver was written by Adrian Hall.  Peter Mount
							and Barry Lind have maintained it in the past, but have
							since moved on to other things.
							We would also like to recognize the work previously done by the following

Kris Jurka

Oliver Jowett

Craig Ringer

Developers

							Most recent contributors can be found here

Translators

cs - Czech

Petr Dittrich

de - German

Andre Bialojahn

es - Spanish

Diego A. Gil

fr - French

Xavier Poinsard

it - Italian

Giuseppe Sacco

pl - Polish

Jaroslaw Pyszny

pt_BR - Brazilian Portuguese

Euler Taveira de Oliveira

ru - Russian

Serguei Mokhov

sr - Serbian

Bojan Skaljac

tr - Turkish

Devrim Gunduz

Nicolai Tufar

zh_CN - Simplified Chinese

Weiping

Kuo ChaoYi

zh_TW - Traditional Chinese

Zhenbang Wei

Kuo ChaoYi

				Privacy Policy |
				About PostgreSQL

				Copyright © 1996-2022 The PostgreSQL Global Development Group


text:
<?php

namespace Placeburger\Services\Burger;

use Placeburger\Domain\Burger;

interface ToFilenameConverter
{
    public function convert(Burger $burger): string;
}


text:
import React, { Component, PropTypes } from 'react';
import Home from '../../components/Home/Home';

const propTypes = {

};
const defaultProps = {

};
class HomeContainer extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return(
            <div>
              <Home/>
            </div>
        );
    }
}

HomeContainer.propTypes = propTypes;
HomeContainer.defaultProps = defaultProps;

export default HomeContainer;


text:
using System.Collections.Generic;
using System.Linq;
using CleanKludge.Api.Responses.Articles;
using CleanKludge.Core.Articles.Extensions;

namespace CleanKludge.Core.Articles
{
    public class GroupedSummaries
    {
        private readonly Dictionary<string, List<ArticleSummary>> _articles;
        private readonly Grouping _grouping;

        public static GroupedSummaries From(List<ArticleSummary> articles, Grouping grouping)
        {
            var result = new Dictionary<string, List<ArticleSummary>>();

            foreach (var item in articles)
            {
                var keys = item.KeysFor(grouping);
                foreach(var key in keys)
                {
                    if (!result.ContainsKey(key))
                        result.Add(key, new List<ArticleSummary>());

                    result[key].Add(item);
                }
            }

            return new GroupedSummaries(result, grouping);
        }

        private GroupedSummaries(Dictionary<string, List<ArticleSummary>> articles, Grouping grouping)
        {
            _articles = articles;
            _grouping = grouping;
        }

        public GroupedSummariesResponse ToResponse()
        {
            var columns = new List<Dictionary<string, List<SummaryResponse>>>();
            foreach (var group in _articles)
            {
                if (columns.Count == 0 || columns.Last().Count == 3)
                    columns.Add(new Dictionary<string, List<SummaryResponse>>());

                columns.Last().Add(group.Key, group.Value.Select(x => x.ToResponse()).ToList());
            }

            return new GroupedSummariesResponse
            {
                GroupedBy = _grouping.ToGroupedBy(),
                Groups = columns
            };
        }
    }
}


text:
package com.tectonica.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An {@link Iterator} for going over a result set row-by-row. It does not use the {@link ResultSet#isLast()} method, which isn't
 * implemented by all JDBC providers. Instead, it performs a read-ahead mechanism which is practically costless when scanning the entire
 * result set. When constructed from a combination of a {@link ResultSet} and {@link Connection}, it will also close the associated
 * connection after the last row has been retrieved.
 *
 * @author Zach Melamed
 */
public class ResultSetIterator implements Iterator<ResultSet>
{
	public final Connection conn;
	public final ResultSet rs;
	private boolean nextFound = false;

	public ResultSetIterator(ResultSet rs)
	{
		this.conn = null;
		this.rs = rs;
	}

	public ResultSetIterator(ResultSet rs, Connection conn)
	{
		this.conn = conn;
		this.rs = rs;
	}

	@Override
	public boolean hasNext()
	{
		if (!nextFound)
		{
			try
			{
				nextFound = rs.next();
			}
			catch (SQLException e)
			{
				throw new RuntimeException(e);
			}

			// auto close connection if applicable
			if (!nextFound && (conn != null))
			{
				try
				{
					conn.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace(); // not a critical error
				}
			}
		}
		return nextFound;
	}

	@Override
	public ResultSet next()
	{
		if (!hasNext())
			throw new NoSuchElementException();
		nextFound = false;
		return rs;
	}

	@Override
	public void remove()
	{
		try
		{
			rs.deleteRow();
		}
		catch (SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
}


text:
<?php

namespace mako\reactor\io;

use \mako\reactor\io\StdErr;
use \Symfony\Component\Console\Helper\ProgressHelper;

/**
 * Reactor output.
 *
 * @author  Frederic G. Østby
 */

class Output extends \mako\reactor\io\StdOut
{
	/**
	 * StdErr instance.
	 *
	 * @var \mako\reactor\io\StdErr;
	 */

	protected $stderr;

	/**
	 * Constructor.
	 *
	 * @access  public
	 */

	public function __construct()
	{
		parent::__construct();

		$this->stderr = new StdErr();
	}

	/**
	 * Returns the stderr instance.
	 *
	 * @access  public
	 * @return  \mako\reactor\io\StdErr
	 */

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

	/**
	 * Output an error message to stderr.
	 *
	 * @access  public
	 * @param   string  $message  Error message
	 */

	public function error($message)
	{
		$this->stderr->writeln('<red>' . $message . '</red>');
	}

	/**
	 * Clears the screen.
	 *
	 * @access  public
	 */

	public function clearScreen()
	{
		if(MAKO_IS_WINDOWS)
		{
			$this->nl(50);
		}
		else
		{
			$this->write("\033[H\033[2J");
		}
	}

	/**
	 * Sytem Beep.
	 *
	 * @access  public
	 * @param   int     $beeps  (optional) Number of system beeps
	 */

	public function beep($beeps = 1)
	{
		$this->write(str_repeat("\x07", $beeps));
	}

	/**
	 * Returns a progress helper.
	 *
	 * @access  public
	 * @param   int                                               $itemCount   Number of items
	 * @param   int                                               $redrawRate  (optional) Redraw rate
	 * @return  \Symfony\Component\Console\Helper\ProgressHelper
	 */

	public function progress($itemCount, $redrawRate = null)
	{
		$progress = new ProgressHelper();

		// Set redraw frequency

		$progress->setRedrawFrequency(max($redrawRate ?: ceil(0.01 * $itemCount), 1));

		// Set stome styles

		$progress->setFormat(ProgressHelper::FORMAT_VERBOSE);

		$progress->setBarCharacter('<green>=</green>');

		$progress->setEmptyBarCharacter('<red>-</red>');

		$progress->setProgressCharacter('|');

		// Start, display and return progress helper instance

		$progress->start($this, $itemCount);

		$progress->display();

		return $progress;
	}
}


text:
using UnityEngine;

namespace Assets.External.NData.NDataExamples.MasterPath {
    public class Preferences : EZData.Context
    {
        #region Property FillPercent
        private readonly EZData.Property<int> _privateFillPercentProperty = new EZData.Property<int>(75);
        public EZData.Property<int> FillPercentProperty { get { return _privateFillPercentProperty; } }
        public int FillPercent
        {
            get    { return FillPercentProperty.GetValue();    }
            set    { FillPercentProperty.SetValue(value); }
        }
        #endregion

        #region Property SwitchState
        private readonly EZData.Property<bool> _privateSwitchStateProperty = new EZData.Property<bool>(true);
        public EZData.Property<bool> SwitchStateProperty { get { return _privateSwitchStateProperty; } }
        public bool SwitchState
        {
            get    { return SwitchStateProperty.GetValue();    }
            set    { SwitchStateProperty.SetValue(value); }
        }
        #endregion
    }

    public class Options : EZData.Context
    {
        public Preferences Preferences { get; private set; }
        public Options() { Preferences = new Preferences(); }
    }

    public class Settings : EZData.Context
    {
        public Options Options { get; private set; }
        public Settings() { Options = new Options(); }
    }

    public class Game : EZData.Context
    {
        public Settings Settings { get; private set; }
        public Game() { Settings = new Settings(); }
    }

    public class MasterPath : MonoBehaviour
    {
        public NguiRootContext View;
        public Game Context;

        void Awake()
        {
            Context = new Game();
            View.SetContext(Context);
        }
    }
}


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

<title>org.apache.nutch.webui.service Class Hierarchy (apache-nutch 2.3 API)</title>
<meta name="date" content="2015-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.nutch.webui.service

Package Hierarchies:

All Packages

Interface Hierarchy

org.apache.nutch.webui.service.CrawlService

org.apache.nutch.webui.service.NutchInstanceService

org.apache.nutch.webui.service.NutchService

org.apache.nutch.webui.service.SeedListService

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
bool isLeapYear ( int _year )
{
	if ( _year % 4 != 0 )
		return false;

	else if ( _year % 100 == 0 )
		return ( _year % 400 == 0 );

	else
		return true;
}

int getDaysInYear ( int _year )
{
	return isLeapYear( _year ) ? 366 : 365;
}

int getYear ( time_t _currentTime )
{
	const int SECONDS_IN_DAY = 24 * 3600;

	int currentYear = 1970;

	while ( true )
	{
		int secondsInCurrentYear = getDaysInYear( currentYear ) * SECONDS_IN_DAY;
		if ( _currentTime < secondsInCurrentYear )
			return currentYear;

		else
		{
			++ currentYear;
			_currentTime -= secondsInCurrentYear;
		}
	}

	return 0;
}

int main ()
{
	time_t currentTime;
	time( & currentTime );

	int year = getYear( currentTime );
	printf( "%d %s leap\n", year, isLeapYear( year ) ? "is" : "is not" );
}


text:
package org.drools.modelcompiler.builder.generator.visitor;

public interface DSLNode {
    void buildPattern();
}


text:
layout: member
title: Devon Goszkowicz
photo: new/devon.jpg
---


text:
var config = require("./config");
var socketio = require("./socketio");
var auth = require("./auth");

// Controllers
var viewController = require("../controllers/viewController");
var GifController = require("../controllers/GifController");
var userController = require("../controllers/UserController");
var roomController = require("../controllers/RoomController");
var userSettingsController = require("../controllers/UserSettingsController");
var messageController = require("../controllers/MessageController");
var externalNotificationsController = require("../controllers/ExternalNotificationsController");

// Policies
var isLoggedIn = require("../policies/isLoggedIn");

module.exports.http = function(app) {
	// Public
	app.get("/login", viewController.login);
	app.get("/loginBasic", viewController.loginBasic);
	app.get("/logout", viewController.logout);
	app.get("/gif/:search?", GifController.index);

	// Internal views
	app.get("/", isLoggedIn, viewController.index);

	// Version 2 (react) available on /2
	// Note it uses a catchall route to enable route params without #
	app.get("/v2*", (req, res) => res.redirect("/2"));
	app.get("/2*", isLoggedIn, viewController.version2);
	app.get("/debug", isLoggedIn, viewController.debug);

	// External Notifications
	app.post("/externalnotifications/jenkinsBestBuy", externalNotificationsController.jenkinsBestBuy);
	app.post("/externalnotifications/serverStatus", externalNotificationsController.serverStatus);

	// Api
	app.get("/api/message/emoticoncounts", messageController.emoticonCounts);

	// Basic Login
	app.post("/api/user/loginbasic", auth.authenicateLocal);

	// proxy images
	app.get("/api/image/:imgurl", viewController.image);
};

module.exports.socketio = function(socket) {
	log.info("socket connection", socket.id);

	// init
	socket.on("/init", socketToController(userController.init));

	// user
	socket.on("/user/current/activity", socketToController(userController.activity));
	socket.on("/user/current/typing", socketToController(userController.typing));
	socket.on("/user/current/present", socketToController(userController.present));

	socket.on("/user/current/markInboxRead", socketToController(userController.markInboxRead));
	socket.on("/user/current/clearInbox", socketToController(userController.clearInbox));
	socket.on("/user/current/ping", socketToController(userController.ping));

	// user settings
	socket.on("/usersettings/save", socketToController(userSettingsController.save));

	// room
	socket.on("/room", socketToController(roomController.create));
	socket.on("/room/join", socketToController(roomController.join));
	socket.on("/room/leave", socketToController(roomController.leave));
	socket.on("/room/message", socketToController(roomController.message));
	socket.on("/room/messages", socketToController(roomController.messages));
	socket.on("/room/history", socketToController(roomController.history));

	// roommember
	socket.on("/roommember/updateSettings", socketToController(userSettingsController.saveRoomMember));

	// message
	socket.on("/message/edit", socketToController(messageController.update));
	socket.on("/message/reaction", socketToController(messageController.toggleReaction));
	socket.on("/message/emoticoncounts", socketToController(messageController.emoticonCounts));

	// pins
	socket.on("/room/pinMessage", socketToController(roomController.pinMessage));
	socket.on("/room/unPinMessage", socketToController(roomController.unPinMessage));

	// search
	socket.on("/search", socketToController(roomController.search));
};

function socketToController(controllerFn) {
	return function(data, cb) {
		var req = {
			socket: this,
			io: socketio.io,
			session: this.handshake.session,
			body: data || {}
		};

		var res = {
			ok: function(returnData) {
				if (_.isFunction(cb) && returnData) cb(returnData);
			},
			serverError: function(err) {
				log.error("server error", err);
				if (_.isFunction(cb)) cb({ serverErrorMessage: err.message });
			},
			badRequest: function(err) {
				if (_.isFunction(cb)) cb({ serverErrorMessage: err.message });
			}
		};
		controllerFn(req, res);
	};
}


text:
"""

This script is responsible for enabling reduced transparency

Commands used:

- defaults write com.apple.universalaccess reduceTransparency -bool true

"""

from common import CLITieIn

class ReducedTransparencyEnabler(CLITieIn):
    def enable_reduced_transparency(self):
        command = '/usr/bin/defaults write com.apple.universalaccess reduceTransparency -bool true'
        command_output = self.command(command)

        if command_output.error_level != 0:
            self._logger.error(
                '{0} failed stating {1}'.format(
                    command, command_output
                )
            )
            return False

        return True

    def restart_dock(self):
        command = '/usr/bin/pkill -9 -f Dock.app'
        command_output = self.command(command)

        if command_output.error_level != 0:
            self._logger.error(
                '{0} failed stating {1}'.format(
                    command, command_output
                )
            )
            return False

        return True

    def run(self):
        if not self.enable_reduced_transparency():
            self._logger.error('failed enable_reduced_transparency; cannot continue')
            return False

        if not self.restart_dock():
            self._logger.error('failed enable_reduced_transparency; cannot continue')
            return False

        self._logger.debug('passed')
        return True

if __name__ == '__main__':
    from utils import get_argparser, get_args

    parser = get_argparser()

    args = get_args(parser)

    actor = ReducedTransparencyEnabler(
        sudo_password=args.sudo_password,
    )

    result = actor.run()

    if not result:
        exit(1)

    exit(0)


text:
Find the closest vertex and coordinate of a geometry to a point.

![Nearest vertex](nearest-vertex.png)

## Use case

Determine the shortest distance between a location and the boundary of an area. For example, developers can snap imprecise user taps to a geometry if the tap is within a certain distance of the geometry.

## How to use the sample

Tap anywhere on the map. An orange cross will show at that location. A blue circle will show the polygon's nearest vertex to the point that was tapped. A red diamond will appear at the coordinate on the geometry that is nearest to the point that was tapped. If tapped inside the geometry, the red and orange markers will overlap. Tap again to dismiss the callout. The information callout showing distance between the tapped point and the nearest vertex/coordinate will be updated with every new location tapped.

## How it works

1. Get an `AGSGeometry` and an `AGSPoint` to check the nearest vertex against.
2. Call `class AGSGeometryEngine.nearestVertex(in:to:)`.
3. Use the returned `AGSProximityResult` to get the `AGSPoint` representing the polygon vertex, and to determine the distance between that vertex and the tapped point.
4. Call `class AGSGeometryEngine.nearestCoordinate(in:to:)`.
5. Use the returned `AGSProximityResult` to get the `AGSPoint` representing the coordinate on the polygon, and to determine the distance between that coordinate and the tapped point.

## Relevant API

* AGSGeometry
* AGSProximityResult
* class AGSGeometryEngine.nearestCoordinate(in:to:)
* class AGSGeometryEngine.nearestVertex(in:to:)
* class AGSGeometryEngine.normalizeCentralMeridian(of:)

## Additional information

The value of `AGSProximityResult.distance` is planar (Euclidean) distance. Planar distances are only accurate for geometries that have a defined projected coordinate system, which maintain the desired level of accuracy. The example polygon in this sample is defined in California State Plane Coordinate System - Zone 5 (WKID 2229), which maintains accuracy near Southern California. Accuracy declines outside the state plane zone.

## Tags

analysis, coordinate, geometry, nearest, proximity, vertex


text:
package forceengine.input;

import java.awt.event.InputEvent;

public class ToggleState implements Action, BiState {
	public boolean state;

	public ToggleState(){
		state = false;
	}

	public ToggleState(boolean initalState){
		state = initalState;
	}

	@Override
	public void act(int action, InputEvent event) {
		if(action == Action.PRESSED)
			state = !state;
	}

	@Override
	public boolean getState() {
		return state;
	}

	@Override
	public void setState(boolean state) {
		this.state = state;
	}

}


text:
Fuel
====

Dead simple dependency injection and inversion of control for javascript.

#### Why
Because inversion of control containers and dependency injection is more flexible than the service locator pattern, which for some reason seems to be the standard for javascript.

## Examples

```javascript
var Fuel = require("fuel");
var fuel = new Fuel();

// register some value types
fuel
.value("connectionString", "mongo://localhost/something")
.value("maxDbConnections", 100)
.value("emailFromAddress", "test@test.com");

// register a factory with injected parameters
fuel.factory("databaseConnector", function(connectionString, maxDbConnections) {
  return function(connectCallback) {
    ConnectToDatabase(connectionString, maxDbConnections, connectionCallback);
  }
});

// register a function
fuel.func("testFunction", function(emailFromAddress) {
  return "from: " + emailFromAddress;
});

// get a value
var dbConnections = fuel.get("maxDbConnections");

// factory
var connector = fuel.get("databaseConnector");
connector(function() {
  console.log("connected to database!");
});

// get a function, but don't inject and bind parameters
var f = fuel.get("testFunction", false);
var result = f("anotherEmail@test.com"); // == "from: anotherEmail@test.com"

```

#### Contributing
Pull requests are more than welcome. Please provide a detailed description of added or fixed funcitonality in your pull request. New features and bugfixes **must** come with test cases.


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

<title>HandshakeImpl1Client</title>
<meta name="date" content="2014-07-23">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.java_websocket.handshake

Class HandshakeImpl1Client

java.lang.Object

org.java_websocket.handshake.HandshakedataImpl1

org.java_websocket.handshake.HandshakeImpl1Client

All Implemented Interfaces:

ClientHandshake, ClientHandshakeBuilder, HandshakeBuilder, Handshakedata

public class HandshakeImpl1Client
extends HandshakedataImpl1
implements ClientHandshakeBuilder

Constructor Summary

Constructors

Constructor and Description

HandshakeImpl1Client()

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getResourceDescriptor()

returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2

void
setResourceDescriptor(java.lang.String resourceDescriptor)

Methods inherited from class org.java_websocket.handshake.HandshakedataImpl1

getContent, getFieldValue, hasFieldValue, iterateHttpFields, put, setContent

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface org.java_websocket.handshake.HandshakeBuilder

put, setContent

Methods inherited from interface org.java_websocket.handshake.Handshakedata

getContent, getFieldValue, hasFieldValue, iterateHttpFields

Constructor Detail

HandshakeImpl1Client

public HandshakeImpl1Client()

Method Detail

setResourceDescriptor

public void setResourceDescriptor(java.lang.String resourceDescriptor)
                           throws java.lang.IllegalArgumentException

Specified by:

setResourceDescriptor in interface ClientHandshakeBuilder

Throws:

java.lang.IllegalArgumentException

getResourceDescriptor

public java.lang.String getResourceDescriptor()

Description copied from interface: ClientHandshake

returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2

Specified by:

getResourceDescriptor in interface ClientHandshake

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require File.dirname(__FILE__) + '/authorization.rb'

module Authorization
  # Provides a few maintenance methods for modifying data without enforcing
  # authorization.
  module Maintenance
    # Disables access control for the given block.  Appropriate for
    # maintenance operation at the Rails console or in test case setup.
    #
    # For use in the Rails console:
    #  require "vendor/plugins/declarative_authorization/lib/maintenance"
    #  include Authorization::Maintenance
    #
    #  without_access_control do
    #    SomeModel.find(:first).save
    #  end
    def without_access_control (&block)
      Authorization::Maintenance.without_access_control(&block)
    end

    # A class method variant of without_access_control.  Thus, one can call
    #  Authorization::Maintenance::without_access_control do
    #    ...
    #  end
    def self.without_access_control
      previous_state = Authorization.ignore_access_control
      begin
        Authorization.ignore_access_control(true)
        yield
      ensure
        Authorization.ignore_access_control(previous_state)
      end
    end

    # Sets the current user for the declarative authorization plugin to the
    # given one for the execution of the supplied block.  Suitable for tests
    # on certain users.
    def with_user (user, &block)
      Authorization::Maintenance.with_user(user, &block)
    end

    def self.with_user (user)
      prev_user = Authorization.current_user
      Authorization.current_user = user
      yield
    ensure
      Authorization.current_user = prev_user
    end

    # Module for grouping usage-related helper methods
    module Usage
      # Delivers a hash of {ControllerClass => usage_info_hash},
      # where usage_info_hash has the form of
      def self.usages_by_controller
        # load each application controller
        begin
          Dir.foreach(File.join(::Rails.root, %w{app controllers})) do |entry|
            if entry =~ /^\w+_controller\.rb$/
              require File.join(::Rails.root, %w{app controllers}, entry)
            end
          end
        rescue Errno::ENOENT
        end
        controllers = []
        ObjectSpace.each_object(Class) do |obj|
          controllers << obj if obj.ancestors.include?(ActionController::Base) and
                                !%w{ActionController::Base ApplicationController}.include?(obj.name)
        end

        controllers.inject({}) do |memo, controller|
          catchall_permissions = []
          permission_by_action = {}
          controller.all_filter_access_permissions.each do |controller_permissions|
            catchall_permissions << controller_permissions if controller_permissions.actions.include?(:all)
            controller_permissions.actions.reject {|action| action == :all}.each do |action|
              permission_by_action[action] = controller_permissions
            end
          end

          actions = controller.public_instance_methods(false) - controller.hidden_actions.to_a
          memo[controller] = actions.inject({}) do |actions_memo, action|
            action_sym = action.to_sym
            actions_memo[action_sym] =
              if permission_by_action[action_sym]
                {
                  :privilege => permission_by_action[action_sym].privilege,
                  :context   => permission_by_action[action_sym].context,
                  :controller_permissions => [permission_by_action[action_sym]]
                }
              elsif !catchall_permissions.empty?
                {
                  :privilege => catchall_permissions[0].privilege,
                  :context   => catchall_permissions[0].context,
                  :controller_permissions => catchall_permissions
                }
              else
                {}
              end
            actions_memo
          end
          memo
        end
      end
    end
  end

  # TestHelper provides assert methods and controller request methods which
  # take authorization into account and set the current user to a specific
  # one.
  #
  # Defines get_with, post_with, get_by_xhr_with etc. for methods
  # get, post, put, delete each with the signature
  #   get_with(user, action, params = {}, session = {}, flash = {})
  #
  # Use it by including it in your TestHelper:
  #  require File.expand_path(File.dirname(__FILE__) +
  #    "/../vendor/plugins/declarative_authorization/lib/maintenance")
  #  class Test::Unit::TestCase
  #    include Authorization::TestHelper
  #    ...
  #
  #    def admin
  #      # create admin user
  #    end
  #  end
  #
  #  class SomeControllerTest < ActionController::TestCase
  #    def test_should_get_index
  #      ...
  #      get_with admin, :index, :param_1 => "param value"
  #      ...
  #    end
  #  end
  #
  # Note: get_with etc. do two things to set the user for the request:
  # Authorization.current_user is set and session[:user], session[:user_id]
  # are set appropriately.  If you determine the current user in a different
  # way, these methods might not work for you.
  module TestHelper
    include Authorization::Maintenance

    # Analogue to the Ruby's assert_raise method, only executing the block
    # in the context of the given user.
    def assert_raise_with_user (user, *args, &block)
      assert_raise(*args) do
        with_user(user, &block)
      end
    end

    # Test helper to test authorization rules.
    #   with_user a_normal_user do
    #     should_not_be_allowed_to :update, :conferences
    #     should_not_be_allowed_to :read, an_unpublished_conference
    #     should_be_allowed_to :read, a_published_conference
    #   end
    #
    # If the objects class name does not match the controller name, you can set the object and context manually
    #   should_be_allowed_to :create, :object => car, :context => :vehicles
    #
    # If you use specify the object and context manually, you can also specify the user manually, skipping the with_user block:
    #   should_be_allowed_to :create, :object => car, :context => :vehicles, :user => a_normal_user
    def should_be_allowed_to (privilege, *args)
      options = {}
      if(args.first.class == Hash)
        options = args.extract_options!
      else
        options[args[0].is_a?(Symbol) ? :context : :object] = args[0]
      end
      assert_nothing_raised do
        Authorization::Engine.instance.permit!(privilege, options)
      end
    end

    # See should_be_allowed_to
    def should_not_be_allowed_to (privilege, *args)
      options = {}
      if(args.first.class == Hash)
        options = args.extract_options!
      else
        options[args[0].is_a?(Symbol) ? :context : :object] = args[0]
      end
      assert !Authorization::Engine.instance.permit?(privilege, options)
    end

    def request_with (user, method, xhr, action, params = {},
        session = {}, flash = {})
      session = session.merge({:user => user, :user_id => user && user.id})
      with_user(user) do
        if xhr
          xhr method, action, params, session, flash
        else
          send method, action, params, session, flash
        end
      end
    end

    def self.included (base)
      [:get, :post, :put, :delete].each do |method|
        base.class_eval <<-EOV, __FILE__, __LINE__
          def #{method}_with (user, *args)
            request_with(user, #{method.inspect}, false, *args)
          end

          def #{method}_by_xhr_with (user, *args)
            request_with(user, #{method.inspect}, true, *args)
          end
        EOV
      end
    end
  end
end


text:
<?php

class qCal_Property_Attendee extends qCal_Property {

	protected $type = 'CAL-ADDRESS';
	// If I'm reading the RFC correctly above, this property can be specified
	// on the following components, but I'm still a bit confused about it. I
	// need to read up on it more to really understand
	protected $allowedComponents = array('VEVENT','VTODO','VJOURNAL','VALARM');
	protected $allowMultiple = true;

}


text:
module HL7
  module Segment
    class MSH < Base
      # NOTE: HL7 specifies the "Field Separator" on MSH segment as first field.
      # But actually it is NOT a field, so we don't define it as such.
      field :encoding_characters, default: '^~\&'
      field :sending_application, default: 'Mowoli'
      field :sending_facility
      field :receiving_application
      field :receiving_facility
      field :datetime_of_message, type: DateTime
      field :security
      field :message_type, default: 'ORM^O01^ORM_O01'
      field :message_control_id, default: ->{ SecureRandom.hex(10) }
      field :processing_id
      field :version_id, default: '2.3'
      field :sequence_number
      field :continuation_pointer
      field :accept_acknowledge_type
      field :application_acknowledge_type
      field :country_code
      field :character_set
      field :principal_language_of_message
      field :alternate_character_set_handling_scheme
      field :message_profile_id
    end
  end
end


text:
require 'spec_helper'

module Merb::Test
  class GeneratorSpecGenerator < Merb::Generators::Generator
    source_paths << File.expand_path('fixtures', File.dirname(__FILE__))

    def create_with_modules_spec
      template 'templates/no_modules.test'
      template 'templates/some_modules.test'
    end
  end
end

describe Merb::Generators::Generator do
  before :all do
    @generator = create_generator(Merb::Test::GeneratorSpecGenerator, temp_app_name)
  end

  after_generator_spec

  it_should_generate :create_with_modules_spec

  describe "#go_up" do
    it "should output an empty string for argument 0" do
      @generator.go_up(0).should == ""
    end

    it "should output a single '..' for argument 1" do
      @generator.go_up(1).should == "'..'"
    end

    it "should concatenate multiple '..' for other arguments" do
      @generator.go_up(3).should == "'..', '..', '..'"
    end
  end

  describe "#with_modules" do
    it_should_create(
      'templates/no_modules.test',
      'templates/some_modules.test'
    )

    it "should be correct for no module" do
      File.read(app_path('templates/no_modules.test')).should == File.read(File.expand_path('fixtures/results/no_modules.test', File.dirname(__FILE__)))
    end

    it "should be correct for some module" do
      File.read(app_path('templates/some_modules.test')).should == File.read(File.expand_path('fixtures/results/some_modules.test', File.dirname(__FILE__)))
    end
  end

end


text:
/** Automatically generated file. DO NOT MODIFY */
package org.sandholm.max.birdgame;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
package org.olat.presentation.framework.core.control.generic.textmarker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.olat.lms.commons.mediaresource.MediaResource;
import org.olat.lms.commons.mediaresource.StringMediaResource;
import org.olat.lms.glossary.GlossaryDataObjectEBL;
import org.olat.lms.glossary.GlossaryEBL;
import org.olat.presentation.framework.dispatcher.mapper.Mapper;
import org.olat.system.logging.log4j.LoggerHelper;
import org.olat.system.spring.CoreSpringFactory;

/**
 * Description:

 * delivers a js-file with all Terms as Arrays
 *

 * Initial Date: 12.03.2009

 *
 * @author Roman Haag, frentix GmbH, roman.haag@frentix.com
 */
class GlossaryTermMapper implements Mapper {

    private static final Logger log = LoggerHelper.getLogger();

    /**
	 */
    @Override
    public MediaResource handle(String relPath, HttpServletRequest request) {

        GlossaryDataObjectEBL glossaryDataObjectEBL = getGlossaryEBL().processGlossaryTermRelativePath(relPath);

        if (glossaryDataObjectEBL.isNotFoundMediaResource()) {
            return glossaryDataObjectEBL.getNotFoundMediaResource();
        }

        // Create a media resource
        StringMediaResource resource = new StringMediaResource() {
            @Override
            public void prepare(HttpServletResponse hres) {
                // don't use normal string media headers which prevent caching,
                // use standard browser caching based on last modified timestamp
            }
        };

        resource.setLastModified(glossaryDataObjectEBL.getLastModifiedTime());
        resource.setContentType("text/javascript");
        // Get data
        String glossaryArrayData = TextMarkerJsGenerator.loadGlossaryItemListAsJSArray(glossaryDataObjectEBL.getGlossaryFolder());

        resource.setData(glossaryArrayData);
        // UTF-8 encoding used in this js file since explicitly set in the ajax
        // call (usually js files are 8859-1)
        resource.setEncoding("utf-8");
        return resource;
    }

    private GlossaryEBL getGlossaryEBL() {
        return CoreSpringFactory.getBean(GlossaryEBL.class);
    }

}