text:
/*
 * modified July 9, 1999 by mark gates <mgates@nlanr.net>
 *          Dec 17, 1999
 *
 * renamed all functions and variables by prepending "gnu_"
 * removed/redid a bunch of stuff under the assumption we're
 *   using a modern standard C compiler.
 *
 * $Id: gnu_getopt.h,v 1.1.1.1 2004/05/18 01:50:44 kgibbs Exp $
 */

#ifndef _GETOPT_H
    #define _GETOPT_H 1

    #ifdef	__cplusplus
extern "C" {
#endif

/* For communication from `gnu_getopt' to the caller.
   When `gnu_getopt' finds an option that takes an argument,
   the argument value is returned here.
   Also, when `ordering' is RETURN_IN_ORDER,
   each non-option ARGV-element is returned here.  */

extern char *gnu_optarg;

/* Index in ARGV of the next element to be scanned.
   This is used for communication to and from the caller
   and for communication between successive calls to `gnu_getopt'.

   On entry to `gnu_getopt', zero means this is the first call; initialize.

   When `gnu_getopt' returns -1, this is the index of the first of the
   non-option elements that the caller should itself scan.

   Otherwise, `gnu_optind' communicates from one call to the next
   how much of ARGV has been scanned so far.  */

extern int gnu_optind;

/* Callers store zero here to inhibit the error message `gnu_getopt' prints
   for unrecognized options.  */

extern int gnu_opterr;

/* Set to an option character which was unrecognized.  */

extern int gnu_optopt;

/* Describe the long-named options requested by the application.
   The LONG_OPTIONS argument to gnu_getopt_long or getopt_long_only is a vector
   of `struct option' terminated by an element containing a name which is
   zero.

   The field `has_arg' is:
   no_argument		(or 0) if the option does not take an argument,
   required_argument	(or 1) if the option requires an argument,
   optional_argument 	(or 2) if the option takes an optional argument.

   If the field `flag' is not NULL, it points to a variable that is set
   to the value given in the field `val' when the option is found, but
   left unchanged if the option is not found.

   To have a long-named option do something other than set an `int' to
   a compiled-in constant, such as set a value from `gnu_optarg', set the
   option's `flag' field to zero and its `val' field to a nonzero
   value (the equivalent single-letter option character, if there is
   one).  For long options that have a zero `flag' field, `gnu_getopt'
   returns the contents of the `val' field.  */

/* has_arg can't be an enum because some compilers complain about
   type mismatches in all the code that assumes it is an int.  */

struct option {
    const char *name;
    int has_arg;
    int *flag;
    int val;
};

/* Names for the values of the `has_arg' field of `struct option'.  */

#define	no_argument		    0
#define required_argument	1
#define optional_argument	2

int gnu_getopt( int argc,
                char *const *argv,
                const char *shortopts );

int gnu_getopt_long( int argc,
                     char *const *argv,
                     const char *shortopts,
                     const struct option *longopts,
                     int *longind );

int gnu_getopt_long_only( int argc,
                          char *const *argv,
                          const char *shortopts,
                          const struct option *longopts,
                          int *longind );

/* Internal only.  Users should not call this directly.  */
int _gnu_getopt_internal( int argc,
                          char *const *argv,
                          const char *shortopts,
                          const struct option *longopts,
                          int *longind,
                          int long_only );

#ifdef	__cplusplus
} /* end extern "C" */
    #endif

#endif /* _GETOPT_H */


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="robots" content="noodp,noydir"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="referrer" content="default" id="meta_referrer"/>

            <meta http-equiv="X-Frame-Options" content="DENY">

        <meta name="description" content="Claudio Ludovico Panetta, Francesco Panetta, Shani Sebastian Panetta, Vittoria Capitale, Lucrezia Maria Panetta, Margherita Sofia Panetta"/>
        <link rel="stylesheet" href="public/css/normalize.css" media="screen" title="no title" charset="utf-8">
        <link rel="stylesheet" href="public/css/panetta.css" media="screen" title="no title" charset="utf-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
        <title>Panetta Family</title>

{{ member.name + " " + member.surname }}

{{ member.description }}

redpajama_set_name: RedPajamaGithub


text:
package me.donniesky.dailypaper.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import me.donniesky.dailypaper.ui.fragment.SectionFragment;
import me.donniesky.dailypaper.ui.fragment.ThemeFragment;
import me.donniesky.dailypaper.ui.fragment.TopicFragment;

/**
 * Created by Mysim on 2016/6/22.
 */
public class TabPagerAdapter extends FragmentPagerAdapter {

    private String[] titles = {"发现","主题日报","栏目"};

    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = TopicFragment.newInstance(position);
                break;
            case 1:
                fragment = ThemeFragment.newInstance();
                break;
            case 2:
                fragment = SectionFragment.newInstance();
                break;
        }

        return fragment;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}


text:
"""
A quick example of viewing data stored in a geoprobe volume file.
"""
from __future__ import print_function
import os

import numpy as np
import matplotlib.pyplot as plt

import geoprobe

def main():
    # Path to the example data dir relative to the location of this script.
    # This is just so that the script can be called from a different directory
    datadir = os.path.join(os.path.dirname(__file__), 'data')

    # Read an existing geoprobe volume
    vol = geoprobe.volume(os.path.join(datadir, 'Volumes', 'example.vol'))

    # Print some info
    print_info(vol)

    # Example plots
    plot(vol)

def plot(vol):
    """Plot the first inline and first crossline in "vol", a geoprobe.volume
    instance."""
    # Plot the first inline in the volume
    fig, ax = plt.subplots()
    ax.imshow(vol.XSlice(vol.xmin))
    # Note: instead of vol.XSlice, we could have used vol.data[0,:,:].T
    ax.set(title='Inline %i' % vol.xmin)

    # Plot the first crossline in the volume
    fig, ax = plt.subplots()
    ax.imshow(vol.YSlice(vol.ymin))
    # Note: instead of vol.YSlice, we could have used vol.data[:,0,:].T
    ax.set(title='Crossline %i' % vol.ymin)

    plt.show()

def print_info(vol):
    """Print some basic information about "vol", a geoprobe.volume instance."""
    # Print out some basic information
    print('The volume has dimensions of (nx, ny, nz):', vol.nx, vol.ny, vol.nz)
    print('The inline coordinates range from', vol.xmin, 'to', vol.xmax)
    print('The inline spacing is:', vol.dxW, 'world units')
    print('The crossline coordinates range from', vol.ymin, 'to', vol.ymax)
    print('The crossline spacing is:', vol.dyW, 'world units')
    print('The depth/time coordinates range from', vol.zmin, 'to', vol.zmax)

    # Determine the locations of the corners
    print('The world coordinates of the corners of the volume are:')
    print('    Lower-left:', vol.model2world(vol.xmin, vol.ymin))
    print('    Upper-left:', vol.model2world(vol.xmin, vol.ymax))
    print('    Upper-right:', vol.model2world(vol.xmax, vol.ymax))
    print('    Lower-right:', vol.model2world(vol.xmax, vol.ymin))

if __name__ == '__main__':
    main()


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecoveryServices.Tests.Helpers
{
    public class CommonTestHelper
    {
        public static string GetSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public static CustomRequestHeaders GetCustomRequestHeaders()
        {
            return new CustomRequestHeaders()
            {
                ClientRequestId = Guid.NewGuid().ToString(),
            };
        }
    }
}


text:
class Base(object):
    """Constants used throughout the application.
    All hard coded settings/data that are not actual/official configuration options for Flask, Celery, or their
    extensions goes here.
    """
    ADMINS = ['me@me.test']
    ENVIRONMENT = property(lambda self: self.__class__.__name__)

class Testing(Base):
    """Default Flask configuration inherited by all environments. Use this for development environments."""
    DEBUG = True
    TESTING = True
    SECRET_KEY = "development_key"

class Production(Base):
    DEBUG = False
    TESTING = False
    SECRET_KEY = "production_key"


text:
package apps::backup::commvault::commserve::restapi::mode::alerts;

use base qw(centreon::plugins::templates::counter);

use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use POSIX;
use centreon::plugins::misc;
use centreon::plugins::statefile;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold_ng);

sub custom_status_output {
    my ($self, %options) = @_;

    return sprintf(
        'alert [severity: %s] [status: %s] [name: %s] [type: %s] %s',
        $self->{result_values}->{severity},
        $self->{result_values}->{status},
        $self->{result_values}->{name},
        $self->{result_values}->{type},
        $self->{result_values}->{generation_time}
    );
}

sub prefix_global_output {
    my ($self, %options) = @_;

    return 'Alerts ';
}

sub set_counters {
    my ($self, %options) = @_;

    $self->{maps_counters_type} = [
        { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output', },
        { name => 'alarms', type => 2, message_multiple => '0 alert(s) detected', display_counter_problem => { nlabel => 'alerts.problems.current.count', min => 0 },
          group => [ { name => 'alarm', skipped_code => { -11 => 1 } } ]
        }
    ];

    $self->{maps_counters}->{global} = [
        { label => 'alerts-total', nlabel => 'alerts.total.count', display_ok => 0, set => {
                key_values => [ { name => 'total' } ],
                output_template => 'total: %s',
                perfdatas => [
                    { template => '%s', min => 0 }
                ]
            }
        }
    ];

    foreach (('critical', 'warning', 'info')) {
        push @{$self->{maps_counters}->{global}},
            { label => 'alerts-' . $_, nlabel => 'alerts.' . $_ . '.count', display_ok => 0, set => {
                    key_values => [ { name => $_ }, { name => 'total' } ],
                    output_template => $_ . ': %s',
                    perfdatas => [
                        { template => '%s', min => 0, max => 'total' }
                    ]
                }
            };
    }

    $self->{maps_counters}->{alarm} = [
        {
            label => 'status',
            type => 2,
            warning_default => '%{severity} =~ /warning/',
            critical_default => '%{severity} =~ /critical/',
            set => {
                key_values => [
                    { name => 'name' }, { name => 'type' },
                    { name => 'severity' }, { name => 'status' },
                    { name => 'since' }, { name => 'generation_time' }
                ],
                closure_custom_output => $self->can('custom_status_output'),
                closure_custom_perfdata => sub { return 0; },
                closure_custom_threshold_check => \&catalog_status_threshold_ng
            }
        }
    ];
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'filter-alert-name:s' => { name => 'filter_alert_name' },
        'filter-alert-type:s' => { name => 'filter_alert_type' },
        'memory'              => { name => 'memory' }
    });

    $self->{statefile_cache} = centreon::plugins::statefile->new(%options);
    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::check_options(%options);

    if (defined($self->{option_results}->{memory})) {
        $self->{statefile_cache}->check_options(%options);
    }
}

my $map_severity = {
    0 => 'autoPick', 1 => 'critical',
    2 => 'warning', 3 => 'info'
};
my $map_status = {
    4 => 'read', 8 => 'unread'
};

sub manage_selection {
    my ($self, %options) = @_;

    my $alarms = $options{custom}->request_paging(
        type => 'alert',
        endpoint => '/Alert'
    );

    my $last_time;
    if (defined($self->{option_results}->{memory})) {
        $self->{statefile_cache}->read(
            statefile => 'commvault_commserve_' . $options{custom}->get_connection_infos() . '_' . $self->{mode} . '_' .
                (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
                (defined($self->{option_results}->{filter_alert_name}) ? md5_hex($self->{option_results}->{filter_alert_name}) : md5_hex('all')) . '_' .
                (defined($self->{option_results}->{filter_alert_type}) ? md5_hex($self->{option_results}->{filter_alert_type}) : md5_hex('all'))
        );
        $last_time = $self->{statefile_cache}->get(name => 'last_time');
    }

    $self->{global} = { total => 0, critical => 0, warning => 0, info => 0 };
    $self->{alarms} = { global => { alarm => {} } };
    my ($i, $current_time) = (1, time());
    foreach my $alarm (@$alarms) {
        my $create_time = $alarm->{detectedTime}->{time};
        next if (defined($self->{option_results}->{memory}) && defined($last_time) && $last_time > $create_time);

        if (defined($self->{option_results}->{filter_alert_name}) && $self->{option_results}->{filter_alert_name} ne '' &&
            $alarm->{alertName} !~ /$self->{option_results}->{filter_alert_name}/) {
            $self->{output}->output_add(long_msg => "skipping '" . $alarm->{alertName} . "': no matching filter.", debug => 1);
            next;
        }
        if (defined($self->{option_results}->{filter_alert_type}) && $self->{option_results}->{filter_alert_type} ne '' &&
            $alarm->{alertType} !~ /$self->{option_results}->{filter_alert_type}/) {
            $self->{output}->output_add(long_msg => "skipping '" . $alarm->{alertName} . "': no matching filter.", debug => 1);
            next;
        }

        my $diff_time = $current_time - $create_time;
        $self->{alarms}->{global}->{alarm}->{$i} = {
            name => $alarm->{alertName},
            type => $alarm->{alertType},
            severity => $map_severity->{ $alarm->{severity} },
            status => $map_status->{ $alarm->{status} },
            since => $diff_time,
            generation_time => centreon::plugins::misc::change_seconds(value => $diff_time)
        };
        $self->{global}->{total}++;
        $self->{global}->{ $map_severity->{ $alarm->{severity} } }++
            if (defined($self->{global}->{ $map_severity->{ $alarm->{severity} } }));
        $i++;
    }

    if (defined($self->{option_results}->{memory})) {
        $self->{statefile_cache}->write(data => { last_time => $current_time });
    }
}

1;

__END__

=head1 MODE

Check alerts.

=over 8

=item B<--filter-alert-name>

Filter alerts by name (can be a regexp).

=item B<--filter-alert-type>

Filter alerts by type (can be a regexp).

=item B<--warning-status>

Set warning threshold for status (Default: '%{severity} =~ /warning/')
Can used special variables like: %{severity}, %{status}, %{type}, %{name}, %{since}

=item B<--critical-status>

Set critical threshold for status (Default: '%{severity} =~ /critical/').
Can used special variables like: %{severity}, %{status}, %{type}, %{name}, %{since}

=item B<--memory>

Only check new alerts.

=back

=cut


text:
package com.facebook.litho.widget;

import static com.facebook.litho.widget.ViewportInfo.State.DATA_CHANGES;
import static com.facebook.litho.widget.ViewportInfo.State.SCROLLING;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import com.facebook.litho.testing.testrunner.LithoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Tests for {@link ViewportManager} */
@RunWith(LithoTestRunner.class)
public class ViewportManagerTest {

  private LayoutInfo mLayoutInfo;
  private ViewportInfo.ViewportChanged mViewportChangedListener;

  @Before
  public void setup() {
    mLayoutInfo = mock(LayoutInfo.class);
    mViewportChangedListener = mock(ViewportInfo.ViewportChanged.class);
  }

  @Test
  public void testOnViewportChangedWhileScrolling() {
    ViewportManager viewportManager = getViewportManager(0, 0);

    setVisibleItemPositionInMockedLayoutManager(0, 5);
    setFullyVisibleItemPositionInMockedLayoutManager(1, 4);
    setTotalItemInMockedLayoutManager(20);

    viewportManager.setShouldUpdate(false);
    viewportManager.onViewportChanged(SCROLLING);

    verify(mViewportChangedListener).viewportChanged(0, 5, 1, 4, SCROLLING);
  }

  @Test
  public void testOnViewportChangedWhileScrollingWithNoItemsFullyVisible() {
    ViewportManager viewportManager = getViewportManager(0, 0);

    // The second and third items are visible partially but neither is fully visible
    setVisibleItemPositionInMockedLayoutManager(1, 2);
    setFullyVisibleItemPositionInMockedLayoutManager(-1, -1);
    setTotalItemInMockedLayoutManager(20);

    viewportManager.setShouldUpdate(true);
    viewportManager.onViewportChanged(SCROLLING);

    verify(mViewportChangedListener).viewportChanged(1, 2, -1, -1, SCROLLING);
  }

  @Test
  public void testOnViewportChangedWithoutScrolling() {
    ViewportManager viewportManager = getViewportManager(5, 20);

    setVisibleItemPositionInMockedLayoutManager(5, 20);
    setFullyVisibleItemPositionInMockedLayoutManager(7, 18);
    setTotalItemInMockedLayoutManager(20);

    viewportManager.setShouldUpdate(true);
    viewportManager.onViewportChanged(DATA_CHANGES);

    verify(mViewportChangedListener).viewportChanged(5, 20, 7, 18, DATA_CHANGES);
  }

  @Test
  public void testNoViewportChangedWithScrolling() {
    setFullyVisibleItemPositionInMockedLayoutManager(7, 9);
    setTotalItemInMockedLayoutManager(13);

    ViewportManager viewportManager = getViewportManager(5, 10);

    setVisibleItemPositionInMockedLayoutManager(5, 10);
    setFullyVisibleItemPositionInMockedLayoutManager(7, 9);
    setTotalItemInMockedLayoutManager(13);

    viewportManager.setShouldUpdate(false);
    viewportManager.onViewportChanged(SCROLLING);

    verifyZeroInteractions(mViewportChangedListener);
  }

  @Test
  public void testTotalItemChangedWhileVisiblePositionsRemainTheSame() {
    setTotalItemInMockedLayoutManager(13);
    ViewportManager viewportManager = getViewportManager(5, 10);

    setVisibleItemPositionInMockedLayoutManager(5, 10);
    setFullyVisibleItemPositionInMockedLayoutManager(7, 9);
    setTotalItemInMockedLayoutManager(12);

    viewportManager.setShouldUpdate(true);
    viewportManager.onViewportChanged(DATA_CHANGES);

    verify(mViewportChangedListener).viewportChanged(5, 10, 7, 9, DATA_CHANGES);
  }

  @Test
  public void testTotalItemChangedWhileNoItemsFullyVisible() {
    setTotalItemInMockedLayoutManager(13);
    ViewportManager viewportManager = getViewportManager(5, 6);

    // The seventh and eighth items are visible partially but neither is fully visible
    setVisibleItemPositionInMockedLayoutManager(6, 7);
    setFullyVisibleItemPositionInMockedLayoutManager(-1, -1);
    setTotalItemInMockedLayoutManager(12);

    viewportManager.setShouldUpdate(false);
    viewportManager.onViewportChanged(SCROLLING);

    verify(mViewportChangedListener).viewportChanged(6, 7, -1, -1, SCROLLING);
  }

  @Test
  public void testInsertAffectsVisibleRange() {
    ViewportManager viewportManager = getViewportManager(5, 10);
    // fully above viewport
    assertThat(viewportManager.insertAffectsVisibleRange(1, 2, 5)).isTrue();
    // last insert within viewport
    assertThat(viewportManager.insertAffectsVisibleRange(1, 6, 5)).isTrue();
    // insert positions fully cover viewport
    assertThat(viewportManager.insertAffectsVisibleRange(1, 20, 5)).isTrue();
    // position within viewport
    assertThat(viewportManager.insertAffectsVisibleRange(5, 1, 5)).isTrue();
    assertThat(viewportManager.insertAffectsVisibleRange(7, 2, 5)).isTrue();
    // position within extended viewport
    assertThat(viewportManager.insertAffectsVisibleRange(11, 2, 7)).isTrue();
    // fully below viewport
    assertThat(viewportManager.insertAffectsVisibleRange(11, 2, 6)).isFalse();
    assertThat(viewportManager.insertAffectsVisibleRange(18, 2, 5)).isFalse();
  }

  @Test
  public void testUpdateAffectsVisibleRange() {
    ViewportManager viewportManager = getViewportManager(5, 10);
    // fully above viewport
    assertThat(viewportManager.updateAffectsVisibleRange(1, 2)).isFalse();
    // last update within viewport
    assertThat(viewportManager.updateAffectsVisibleRange(1, 6)).isTrue();
    // update positions fully cover viewport
    assertThat(viewportManager.updateAffectsVisibleRange(1, 20)).isTrue();
    // position within viewport
    assertThat(viewportManager.updateAffectsVisibleRange(5, 1)).isTrue();
    assertThat(viewportManager.updateAffectsVisibleRange(7, 2)).isTrue();
    // fully below viewport
    assertThat(viewportManager.updateAffectsVisibleRange(11, 2)).isFalse();
    assertThat(viewportManager.updateAffectsVisibleRange(18, 2)).isFalse();
  }

  @Test
  public void testMoveAffectsVisibleRange() {
    ViewportManager viewportManager = getViewportManager(5, 10);
    // either is within viewport
    assertThat(viewportManager.moveAffectsVisibleRange(12, 9, 6)).isTrue();
    assertThat(viewportManager.moveAffectsVisibleRange(9, 12, 6)).isTrue();
    // both is within viewport
    assertThat(viewportManager.moveAffectsVisibleRange(6, 7, 6)).isTrue();
    // neither is within viewport
    assertThat(viewportManager.moveAffectsVisibleRange(11, 13, 6)).isFalse();
    assertThat(viewportManager.moveAffectsVisibleRange(1, 3, 6)).isFalse();
  }

  @Test
  public void testRemoveAffectsVisibleRange() {
    ViewportManager viewportManager = getViewportManager(5, 10);
    // fully above viewport
    assertThat(viewportManager.removeAffectsVisibleRange(1, 2)).isTrue();
    // last remove within viewport
    assertThat(viewportManager.removeAffectsVisibleRange(1, 6)).isTrue();
    // remove positions fully cover viewport
    assertThat(viewportManager.removeAffectsVisibleRange(1, 20)).isTrue();
    // position within viewport
    assertThat(viewportManager.removeAffectsVisibleRange(5, 1)).isTrue();
    assertThat(viewportManager.removeAffectsVisibleRange(7, 2)).isTrue();
    // fully below viewport
    assertThat(viewportManager.removeAffectsVisibleRange(11, 2)).isFalse();
    assertThat(viewportManager.removeAffectsVisibleRange(18, 2)).isFalse();
  }

  @Test
  public void testChangeSetIsVisibleForInitialisation() {
    ViewportManager viewportManager = getViewportManager(-1, 2);

    assertThat(viewportManager.insertAffectsVisibleRange(6, 2, -1)).isTrue();
    assertThat(viewportManager.updateAffectsVisibleRange(6, 2)).isTrue();
    assertThat(viewportManager.moveAffectsVisibleRange(6, 2, 10)).isTrue();
    assertThat(viewportManager.removeAffectsVisibleRange(6, 2)).isTrue();

    viewportManager = getViewportManager(1, -1);

    assertThat(viewportManager.insertAffectsVisibleRange(6, 2, 10)).isTrue();
    assertThat(viewportManager.updateAffectsVisibleRange(6, 2)).isTrue();
    assertThat(viewportManager.moveAffectsVisibleRange(6, 2, -1)).isTrue();
    assertThat(viewportManager.removeAffectsVisibleRange(6, 2)).isTrue();
  }

  private void setVisibleItemPositionInMockedLayoutManager(
      int firstVisibleItemPosition, int lastVisibleItemPosition) {
    when(mLayoutInfo.findFirstVisibleItemPosition()).thenReturn(firstVisibleItemPosition);
    when(mLayoutInfo.findLastVisibleItemPosition()).thenReturn(lastVisibleItemPosition);
  }

  private void setFullyVisibleItemPositionInMockedLayoutManager(
      int firstFullyVisiblePosition, int lastFullyVisiblePosition) {
    when(mLayoutInfo.findFirstFullyVisibleItemPosition()).thenReturn(firstFullyVisiblePosition);
    when(mLayoutInfo.findLastFullyVisibleItemPosition()).thenReturn(lastFullyVisiblePosition);
  }

  private void setTotalItemInMockedLayoutManager(int totalItem) {
    when(mLayoutInfo.getItemCount()).thenReturn(totalItem);
  }

  private ViewportManager getViewportManager(int firstVisiblePosition, int lastVisiblePosition) {
    ViewportManager viewportManager =
        new ViewportManager(firstVisiblePosition, lastVisiblePosition, mLayoutInfo);
    viewportManager.addViewportChangedListener(mViewportChangedListener);

    return viewportManager;
  }
}


text:
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *btn;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self test1];
    [self test2];
    [self test3];
    [self test4];
    [self test5];

    [_btn2 qf_addTarget:self forControlEvents:UIControlEventTouchUpInside handle:^{
        NSLog(@"点击btn");
    }];

    __block int a = 0;
    [self qf_addObserverForName:@"hello" object:nil handle:^(NSNotification *notify) {
        a = 2;
        NSLog(@"-------------%d",a);
    }];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hello" object:nil];
}

// 1.交换两个方法
- (void)test1
{
    [Person run];
    [Person eat];
}

// 2.拦截系统自带的方法
- (void)test2
{
    UIImage *image = [UIImage imageNamed:@"hello"];
    [self.view addSubview:[[UIImageView alloc] initWithImage:image]];
}

// 3.给类方法添加属性
- (void)test3
{
    [Dog eatSomething:@"bounds"];
    NSLog(@"%@",[Dog something]);
}

// 4.解归档
- (void)test4
{
    Person *person = [[Person alloc] init];
    person.name = @"jack";
    ClassRoom *room = [[ClassRoom alloc] initWithClassName:@"classA" grade:3 students:30 person:person];
    [room saveRoom];

}

- (void)test5
{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@100 forKey:@"price"];
    [dic setValue:@"hello" forKey:@"name"];
    [dic setValue:@100 forKey:@"page"];
    [dic setValue:@"jack" forKey:@"author"];
    Book *book = [Book objectWithDict:dic];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [ClassRoom room];
}

@end


text:
def lenIter(aStr):
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    # Your code here
    count = 0
    for char in aStr:
        count += 1
    return count

print lenIter("good")


text:
class myDirectPushButton : public QPushButton
{
public:
    myDirectPushButton(directions direct, QWidget *parent = 0);

    directions direction();

public slots:
    void inverseDirection();
    void setDirection(directions d);

protected:
    void paintEvent(QPaintEvent *event);
    directions _direction;
};

#endif // MYDIRECTPUSHBUTTON_H


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.core.data;

import java.util.List;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import docking.action.DockingActionIf;
import generic.test.category.NightlyCategory;
import ghidra.program.model.data.DataType;

@Category(NightlyCategory.class)
public class DataAction1Test extends AbstractDataActionTest {

	@Test
	public void testAllStructDataSettings() throws Exception {

		List<DataType> builtIns = getBuiltInDataTypesAsFavorites();
		for (DataType type : builtIns) {
			String actionName = "Define " + type.getName();
			DockingActionIf action = getAction(actionName);
			manipulateAllSettings(false, true, false, action);
			manipulateAllSettings(true, true, true, action);
		}
	}
}


text:
package gameEngine.actors;

import gameEngine.ManagerInterface.InformationInterface;
import gameEngine.actors.behaviors.IBehavior;

import java.util.Map;

import javafx.scene.Node;
import javafx.scene.shape.Circle;

public abstract class RealActor extends BaseActor {
    protected ProjectileInfo myProjectile;
    public RealActor(Map<String,IBehavior> behaviors, String image, String name, double range){
        super(behaviors,image,name, range);
        myProjectile=null;
    }
    public RealActor(Map<String,IBehavior> behaviors, String image, String name, double range, ProjectileInfo projectile){
        super(behaviors,image,name, range);
        myProjectile=projectile;
    }
    @Override
    public void update(InformationInterface info){
        myInfo = info;
        for(String s: myDebuffs.keySet()){
            myDebuffs.get(s).execute(this);
        }
        for (String s : myBehaviors.keySet()) {
            myBehaviors.get(s).execute(this);
        }

        for(IBehavior debuff: myDebuffsToRemove){
            myDebuffs.remove(debuff.toString());
        }
        myDebuffsToRemove.clear();

    }
    public ProjectileInfo getProjectile(){
        return myProjectile;
    }
    public void spawnProjectile(BaseActor projectile){
        setChanged();
        notifyObservers(projectile);
    }
    public Node getRange() {
        return new Circle(myNode.getXCenter(),myNode.getYCenter(),myRange);
    }

    /**
     * Copies the current actor to create another one
     * This is used when creating x amount of enemies of the same type on a specific level
     * The copy is created by copying all of the behaviors and creating a new BaseActor object
     */
    public abstract BaseActor copy();
}


text:
package org.egordorichev.lasttry.util.math;

/**
 * Simple number util
 */
public class NumberUtil {
	/**
	 * Returns middle value from all three
	 * @param x Number one
	 * @param y Number two
	 * @param z Number three
	 * @return The middle number
	 */
	public static float clamp(float x, float y, float z) {
		if (x > y) {
			float tmp = x;

			x = y;
			y = tmp;
		}

		return Math.max(x, Math.min(y, z));
	}
}


text:
package com.hitzd.his.Web.Taglibs.Plugs;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class GraphTagUtil
{
	public static String getMapValue(Map<String, String> value)
	{
		StringBuffer sb = new StringBuffer();
		if(value.size() == 0)
		{
			return "";
		}
		sb.append("[");
		for(String key : value.keySet())
		{
			sb.append("['").append(key).append("',").append(value.get(key)).append("],");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		return sb.toString();
    }
	/**
	 * 通过两个List拼装js数组
	 * @param key
	 * @param value
	 * @return
	 */
	public static String get2ListValue(List<String> key, List<String> value)
	{
		StringBuffer sb = new StringBuffer();
		if(value.size() == 0)
		{
			return "";
		}
		sb.append("[");
		for(int i=0; i<key.size(); i++)
		{
			sb.append("['").append(key.get(i)).append("',").append(value.get(i)).append("],");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		return sb.toString();
	}
	public static String convertList2JsArray(List<String> list)
	{
		StringBuffer s = new StringBuffer();
		s.append("[");
		for(String str: list){
			s.append("'" + str + "',");
		}
		if(list.size()>0)s.deleteCharAt(s.length()-1);//删除最后一个
		s.append("]");
		return s.toString();
	}

	public static String convertList2JsArrayWithoutComma(List<String> list)
	{
		StringBuffer s = new StringBuffer();
		s.append("[");
		for(String str: list){
			s.append("" + str + ",");
		}
		if(list.size()>0)s.deleteCharAt(s.length()-1);//删除最后一个
		s.append("]");
		return s.toString();
	}

	//test  getMapValue
	public static void main(String[] args)
	{
		LinkedHashMap orderMap1 = new LinkedHashMap();
		orderMap1.put("1","100");
		orderMap1.put("2","100");
		orderMap1.put("3","100");
		orderMap1.put("4","100");
		orderMap1.put("5","100");
		LinkedHashMap orderMap2 = new LinkedHashMap();
		LinkedHashMap orderMap3 = new LinkedHashMap();
		orderMap2.put("1","80");
		orderMap2.put("2","80");
		orderMap2.put("3","80");
		orderMap2.put("4","80");
		orderMap2.put("5","8");

		List<String> test = new ArrayList<String>();
		test.add("你");
		test.add("我");
		test.add("他");
		System.out.println(convertList2JsArray(test));

		List<String> test1 = new ArrayList<String>();
		test1.add("1");
		test1.add("2");
		test1.add("3");

		System.out.println(get2ListValue(test, test1));
	}
}


text:
Implementation of various algorithms in the Nested Sequential Monte Carlo family of methods.

These are a special type of sequential Monte Carlo methods, otherwise known as particle filters.


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds       #-}
{-# LANGUAGE GeneralizedNewtypeDeriving  #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes       #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators   #-}

module Vulgr.API
    ( module Vulgr.Cve
    , API
    , App (..)
    , api
    , getCve
    , postCves
    ) where

import Control.Lens.Operators
import Control.Monad.Reader
import Data.Aeson
import Data.Aeson.Lens
import qualified Data.HashMap.Strict as M
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Proxy
import Database.Neo4j as Neo
import Database.Neo4j.Transactional.Cypher as TC
import Servant

import Prelude hiding (product)

import Debug.Trace

import Vulgr.Cve
import Vulgr.Neo4j

type API =
    "cves" :> Capture "cveId" T.Text :> Get '[JSON] [Cve]
    :<|> "cves" :> ReqBody '[JSON] [Cve] :> Post '[JSON] T.Text

newtype App a = App { runApp :: ReaderT Neo.Connection IO a }
    deriving (Monad, Functor, Applicative, MonadReader Neo.Connection, MonadIO)

api :: Proxy API
api = Proxy

-- | Post to /cves
postCves :: [Cve] -> App T.Text
postCves cs = traceShow "Called post..." $ do
    conn <- ask
    liftIO $ createCve conn cs

createCve :: Neo.Connection -> [Cve] -> IO T.Text
createCve conn cves = do
    eitherResults <- n4jTransaction conn $ mapM uniqCveNodeCypher cves
    return $ case eitherResults of
        Right _ -> "Success"
        Left e  -> fst e

uniqCveNodeCypher :: Cve -> TC.Transaction TC.Result
uniqCveNodeCypher cve =
    TC.cypher ("MERGE ( n:CVE { cveId : {cveId}, summary : {summary}, " <>
        "product : {product}, cvssScore : {cvssScore} } )") (traceShow (cve2map cve) $ cve2map cve)
  where
    cve2map cve = M.fromList [
        (T.pack "cveId", TC.newparam (cveId cve))
        , (T.pack "summary", TC.newparam (summary cve))
        , (T.pack "product", TC.newparam (product cve))
        , (T.pack "cvssScore", TC.newparam (cvssScore cve))
        ]

-- | Get the nodes corresponding to a Cve ID.
-- Note that this can be more than one node, Cve ID's are enforced
-- through this API as a unique constraint however it is not
-- enforced in Neo4j, and I cannot find a way to do this...
getCve :: T.Text -> App [Cve]
getCve cveid = do
    conn <- ask
    eitherResult <- liftIO $ n4jTransaction conn $
        TC.cypher "MATCH (n: CVE {cveId : {cveId}}) RETURN n" $ M.fromList [("cveId", TC.newparam cveid)]
    case eitherResult of
        Right result -> return (jsonToCve $ vals result)
        Left e -> return [] -- TODO : This function should return an Either.
  where
    -- Turn a list of lists of Value's into a list of Cve's.
    jsonToCve :: [[Value]] -> [Cve]
    jsonToCve lvals = catMaybes . concat $
        fmap (fmap (\obj -> obj ^? _JSON :: Maybe Cve)) lvals


text:
package com.wq.android.lightannotation.annotations;

import android.view.View;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * <pre>
 *
 * See: {@link android.view.View#setOnLongClickListener(android.view.View.OnLongClickListener)}
 *
 * Usage Example:
 *
 * @OnLongClick({R.id.viewId})
 * public boolean onLongClick(View v)
 * {
 * }
 *
 * </pre>
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnLongClick {
    int[] value() default View.NO_ID;
}


text:
FROM python:2-onbuild
MAINTAINER Vadim Caen <vadimcaen@gmail.com>

RUN apt-get update && apt-get install -y \
	python-psycopg2

EXPOSE 8000
ENTRYPOINT python /app/server.py


text:
// Type definitions for pkgcloud 1.7
// Project: https://github.com/pkgcloud/pkgcloud#readme
// Definitions by: Daniel Friesen <https://github.com/dantman>
//                 Adam Smith <https://github.com/ScriptSmith>
//                 Cornelis Heuperman <https://github.com/heuperman>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7

/// <reference types="node" />

export const version: string;

export interface ClientError extends Error {
    provider?: Providers | undefined;
    method?: string | undefined;
    failCode?: string | undefined;
    statusCode?: number | undefined;
    href?: string | undefined;
    headers?: { [headerName: string]: string } | undefined;
    result?: any;
}

export type Providers =
    | 'amazon'
    | 'azure'
    | 'digitalocean'
    | 'google'
    | 'hp'
    | 'iriscouch'
    | 'joyent'
    | 'mongohq'
    | 'mongolab'
    | 'oneandone'
    | 'openstack'
    | 'rackspace'
    | 'redistogo'
    | 'telefonic';

export interface BaseProviderOptions {
    provider: Providers;
}

export interface AmazonProviderOptions {
    provider: 'amazon';
    keyId: string;
    key: string;
    region?: string | undefined;
}

export interface AzureProviderOptions {
    provider: 'azure';
    storageAccount: string;
    storageAccessKey: string;
    location?: string | undefined;
}

export interface GoogleProviderOptions {
    provider: 'google';
    keyFilename: string;
    projectId: string;
}

export interface OpenstackProviderOptions {
    provider: 'openstack';
    username: string;
    password: string;
    authUrl: string;
    region?: string | undefined;
    tenantId?: string | undefined;
    version?: string | undefined;
    keystoneAuthVersion?: string | undefined;
    domainId?: string | undefined;
    domainName?: string | undefined;
}

export type RackspaceRegions =
    | 'DFW' // Dallas/Fort Worth, United States
    | 'ORD' // Chicago, United States
    | 'IAD' // Northern Virginia, United States
    | 'LON' // London, United Kingdom
    | 'HKG' // Hong Kong, China
    | 'SYD'; // Sydney, Australia

export interface RackspaceProviderOptions {
    provider: 'rackspace';
    username: string;
    apiKey: string;
    region: RackspaceRegions;
    useInternal?: boolean | undefined;
}

export type ProviderOptions = BaseProviderOptions & Partial<
    | AmazonProviderOptions
    | AzureProviderOptions
    | GoogleProviderOptions
    | OpenstackProviderOptions
    | RackspaceProviderOptions
>;

/**
 * Storage
 */

export namespace storage {
    interface StorageUploadOptions {
        container: string;
        remote: string;
    }

    interface StorageDownloadOptions {
        container: string;
        remote: string;
    }

    interface Client {
        provider: string;
        config: ProviderOptions;
        protocol: string;

        getContainers(
            callback: (err: ClientError, containers: Container[]) => any,
        ): void;
        createContainer(
            options: any,
            callback: (err: ClientError, container: Container) => any,
        ): void;
        destroyContainer(
            containerName: string,
            callback: (err: ClientError) => any,
        ): void;
        getContainer(
            containerName: string,
            callback: (err: ClientError, container: Container) => any,
        ): void;
        upload(options: StorageUploadOptions): NodeJS.WriteStream;
        download(options: StorageDownloadOptions): NodeJS.ReadStream;
        getFiles(
            containerName: string,
            callback: (err: ClientError, files: File[]) => any,
        ): void;
        getFile(
            containerName: string,
            file: string,
            callback: (err: ClientError, file: File) => any,
        ): void;
        removeFile(
            containerName: string,
            file: string,
            callback: (err: ClientError) => any,
        ): void;
        // Logs
        on(
            eventName: string,
            callback: (message: string, object?: any) => any,
        ): void;
    }

    interface Container {
        // files: ?
        client: Client;
    }

    interface File {
        container: string;
        name: string;
        size: number;
        client: Client;
    }

    function createClient(options: ProviderOptions): Client;
}


text:
#!/bin/bash

. ./script/common.sh

INPUTDATA_REPOSITORY=${INPUTDATA_DIR}/statsrepo-inputdata.sql

function exec_statsinfo()
{
	pg_statsinfo -U ${REPOSITORY_USER} -p ${REPOSITORY_PORT} "${@}"
}

trap stop_all_database EXIT

echo "/*---- Initialize repository DB ----*/"
setup_repository ${REPOSITORY_DATA} ${REPOSITORY_USER} ${REPOSITORY_PORT} ${REPOSITORY_CONFIG}

export PGOPTIONS=' -c intervalstyle=postgres'

[ $(server_version) -lt 90000 ] &&
	send_query -c "CREATE LANGUAGE plpgsql" > /dev/null

echo "/*---- Input the repository data ----*/"
send_query -qf "$(pg_config --sharedir)/contrib/pg_statsrepo.sql"
send_query -c "SELECT statsrepo.create_snapshot_partition('2012-11-01')" > /dev/null
send_query -qf ${INPUTDATA_REPOSITORY}
send_query << EOF > /dev/null
SELECT statsrepo.input_data(1, '5807946214009601530', 'statsinfo', 5432, '8.4.0', 1);
SELECT statsrepo.input_data(2, '5807946214009601531', 'statsinfo', 5433, '9.0.0', 5);
SELECT statsrepo.input_data(3, '5807946214009601532', 'statsinfo', 5434, '9.1.0', 9);
SELECT statsrepo.input_data(4, '5807946214009601533', 'statsinfo', 5435, '9.2.0', 13);
SELECT statsrepo.input_data(5, '5807946214009601534', 'statsinfo', 5436, '9.3.0', 17);
SELECT statsrepo.input_data(6, '5807946214009601535', 'statsinfo', 5437, '9.4.0', 21);
EOF

echo "/*---- Create report ----*/"
echo "/**--- REPORTID: Summary ---**/"
exec_command "exec_statsinfo -r Summary"

echo "/**--- REPORTID: DatabaseStatistics ---**/"
exec_command "exec_statsinfo -r DatabaseStatistics"

echo "/**--- REPORTID: InstanceActivity ---**/"
exec_command "exec_statsinfo -r InstanceActivity"

echo "/**--- REPORTID: OSResourceUsage ---**/"
exec_command "exec_statsinfo -r OSResourceUsage"

echo "/**--- REPORTID: DiskUsage ---**/"
exec_command "exec_statsinfo -r DiskUsage"

echo "/**--- REPORTID: LongTransactions ---**/"
exec_command "exec_statsinfo -r LongTransactions"

echo "/**--- REPORTID: NotableTables ---**/"
exec_command "exec_statsinfo -r NotableTables"

echo "/**--- REPORTID: CheckpointActivity ---**/"
exec_command "exec_statsinfo -r CheckpointActivity"

echo "/**--- REPORTID: AutovacuumActivity ---**/"
exec_command "exec_statsinfo -r AutovacuumActivity"

echo "/**--- REPORTID: QueryActivity ---**/"
exec_command "exec_statsinfo -r QueryActivity"

echo "/**--- REPORTID: LockConflicts ---**/"
exec_command "exec_statsinfo -r LockConflicts"

echo "/**--- REPORTID: ReplicationActivity ---**/"
exec_command "exec_statsinfo -r ReplicationActivity"

echo "/**--- REPORTID: SettingParameters ---**/"
exec_command "exec_statsinfo -r SettingParameters"

echo "/**--- REPORTID: SchemaInformation ---**/"
exec_command "exec_statsinfo -r SchemaInformation"

echo "/**--- REPORTID: Alert ---**/"
exec_command "exec_statsinfo -r Alert"

echo "/**--- REPORTID: Profiles ---**/"
exec_command "exec_statsinfo -r Profiles"

echo "/**--- REPORTID: All ---**/"
exec_command "exec_statsinfo -r All"

echo "/**--- Specify the INSTANCEID that exists in data ---**/"
exec_command "exec_statsinfo -r Summary -i 1"

echo "/**--- Specify the INSTANCEID that not exists in data ---**/"
exec_command "exec_statsinfo -r Summary -i 99"

echo "/**--- Specify the report scope (-e=2) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -e 2"

echo "/**--- Specify the report scope (-b=2, -e=3) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -b 2 -e 3"

echo "/**--- Specify the report scope (-b=3) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -b 3"

echo "/**--- Specify the report scope (-E=<snapid=2>) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -E '2012-11-01 00:01:00'"

echo "/**--- Specify the report scope (-B=<snapid=2>, -E=<snapid=3>) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -B '2012-11-01 00:01:00' -E '2012-11-01 00:02:00'"

echo "/**--- Specify the report scope (-B=<snapid=3>) ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -B '2012-11-01 00:02:00'"

echo "/**--- Output the report to a file ---**/"
exec_command "exec_statsinfo -r Summary -i 1 -o ${REPOSITORY_DATA}/report.log"
cat ${REPOSITORY_DATA}/report.log

echo "/**--- Output the report to a file (overwrite) ---**/"
exec_command "exec_statsinfo -r Summary -i 2 -o ${REPOSITORY_DATA}/report.log"
cat ${REPOSITORY_DATA}/report.log

echo "/*---- Quasi-normal pattern ----*/"
echo "/**--- Contain the snapshot that is same acquisition date ---**/"
send_query -c "UPDATE statsrepo.snapshot SET time = '2012-11-01 00:00:00' WHERE instid = 5"
exec_command "exec_statsinfo -r All -i 5"


text:
#ifndef RESOWNER_H
#define RESOWNER_H

/*
 * ResourceOwner objects are an opaque data structure known only within
 * resowner.c.
 */
typedef struct ResourceOwnerData *ResourceOwner;

/*
 * Globally known ResourceOwners
 */
extern PGDLLIMPORT ResourceOwner CurrentResourceOwner;
extern PGDLLIMPORT ResourceOwner CurTransactionResourceOwner;
extern PGDLLIMPORT ResourceOwner TopTransactionResourceOwner;
extern PGDLLIMPORT ResourceOwner AuxProcessResourceOwner;

/*
 * Resource releasing is done in three phases: pre-locks, locks, and
 * post-locks.  The pre-lock phase must release any resources that are
 * visible to other backends (such as pinned buffers); this ensures that
 * when we release a lock that another backend may be waiting on, it will
 * see us as being fully out of our transaction.  The post-lock phase
 * should be used for backend-internal cleanup.
 */
typedef enum
{
	RESOURCE_RELEASE_BEFORE_LOCKS,
	RESOURCE_RELEASE_LOCKS,
	RESOURCE_RELEASE_AFTER_LOCKS
} ResourceReleasePhase;

/*
 *	Dynamically loaded modules can get control during ResourceOwnerRelease
 *	by providing a callback of this form.
 */
typedef void (*ResourceReleaseCallback) (ResourceReleasePhase phase,
										 bool isCommit,
										 bool isTopLevel,
										 void *arg);

/*
 * Functions in resowner.c
 */

/* generic routines */
extern ResourceOwner ResourceOwnerCreate(ResourceOwner parent,
										 const char *name);
extern void ResourceOwnerRelease(ResourceOwner owner,
								 ResourceReleasePhase phase,
								 bool isCommit,
								 bool isTopLevel);
extern void ResourceOwnerReleaseAllPlanCacheRefs(ResourceOwner owner);
extern void ResourceOwnerDelete(ResourceOwner owner);
extern ResourceOwner ResourceOwnerGetParent(ResourceOwner owner);
extern void ResourceOwnerNewParent(ResourceOwner owner,
								   ResourceOwner newparent);
extern void RegisterResourceReleaseCallback(ResourceReleaseCallback callback,
											void *arg);
extern void UnregisterResourceReleaseCallback(ResourceReleaseCallback callback,
											  void *arg);
extern void CreateAuxProcessResourceOwner(void);
extern void ReleaseAuxProcessResources(bool isCommit);

#endif							/* RESOWNER_H */


text:
package com.hazelcast.config;

import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import static com.hazelcast.test.HazelcastTestSupport.assertContains;
import static com.hazelcast.test.HazelcastTestSupport.assumeDifferentHashCodes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class LockConfigTest {

    private LockConfig config = new LockConfig();

    @Test
    public void testConstructor_withName() {
        config = new LockConfig("foobar");

        assertEquals("foobar", config.getName());
    }

    @Test
    public void testConstructor_withLockConfig() {
        config.setName("myName");
        config.setQuorumName("myQuorum");

        LockConfig cloned = new LockConfig(config);

        assertEquals(config.getName(), cloned.getName());
        assertEquals(config.getQuorumName(), cloned.getQuorumName());
    }

    @Test
    public void testConstructor_withLockConfigAndOverriddenName() {
        config.setName("myName");
        config.setQuorumName("myQuorum");

        LockConfig cloned = new LockConfig("newName", config);

        assertEquals("newName", cloned.getName());
        assertNotEquals(config.getName(), cloned.getName());
        assertEquals(config.getQuorumName(), cloned.getQuorumName());
    }

    @Test
    public void testToString() {
        assertNotNull(config.toString());
        assertContains(config.toString(), "LockConfig");
    }

    @Test
    public void testEqualsAndHashCode() {
        assumeDifferentHashCodes();
        EqualsVerifier.forClass(LockConfig.class)
                .allFieldsShouldBeUsed()
                .suppress(Warning.NONFINAL_FIELDS)
                .verify();
    }
}


text:
#ifndef COMMON_H
#define COMMON_H

#include "postgres_fe.h"
#include <setjmp.h>
#include "libpq-fe.h"

#ifdef USE_ASSERT_CHECKING
#include <assert.h>
#define psql_assert(p) assert(p)
#else
#define psql_assert(p)
#endif

#define atooid(x)  ((Oid) strtoul((x), NULL, 10))

/*
 * Safer versions of some standard C library functions. If an
 * out-of-memory condition occurs, these functions will bail out
 * safely; therefore, their return value is guaranteed to be non-NULL.
 */
extern char *pg_strdup(const char *string);
extern void *pg_malloc(size_t size);
extern void *pg_malloc_zero(size_t size);
extern void *pg_calloc(size_t nmemb, size_t size);

extern bool setQFout(const char *fname);

extern void
psql_error(const char *fmt,...)
/* This lets gcc check the format string for consistency. */
__attribute__((format(printf, 1, 2)));

extern void NoticeProcessor(void *arg, const char *message);

extern volatile bool sigint_interrupt_enabled;

extern sigjmp_buf sigint_interrupt_jmp;

extern volatile bool cancel_pressed;

/* Note: cancel_pressed is defined in print.c, see that file for reasons */

extern void setup_cancel_handler(void);

extern void SetCancelConn(void);
extern void ResetCancelConn(void);

extern PGresult *PSQLexec(const char *query, bool start_xact);

extern bool SendQuery(const char *query);

extern bool is_superuser(void);
extern bool standard_strings(void);
extern const char *session_username(void);

extern char *expand_tilde(char **filename);

#ifndef WIN32

#include <sys/time.h>

typedef struct timeval TimevalStruct;

#define GETTIMEOFDAY(T) gettimeofday(T, NULL)
#define DIFF_MSEC(T, U) \
	((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
	  ((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)
#else
/*
 * To get good resolution (better than ~15ms) on Windows, use
 * the high resolution performance counters. They can't be used
 * to get absolute times, but are good for measuring differences.
 */
static __inline__ double
GetTimerFrequency(void)
{
	LARGE_INTEGER f;

	QueryPerformanceFrequency(&f);
	return (double) f.QuadPart;
}

typedef LARGE_INTEGER TimevalStruct;

#define GETTIMEOFDAY(T) QueryPerformanceCounter((T))
#define DIFF_MSEC(T, U) \
	(((T)->QuadPart - (U)->QuadPart) * 1000.0 / GetTimerFrequency())
#endif   /* WIN32 */

#endif   /* COMMON_H */


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_AvatarIKGoal : LuaObject {
	static public void reg(IntPtr l) {
		getEnumTable(l,"UnityEngine.AvatarIKGoal");
		addMember(l,0,"LeftFoot");
		addMember(l,1,"RightFoot");
		addMember(l,2,"LeftHand");
		addMember(l,3,"RightHand");
		LuaDLL.lua_pop(l, 1);
	}
}


text:
package org.onosproject.provider.restconf.device.impl;

import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Test Case to Validate RESTCONF Device Provider.
 */
public class RESTConfDeviceProviderTest {
    private final Logger log = getLogger(RESTConfDeviceProviderTest.class);

    @Before
    public void setUp() {
        log.info("setup");
    }

    @After
    public void tearDown() {
        log.info("tear down");
    }
}


text:
__As jsFiddle, nodeFiddle__

Execute and share nodeJS code on the browser! [Try it here!](http://nodefiddle.github.io/nodeFiddle)

### Install

You need to install node in your machine (I recommend doing it through nvm).

Once done, install the project dependencies

```
$ npm install -g grunt-cli
$ npm install
```

### Run

Once all installed, type

```
$ grunt
```

And the web app will be hosted at http://localhost:9001/app/#/home


text:
namespace System.Security.Permissions
{

#if CONFIG_PERMISSIONS && CONFIG_REFLECTION

using System;
using System.Security;

public sealed class ReflectionPermission
	: CodeAccessPermission, IUnrestrictedPermission
{
	// Internal state.
	private PermissionState state;
	private ReflectionPermissionFlag flags;

	// Constructor.
	public ReflectionPermission(PermissionState state)
			{
				this.state = state;
			}
	public ReflectionPermission(ReflectionPermissionFlag flags)
			{
				this.flags = flags;
			}

	// Convert an XML value into a permissions value.
	public override void FromXml(SecurityElement esd)
			{
				String value;
				if(esd == null)
				{
					throw new ArgumentNullException("esd");
				}
				if(esd.Attribute("version") != "1")
				{
					throw new ArgumentException(_("Arg_PermissionVersion"));
				}
				value = esd.Attribute("Unrestricted");
				if(value != null && Boolean.Parse(value))
				{
					state = PermissionState.Unrestricted;
				}
				else
				{
					state = PermissionState.None;
				}
				value = esd.Attribute("Flags");
				if(value != null)
				{
					flags = (ReflectionPermissionFlag)
						Enum.Parse(typeof(ReflectionPermissionFlag), value);
				}
				else
				{
					flags = ReflectionPermissionFlag.NoFlags;
				}
			}

	// Convert this permissions object into an XML value.
	public override SecurityElement ToXml()
			{
				SecurityElement element;
				element = new SecurityElement("IPermission");
				element.AddAttribute
					("class",
					 SecurityElement.Escape(typeof(ReflectionPermission).
					 						AssemblyQualifiedName));
				element.AddAttribute("version", "1");
				if(flags != ReflectionPermissionFlag.NoFlags)
				{
					element.AddAttribute("Flags", flags.ToString());
				}
				else if(state == PermissionState.Unrestricted)
				{
					element.AddAttribute("Unrestricted", "true");
				}
				return element;
			}

	// Implement the IPermission interface.
	public override IPermission Copy()
			{
				if(flags != ReflectionPermissionFlag.NoFlags)
				{
					return new ReflectionPermission(flags);
				}
				else
				{
					return new ReflectionPermission(state);
				}
			}
	public override IPermission Intersect(IPermission target)
			{
				ReflectionPermissionFlag newFlags;
				if(target == null)
				{
					return target;
				}
				else if(!(target is ReflectionPermission))
				{
					throw new ArgumentException(_("Arg_PermissionMismatch"));
				}
				else if(((ReflectionPermission)target).IsUnrestricted())
				{
					if(IsUnrestricted())
					{
						return Copy();
					}
					else
					{
						newFlags = flags;
					}
				}
				else if(IsUnrestricted())
				{
					newFlags = ((ReflectionPermission)target).flags;
				}
				else
				{
					newFlags = ((ReflectionPermission)target).flags & flags;
				}
				if(newFlags == 0)
				{
					return null;
				}
				else
				{
					return new ReflectionPermission(newFlags);
				}
			}
	public override bool IsSubsetOf(IPermission target)
			{
				if(target == null)
				{
					return (flags == ReflectionPermissionFlag.NoFlags);
				}
				else if(!(target is ReflectionPermission))
				{
					throw new ArgumentException(_("Arg_PermissionMismatch"));
				}
				else if(((ReflectionPermission)target).IsUnrestricted())
				{
					return true;
				}
				else if(IsUnrestricted())
				{
					return false;
				}
				else
				{
					return ((flags & ~(((ReflectionPermission)target).flags))
								== 0);
				}
			}
	public override IPermission Union(IPermission target)
			{
				if(target == null)
				{
					return Copy();
				}
				else if(!(target is ReflectionPermission))
				{
					throw new ArgumentException(_("Arg_PermissionMismatch"));
				}
				else if(IsUnrestricted() ||
				        ((ReflectionPermission)target).IsUnrestricted())
				{
					return new ReflectionPermission
						(PermissionState.Unrestricted);
				}
				else
				{
					return new ReflectionPermission
						(flags | ((ReflectionPermission)target).flags);
				}
			}

	// Determine if this object has unrestricted permissions.
#if ECMA_COMPAT
	private bool IsUnrestricted()
			{
				return (state == PermissionState.Unrestricted);
			}
	bool IUnrestrictedPermission.IsUnrestricted()
#else
	public bool IsUnrestricted()
#endif
			{
				return (state == PermissionState.Unrestricted);
			}

#if !ECMA_COMPAT

	// Get or set the flags on this permissions object.
	public ReflectionPermissionFlag Flags
			{
				get
				{
					return flags;
				}
				set
				{
					if((flags & ~(ReflectionPermissionFlag.AllFlags)) != 0)
					{
						throw new ArgumentException(_("Arg_ReflectionFlag"));
					}
				}
			}

#endif // !ECMA_COMPAT

}; // class ReflectionPermission

#endif // CONFIG_PERMISSIONS && CONFIG_REFLECTION

}; // namespace System.Security.Permissions


text:
@protocol MXOAuthViewDelegate <NSObject>
-(void)didFinishOAuthViewSign:(NSString *)accessToken type:(NSString *)type;
@end

@interface MXOAuthViewController : UIViewController<UIWebViewDelegate,MBGithubOAuthDelegate,MXGoogleOAuthDelegate,MXQQOAuthDelegate,MXSinaOAuthDelegate>

@property (nonatomic, assign) id<MXOAuthViewDelegate> mydelegate;

@property (nonatomic, strong) NSString * type;
@property (nonatomic, strong) NSString * ClientID;
@property (nonatomic, strong) NSString * ClientSecret;
@property (nonatomic, strong) NSString * RedirectUrl;
@property (weak, nonatomic) IBOutlet UIWebView *myWebView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *Indicator;
@end


text:
module Sorcery
  module Model
    module Submodules
      #
      # Access Token submodule
      #
      # Handles the creation and deletion of user access_tokens,
      #
      module AccessToken
        def self.included(base)
          base.sorcery_config.class_eval do
            attr_accessor(:access_token_mode,
                          :access_token_duration,
                          :access_token_duration_from_last_activity,
                          :access_token_max_per_user,
                          :access_token_register_last_activity)
          end

          base.sorcery_config.instance_eval do
            @defaults.merge!(:@access_token_mode => 'single_token',
                             :@access_token_duration => nil,
                             :@access_token_duration_from_last_activity => false,
                             :@access_token_max_per_user => nil,
                             :@access_token_register_last_activity => false)

            reset!
          end

          base.send(:include, InstanceMethods)

          if defined?(Mongoid) && base.ancestors.include?(Mongoid::Document)
            base.sorcery_config.after_config << :define_access_token_mongoid_fields
          end
          if defined?(MongoMapper) && base.ancestors.include?(MongoMapper::Document)
            base.sorcery_config.after_config << :define_access_token_mongo_mapper_fields
          end

          base.sorcery_config.after_config << :register_access_token_creation_callback

          base.extend(ClassMethods)
        end

        module ClassMethods
          protected

            def define_access_token_mongoid_fields
              include Mongoid::Timestamps
              field :user_id, :type => Integer
              field :token, :type => String
              field :expirable, :type => Boolean, :default => true
              field :last_activity_at, :type => Time
            end

            def define_access_token_mongo_mapper_fields
              key :token, String
              key :expirable, Boolean, :default => true
              key :last_activity_at, Time
              timestamps!
            end

            # Register conditional create_access_token on after_create callback,
            # create token after user creation when mode is set to 'single_token'
            def register_access_token_creation_callback
              after_create do
                create_access_token!(:user_creation)
              end
            end
        end

        module InstanceMethods
          # Create and return access token, or nil if nothing was created,
          # it has the side effect of destroying user invalid tokens.
          # Creation conditions:
          #   * session mode : number of valid stored tokens must be less than
          #                    value defined in max_per_user (if any).
          #   * single_token mode : stored token must be invalid or nonexistent.
          def create_access_token!(context = nil)
            access_token_mode = sorcery_config.access_token_mode.to_s
            max = sorcery_config.access_token_max_per_user
            delete_expired_access_tokens
            self.reload
            if access_token_mode == 'session' && context != :user_creation
              if ! max || access_tokens.count < max.to_i
                access_tokens.create!
              end
            elsif access_token_mode == 'single_token' && access_tokens.empty?
              access_tokens.create!
            end
          end

          # Delete user expired access tokens
          def delete_expired_access_tokens
            ::AccessToken.delete_expired(self.id)
          end

        end
      end
    end
  end
end


text:
import PropTypes from 'prop-types';
import React from 'react';
import uuid from 'uuid';
import Components from '../../../components/react-components';
const {Copy} = Components;

export default class NotificationPanelRow extends React.Component {
  static propTypes = {
    item: PropTypes.object.isRequired,
    filter: PropTypes.string.isRequired,
    clearSingleNotification: PropTypes.func.isRequired
  };

  clearNotification = () => {
    const {notificationId} = this.props.item;
    this.props.clearSingleNotification(notificationId);
  };

  render() {
    const iconMap = {
      success: 'fonticon-ok-circled',
      error: 'fonticon-attention-circled',
      info: 'fonticon-info-circled'
    };

    const timeElapsed = this.props.item.time.fromNow();

    // we can safely do this because the store ensures all notifications are of known types
    const rowIconClasses = 'fonticon ' + iconMap[this.props.item.type];
    const hidden = (this.props.filter === 'all' || this.props.filter === this.props.item.type) ? false : true;
    const {style} = this.props;
    const {opacity, height} = style;
    if (opacity === 0 && height === 0) {
      return null;
    }
    // N.B. wrapper
 needed to ensure smooth hide/show transitions
    return (
      <li style={{opactiy: opacity, height: height + 'px', borderBottomColor: `rgba(34, 34, 34, ${opacity})`}} aria-hidden={hidden}>

{this.props.item.cleanMsg}

              {timeElapsed}
              |
              <Copy uniqueKey={uuid.v4()} text={this.props.item.cleanMsg} displayType="text" />

          <button type="button" onClick={this.clearNotification}>×</button>

    );
  }
}


text:
from __future__ import absolute_import, unicode_literals

from django.dispatch import receiver
from wagtail.wagtaildocs.models import document_served

from downloadcounter.models import DownloadCount

@receiver(document_served)
def count(instance, **kwargs):
    download_count, created = DownloadCount.objects.get_or_create(file=instance)
    download_count.count = download_count.count + 1
    download_count.save()


text:
@implementation UserModel

@end

@implementation LivesModel

@end


text:
@ECHO OFF
SET BIN_TARGET=%~dp0/../heroku/heroku-buildpack-php/bin/heroku-php-apache2
bash "%BIN_TARGET%" %*


text:
package org.apache.orc.impl;

import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.kms.KMSClientProvider;
import org.apache.orc.EncryptionAlgorithm;
import org.junit.jupiter.api.Test;

import java.sql.Date;
import java.util.HashMap;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class TestHadoopShimsPre2_7 {

  @Test
  public void testFindingUnknownEncryption() {
    assertThrows(IllegalArgumentException.class, () -> {
      KeyProvider.Metadata meta = new KMSClientProvider.KMSMetadata(
          "XXX/CTR/NoPadding", 128, "", new HashMap<String, String>(),
          new Date(0), 1);
      HadoopShimsCurrent.findAlgorithm(meta);
    });
  }

  @Test
  public void testFindingAesEncryption()  {
    KeyProvider.Metadata meta = new KMSClientProvider.KMSMetadata(
        "AES/CTR/NoPadding", 128, "", new HashMap<String, String>(),
        new Date(0), 1);
    assertEquals(EncryptionAlgorithm.AES_CTR_128,
        HadoopShimsCurrent.findAlgorithm(meta));
    meta = new KMSClientProvider.KMSMetadata(
        "AES/CTR/NoPadding", 256, "", new HashMap<String, String>(),
        new Date(0), 1);
    assertEquals(EncryptionAlgorithm.AES_CTR_256,
        HadoopShimsCurrent.findAlgorithm(meta));
    meta = new KMSClientProvider.KMSMetadata(
        "AES/CTR/NoPadding", 512, "", new HashMap<String, String>(),
        new Date(0), 1);
    assertEquals(EncryptionAlgorithm.AES_CTR_256,
        HadoopShimsCurrent.findAlgorithm(meta));
  }
}


text:
class AddVisitTypeToVisits < ActiveRecord::Migration
  def change
    add_column :visits, :status, :string, default: 'visited', limit: 10
    add_column :visits, :visibility, :integer, default: 1000
  end
end


text:
var should = require('should');
var setup = require('./../mocks/setup');
var assert = require('assert');

setup.makeSuite('search service', function() {

  var searchService = require('./../../src/services/search');
  var slugsService = require('./../../src/services/slugs');
  var dataService = require('./../../src/services/data');
  var projectService = require('./../../src/services/project');
  var importService = require('./../../src/services/import');
  var elasticTools = require('./../../src/elastic/tools');
  var fs = require('fs-extra');

  before(function(done) {

    var data = [{
      name: 'Godfather',
      tags: ['Great movie', 'Best movie', 'Drama'],
      enabled: true
    }, {
      name: 'Fight club',
      enabled: false
    }, {
      name: 'test/test',
      enabled: true
    }]

    projectService.ensureCollectionAsync({
      projectName: 'test',
      collectionName: 'movie'
    }).delay(30)
    .then(function(res) {
      dataService.addDocumentsAsync({
        refresh: true,
        collectionName: 'movie',
        body: data
      })
    }).delay(100)
    .then(function(res) {
      done();
    });
  });

  it('should reindex slugs movies collection', function(done) {
    slugsService.reindexAsync({
      collectionName: 'movie',
      per_page: 1
    }).then(function(res) {
      done();
    });
  });

  it('should get slug value for god-father', function(done) {
    slugsService.getAsync('movie', 'tags', 'great-movie')
    .then(function(res) {
      assert.equal(res, 'Great movie')
      done();
    });
  });

  it('should get null for incorrect values', function(done) {
    slugsService.getAsync('movie', 'tagsg', 'great-movie')
    .then(function(res) {
      assert.equal(res, null)
      done();
    });
  });

});


text:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import { Message } from './../shared/models/message';

@Injectable()
export class MessageService {
    private subject = new Subject<Message>();

    constructor() {}

    public SendMessage(type: string, msg: string, timeOut: number) {
        const message = new Message(type, msg, timeOut);
        this.subject.next(message);
    }

    ClearMessage() {
        this.subject.next();
    }

    GetMessage(): Observable<Message> {
        return this.subject.asObservable();
    }
}


text:
/*global console window describe xdescribe it expect runs waits*/
(function () {
	require.paths.unshift(__dirname + '/../');

	require('thorny/base')('./config/default.json')(function ($) {
		describe('a poly2', function () {
			it('should contain the following functions', function () {
				var
					vector2 = $('thorny math vector2'),
					poly2 = $('thorny math poly2');

				expect(typeof poly2.factory).toEqual('function');
				expect(typeof poly2.findAngles).toEqual('function');
				expect(typeof poly2.findDistanceFromLineSegment).toEqual('function');

				describe('a poly2 factory', function () {
					it('should contain the following functions', function () {
						var
							v1 = vector2.factory(0, 0),
							v2 = vector2.factory(0, 100),
							v3 = vector2.factory(100, 0),
							instance = poly2.factory(v1, v2, v3);

						// Node stuff, makes sure we're extending the core/node
						// object correctly.
						expect(typeof instance.isNode).toEqual('function');
						expect(typeof instance.getId).toEqual('function');
						expect(typeof instance.addNeighbour).toEqual('function');
						expect(typeof instance.getNeightbours).toEqual('function');

						// Poly2 stuff
						expect(typeof instance.getVector2s).toEqual('function');
						describe('getVector2s', function () {
							it('should return the vector2s within the poly2', function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									vector2s = poly2.factory(v1, v2, v3)
										.getVector2s();

								// Makesure the look right
								expect(vector2s[0].getSimpleCoords())
									.toEqual(v1.getSimpleCoords());
								expect(vector2s[1].getSimpleCoords())
									.toEqual(v2.getSimpleCoords());
								expect(vector2s[2].getSimpleCoords())
									.toEqual(v3.getSimpleCoords());

								vector2s[0] = vector2.factory(50, 50);
								vector2s[1] = vector2.factory(50, 50);
								vector2s[2] = vector2.factory(50, 50);

								// Refresh the vector2s
								vector2s = poly2.factory(v1, v2, v3)
									.getVector2s();

								// Makesure they are still different
								expect(vector2s[0].getSimpleCoords())
									.toEqual(v1.getSimpleCoords());
								expect(vector2s[1].getSimpleCoords())
									.toEqual(v2.getSimpleCoords());
								expect(vector2s[2].getSimpleCoords())
									.toEqual(v3.getSimpleCoords());
							});
						});//getVector2s

						expect(typeof instance.getMidpoint).toEqual('function');
						describe('getMidpoint', function () {
							it('should return the midpoint of a poly', function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									poly = poly2.factory(v1, v2, v3);

								expect(poly.getMidpoint().getIntegerCoords()).toEqual([33, 33]);
							});
						});//getMidpoint

						expect(typeof instance.sharesEdge).toEqual('function');
						describe('sharesEdge', function () {
							it('should detect a sharded edge', function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									v4 = vector2.factory(100, 100),
									v5 = vector2.factory(150, 100),
									p1 = poly2.factory(v1, v2, v3),
									p2 = poly2.factory(v2, v3, v4),
									p3 = poly2.factory(v3, v4, v5);

								expect(p1.sharesEdge(p2)).toBeTruthy();
								expect(p2.sharesEdge(p1)).toBeTruthy();
								expect(p2.sharesEdge(p3)).toBeTruthy();
								expect(p3.sharesEdge(p2)).toBeTruthy();
							});

							it("shouldn't detect a shared edge", function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									v4 = vector2.factory(100, 100),
									v5 = vector2.factory(150, 100),
									p1 = poly2.factory(v1, v2, v3),
									p2 = poly2.factory(v2, v3, v4),
									p3 = poly2.factory(v3, v4, v5);

								expect(p1.sharesEdge(p3)).toBeFalsy();
							});
						});//sharesEdge

						expect(typeof instance.isVector2Internal).toEqual('function');
						describe('isVector2Internal', function () {
							it('should detect is a vector2 is within a poly', function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									ps = [
										poly2.factory(v1, v2, v3),
										poly2.factory(v2, v3, v1),
										poly2.factory(v3, v1, v2),
										poly2.factory(v3, v2, v1),
										poly2.factory(v2, v1, v3),
										poly2.factory(v1, v3, v2)
									],
									counter = 0,
									i,	// Used for loop control
									ii;	// Used for loop delimiting

								for (i = 0, ii = ps.length; i < ii; i += 1) {
									expect(ps[i].isVector2Internal(vector2.factory(0, 0))).toBeTruthy();

									expect(ps[i].isVector2Internal(vector2.factory(0, 100))).toBeTruthy();
									expect(ps[i].isVector2Internal(vector2.factory(100, 0))).toBeTruthy();
									expect(ps[i].isVector2Internal(vector2.factory(40, 40))).toBeTruthy();
									expect(ps[i].isVector2Internal(vector2.factory(50, 0))).toBeTruthy();
									expect(ps[i].isVector2Internal(vector2.factory(0, 50))).toBeTruthy();
									expect(ps[i].isVector2Internal(vector2.factory(50, 50))).toBeTruthy();

									expect(ps[i].isVector2Internal(vector2.factory(50.00001, 50.00001))).toBeFalsy();
									expect(ps[i].isVector2Internal(vector2.factory(101, 0))).toBeFalsy();
									expect(ps[i].isVector2Internal(vector2.factory(0, 101))).toBeFalsy();
									expect(ps[i].isVector2Internal(vector2.factory(-1, -1))).toBeFalsy();
									expect(ps[i].isVector2Internal(vector2.factory(-1, 0))).toBeFalsy();
									expect(ps[i].isVector2Internal(vector2.factory(0, -1))).toBeFalsy();

									counter += 1;
								}

								//expect(counter).toEqual(ps.length);
							});
						});//isVector2Internal

						expect(typeof instance.uncommonVector2).toEqual('function');
						describe('uncommonVector2', function () {
							it('should find the uncommon point in a poly', function () {
								var
									v1 = vector2.factory(0, 0),
									v2 = vector2.factory(0, 100),
									v3 = vector2.factory(100, 0),
									ps = [
										poly2.factory(v1, v2, v3),
										poly2.factory(v2, v3, v1),
										poly2.factory(v3, v1, v2),
										poly2.factory(v3, v2, v1),
										poly2.factory(v2, v1, v3),
										poly2.factory(v1, v3, v2)
									],
									counter = 0,
									i,	// Used for loop control
									ii;	// Used for loop delimiting

								// Loop over the permutations of possible poly2s
								for (i = 0, ii = ps.length; i < ii; i += 1) {
									expect(ps[i].uncommonVector2([v2, v3]))
										.toEqual(v1);
								}
								for (i = 0, ii = ps.length; i < ii; i += 1) {
									expect(ps[i].uncommonVector2([v1, v3]))
										.toEqual(v2);
								}
								for (i = 0, ii = ps.length; i < ii; i += 1) {
									expect(ps[i].uncommonVector2([v1, v2]))
										.toEqual(v3);
								}
							});//it
						});//uncommonVector2
					});//it
				});//desc factory

				describe('findAngles', function () {
					it('should find the internal angels in a poly2', function () {
						//console.log('TODO - write specs for findAngles');
					});
				});//desc poly2.findAngles

				describe('findDistanceFromLineSegment', function () {
					it('should find the distance from a line segment', function () {
						//console.log('TODO - write specs for findDistanceFromLineSegment');
					});
				});//desc poly2.findDistanceFromLineSegment
			});
		});// desc a poly2
	});//instanceof thorny
}());


text:
package org.wscale.mountains.config;

import static org.mockito.Mockito.mock;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.wscale.mountains.service.MountainService;

@Configuration
public class WebserviceConfig {

    /**
     * This method replaces the MountainService Implementation from the business layer for our integration tests with
     * an Mockito mock object. It gets automatically called when we execute our tests and want to Autowire a
     * MountainService object.
     * @return - A mock object of the MountainService Interface.
     */
    @Bean
    public MountainService mountainService(){
        return mock(MountainService.class);
    }

}


text:
import 'normalize.css';
import 'font-awesome/css/font-awesome.css';

import React from 'react';
import { render } from 'react-dom';

import InlineToggleButtonWidget from 'paraviewweb/src/React/Widgets/InlineToggleButtonWidget';
import logo from 'paraviewweb/documentation/images/ui.png';

function onChange(obj, idx) {
  console.log('Active', obj, idx);
}

render(
  React.createElement(InlineToggleButtonWidget, {
    activeColor: 'red',
    defaultColor: 'green',
    height: '0.75em',
    options: [
      { label: 'First' },
      { label: 'A' },
      { label: 'B' },
      { label: 'C' },
      { img: logo },
      { icon: 'fa fa-twitter' },
      { label: 'Last' },
    ],
    onChange,
  }),
  document.querySelector('.content')
);


text:
using System;
using Nessos.LinqOptimizer.CSharp;
using Obscur.Core.Cryptography.Support;
using Obscur.Core.Cryptography.Support.Math;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Endomorphism;

namespace Obscur.Core.Cryptography.Information.EllipticCurve
{
    ///
    ///     Information for a named elliptic curve over F(p)
    ///     that uses a custom implementation for computations.
    ///
    public class CustomFpEcCurveInformation : EcCurveInformation
    {
        protected readonly Func<ECCurve> CurveFunc;
        protected readonly GlvTypeBParameters GlvParameters;

        ///
        ///     Create a new instance of the custom-implementation F(p) curve information class,
        ///     CustomFpEcNamedCurveInformation.
        ///
        /// <param name="curve">Custom curve function.</param>
        /// <param name="glvParams">GLV endomorphism parameters, if any.</param>
        public CustomFpEcCurveInformation(Func<ECCurve> curve, GlvTypeBParameters glvParams = null)
        {
            Field = CurveField.Fp;
            GlvParameters = glvParams;

            if (GlvParameters != null) {
                CurveFunc = () => {
                    ECCurve c = curve();
                    c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, GlvParameters)).Create();
                    return c;
                };
            } else {
                CurveFunc = curve;
            }
        }

        ///
        ///     Base point
        ///
        public string G { get; protected internal set; }

        public string Seed { get; protected internal set; }

        /// <inheritdoc />
        public override ECDomainParameters GetParameters()
        {
            ECCurve curve = CurveFunc();
            return new ECDomainParameters(curve, curve.DecodePoint(G.HexToBinary()), curve.Order, curve.Cofactor,
                String.IsNullOrEmpty(Seed) ? null : Seed.HexToBinary());
        }

        public static GlvTypeBParameters CreateEndomorphismParameters(string beta, string lambda, string[] v1,
            string[] v2, string g1, string g2, int bits)
        {
            BigInteger[] v1_ = v1.AsQueryExpr().Select(s => new BigInteger(s, 16)).ToArray().Run();
            BigInteger[] v2_ = v2.AsQueryExpr().Select(s => new BigInteger(s, 16)).ToArray().Run();

            return new GlvTypeBParameters(
                new BigInteger(beta, 16),
                new BigInteger(lambda, 16),
                v1_,
                v2_,
                new BigInteger(g1, 16),
                new BigInteger(g2, 16),
                bits);
        }
    }
}


text:
MO_NAMESPACE_BEGIN

MO_FR_DECLARE void MoFeatureResourceInitialize();
MO_FR_DECLARE void MoFeatureResourceStartup();
MO_FR_DECLARE void MoFeatureResourceShutdown();
MO_FR_DECLARE void MoFeatureResourceRelease();

MO_NAMESPACE_END

#endif //__MO_FEATURE_RESOURCE_H__


text:
package org.araneaframework.uilib.list;

import org.araneaframework.backend.util.BeanUtil;

/**
 * This class extends the functionality of TypeHelper for BeanListWidgets.
 *
 * @author Martti Tamm (martti@araneaframework.org)
 * @see BeanListWidget
 * @since 1.2
 */
public class BeanTypeHelper extends TypeHelper {

  protected Class<?> beanType;

  public BeanTypeHelper(Class<?> beanType) {
    this.beanType = beanType;
  }

  // Configuration
  @Override
  public Class<?> getFieldType(String fieldId) {
    Class<?> result = super.getFieldType(fieldId);
    if (result == null) {
      result = BeanUtil.getPropertyType(this.beanType, fieldId);
    }
    return result;
  }
}


text:
package io.github.factoryfx.dom.rest;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.eclipse.jetty.http.MimeTypes;

import io.github.factoryfx.factory.FactoryBase;
import io.github.factoryfx.factory.FactoryTreeBuilderBasedAttributeSetup;
import io.github.factoryfx.factory.attribute.AttributeAndMetadata;
import io.github.factoryfx.factory.attribute.dependency.FactoryViewAttribute;
import io.github.factoryfx.factory.attribute.dependency.FactoryViewListAttribute;
import io.github.factoryfx.factory.attribute.types.EncryptedString;
import io.github.factoryfx.microservice.rest.MicroserviceResource;
import io.github.factoryfx.server.Microservice;
import io.github.factoryfx.server.user.UserManagement;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

public class MicroserviceDomResource<R extends FactoryBase<?,R>> extends MicroserviceResource<R> {
    private final StaticFileAccess staticFileAccess;
    private final FactoryTreeBuilderBasedAttributeSetup<R> factoryTreeBuilderBasedAttributeSetup;
    private final Function<R,List<GuiNavbarItem>> guiNavbarItemCreator;
    private final String projectName;

    public MicroserviceDomResource(Microservice<?, R> microservice, UserManagement userManagement, StaticFileAccess staticFileAccess, FactoryTreeBuilderBasedAttributeSetup<R> factoryTreeBuilderBasedAttributeSetup, Function<R, List<GuiNavbarItem>> guiNavbarItemCreator, String projectName) {
        super(microservice, userManagement);
        this.staticFileAccess = staticFileAccess;
        this.factoryTreeBuilderBasedAttributeSetup = factoryTreeBuilderBasedAttributeSetup;
        this.guiNavbarItemCreator = guiNavbarItemCreator;
        this.projectName = projectName;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/metadata")
    public DomGuiMetadata getDynamicDataDictionary() {
        R root = microservice.prepareNewFactory().root;
        return new DomGuiMetadata(new DynamicDataDictionary(root),new GuiConfiguration(projectName,guiNavbarItemCreator.apply(root)));
    }

    @GET
    @Path("/{path:.*}")
    public Response get(@PathParam("path") String path) {
        if (com.google.common.io.Files.getFileExtension(path).isEmpty()) {//https://github.com/Microsoft/TypeScript/issues/16577
            path=path+".js";
        }

        MimeTypes mimeTypes = new MimeTypes();
        return Response.ok(staticFileAccess.getFile(path)).
                header("Content-Type", mimeTypes.getMimeByExtension(path)).build();
    }

    @POST
    @Path("/createNewFactories")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public CreateNewFactoriesResponse createNewFactories(AttributeAdressingRequest request) {
        CreateNewFactoriesResponse<R> response = new CreateNewFactoriesResponse<>();

        AttributeAndMetadata attribute = resolveAttribute(request);
        if (attribute.attributeMetadata.liveObjectClass!=null) {
            response.factories = factoryTreeBuilderBasedAttributeSetup.createNewFactory(attribute.attributeMetadata.liveObjectClass);
            response.dynamicDataDictionary = new DynamicDataDictionary(response.factories);
            return response;
        }
        //TODO select dialog if multiple in gui
        throw new IllegalArgumentException("no liveObjectClass found for: "+request);
    }

    public static class CreateNewFactoriesResponse<R extends FactoryBase<?,R>>{
        public List<? extends FactoryBase<?, R>> factories;
        public DynamicDataDictionary dynamicDataDictionary;
    }

    public static class AttributeAdressingRequest {
        public String factoryId;
        public String attributeVariableName;
        public FactoryBase<?,?> root;

        @Override
        public String toString() {
            return "AttributeAdressingRequest{" + "factoryId='" + factoryId + '\'' + ", attributeVariableName='" + attributeVariableName + '\'' + ", root=" + root + '}';
        }
    }

    public static class ResolveViewResponse{
        public String factoryId;

        public ResolveViewResponse(String factoryId) {
            this.factoryId = factoryId;
        }
    }

    @POST
    @Path("/resolveViewRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @SuppressWarnings("unchecked")
    public ResolveViewResponse resolveViewRequest(AttributeAdressingRequest request) {
        return new ResolveViewResponse(((FactoryViewAttribute<R,?,?>)resolveAttribute(request).attribute).get().getId().toString());
    }

    private AttributeAndMetadata resolveAttribute(AttributeAdressingRequest request) {
        request.root.internal().finalise();
        Map<UUID, ? extends FactoryBase<?, ?>> uuidFactoryBaseMap = request.root.internal().collectChildFactoryMap();
        return uuidFactoryBaseMap.get(UUID.fromString(request.factoryId)).internal().getAttribute(request.attributeVariableName);
    }

    @POST
    @Path("/resolveViewList")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @SuppressWarnings("unchecked")
    public List<String> resolveViewList(AttributeAdressingRequest request) {
        return ((FactoryViewListAttribute<R,?,?>)resolveAttribute(request).attribute).get().stream().map(f->f.getId().toString()).collect(Collectors.toList());
    }

    @POST
    @Path("/decryptAttribute")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public DecryptAttributeResponse decryptAttribute(DecryptAttributeRequest request) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return new DecryptAttributeResponse(new EncryptedString(request.encryptedText).decrypt(request.key));
    }

    public static class DecryptAttributeRequest  {
        public String key;
        public String encryptedText;
    }

    public static class DecryptAttributeResponse{
        public String text;

        public DecryptAttributeResponse(String text) {
            this.text = text;
        }
    }

    @POST
    @Path("/encryptAttribute")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public EncryptAttributeResponse encryptAttribute(EncryptAttributeRequest request) {
        return new EncryptAttributeResponse(new EncryptedString(request.text,request.key).getEncryptedString());

    }

    public static class EncryptAttributeRequest{
        public String text;
        public String key;
    }

    public static class EncryptAttributeResponse{
        public String  encryptedText;

        public EncryptAttributeResponse(String encryptedText) {
            this.encryptedText = encryptedText;
        }
    }

}


text:
RSpec::Matchers.define :have_cluster_member do |name|
  match do |cluster_identifier|
    cluster_identifier.has_cluster_member?(name, @is_writer)
  end

  chain :is_writer do |is_writer|
    @is_writer = is_writer
  end
end


text:
package com.amazonaws.services.athena.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchGetPreparedStatementRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * A list of prepared statement names to return.
     *

     */
    private java.util.List<String> preparedStatementNames;
    /**
     *

     * The name of the workgroup to which the prepared statements belong.
     *

     */
    private String workGroup;

    /**
     *

     * A list of prepared statement names to return.
     *

     *
     * @return A list of prepared statement names to return.
     */

    public java.util.List<String> getPreparedStatementNames() {
        return preparedStatementNames;
    }

    /**
     *

     * A list of prepared statement names to return.
     *

     *
     * @param preparedStatementNames
     *        A list of prepared statement names to return.
     */

    public void setPreparedStatementNames(java.util.Collection<String> preparedStatementNames) {
        if (preparedStatementNames == null) {
            this.preparedStatementNames = null;
            return;
        }

        this.preparedStatementNames = new java.util.ArrayList<String>(preparedStatementNames);
    }

    /**
     *

     * A list of prepared statement names to return.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setPreparedStatementNames(java.util.Collection)} or
     * {@link #withPreparedStatementNames(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param preparedStatementNames
     *        A list of prepared statement names to return.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchGetPreparedStatementRequest withPreparedStatementNames(String... preparedStatementNames) {
        if (this.preparedStatementNames == null) {
            setPreparedStatementNames(new java.util.ArrayList<String>(preparedStatementNames.length));
        }
        for (String ele : preparedStatementNames) {
            this.preparedStatementNames.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of prepared statement names to return.
     *

     *
     * @param preparedStatementNames
     *        A list of prepared statement names to return.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchGetPreparedStatementRequest withPreparedStatementNames(java.util.Collection<String> preparedStatementNames) {
        setPreparedStatementNames(preparedStatementNames);
        return this;
    }

    /**
     *

     * The name of the workgroup to which the prepared statements belong.
     *

     *
     * @param workGroup
     *        The name of the workgroup to which the prepared statements belong.
     */

    public void setWorkGroup(String workGroup) {
        this.workGroup = workGroup;
    }

    /**
     *

     * The name of the workgroup to which the prepared statements belong.
     *

     *
     * @return The name of the workgroup to which the prepared statements belong.
     */

    public String getWorkGroup() {
        return this.workGroup;
    }

    /**
     *

     * The name of the workgroup to which the prepared statements belong.
     *

     *
     * @param workGroup
     *        The name of the workgroup to which the prepared statements belong.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchGetPreparedStatementRequest withWorkGroup(String workGroup) {
        setWorkGroup(workGroup);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPreparedStatementNames() != null)
            sb.append("PreparedStatementNames: ").append(getPreparedStatementNames()).append(",");
        if (getWorkGroup() != null)
            sb.append("WorkGroup: ").append(getWorkGroup());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof BatchGetPreparedStatementRequest == false)
            return false;
        BatchGetPreparedStatementRequest other = (BatchGetPreparedStatementRequest) obj;
        if (other.getPreparedStatementNames() == null ^ this.getPreparedStatementNames() == null)
            return false;
        if (other.getPreparedStatementNames() != null && other.getPreparedStatementNames().equals(this.getPreparedStatementNames()) == false)
            return false;
        if (other.getWorkGroup() == null ^ this.getWorkGroup() == null)
            return false;
        if (other.getWorkGroup() != null && other.getWorkGroup().equals(this.getWorkGroup()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getPreparedStatementNames() == null) ? 0 : getPreparedStatementNames().hashCode());
        hashCode = prime * hashCode + ((getWorkGroup() == null) ? 0 : getWorkGroup().hashCode());
        return hashCode;
    }

    @Override
    public BatchGetPreparedStatementRequest clone() {
        return (BatchGetPreparedStatementRequest) super.clone();
    }

}