text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for DatastoreFileDeletedEvent complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DatastoreFileDeletedEvent">
 *   <complexContent>
 *     <extension base="{urn:vim25}DatastoreFileEvent">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DatastoreFileDeletedEvent")
public class DatastoreFileDeletedEvent
    extends DatastoreFileEvent
{

}


text:
/**
 * @requires OpenLayers/Format/WMSDescribeLayer.js
 * @requires OpenLayers/Format/OGCExceptionReport.js
 */

/**
 * Class: OpenLayers.Format.WMSDescribeLayer.v1_1_1
 * Read SLD WMS DescribeLayer response for WMS 1.1.X
 * WMS 1.1.X is tightly coupled to SLD 1.0.0
 *
 * Example DescribeLayer request:
 * http://demo.opengeo.org/geoserver/wms?request=DescribeLayer&version=1.1.1&layers=topp:states
 *
 * Inherits from:
 *  - <OpenLayers.Format.WMSDescribeLayer>
 */
OpenLayers.Format.WMSDescribeLayer.v1_1_1 = OpenLayers.Class(
    OpenLayers.Format.WMSDescribeLayer, {

    /**
     * Constructor: OpenLayers.Format.WMSDescribeLayer
     * Create a new parser for WMS DescribeLayer responses.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */
    initialize: function(options) {
        OpenLayers.Format.WMSDescribeLayer.prototype.initialize.apply(this,
            [options]);
    },

    /**
     * APIMethod: read
     * Read DescribeLayer data from a string, and return the response.
     * The OGC defines 2 formats which are allowed for output,
     * so we need to parse these 2 types for version 1.1.X
     *
     * Parameters:
     * data - {String} or {DOMElement} data to read/parse.
     *
     * Returns:
     * {Object} Object with a layerDescriptions property, which holds an Array
     * of {<LayerDescription>} objects which have:
     * - {String} owsType: WFS/WCS
     * - {String} owsURL: the online resource
     * - {String} typeName: the name of the typename on the owsType service
     * - {String} layerName: the name of the WMS layer we did a lookup for
     */
    read: function(data) {
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var root = data.documentElement;
        var children = root.childNodes;
        var describelayer = {layerDescriptions: []};
        var childNode, nodeName;
        for(var i=0; i<children.length; ++i) {
            childNode = children[i];
            nodeName = childNode.nodeName;
            if (nodeName == 'LayerDescription') {
                var layerName = childNode.getAttribute('name');
                var owsType = '';
                var owsURL = '';
                var typeName = '';
                // check for owsType and owsURL attributes
                if (childNode.getAttribute('owsType')) {
                  owsType = childNode.getAttribute('owsType');
                  owsURL = childNode.getAttribute('owsURL');
                } else {
                    // look for wfs or wcs attribute
                    if (childNode.getAttribute('wfs') != '') {
                        owsType = 'WFS';
                        owsURL = childNode.getAttribute('wfs');
                    } else if (childNode.getAttribute('wcs') != '') {
                        owsType = 'WCS';
                        owsURL = childNode.getAttribute('wcs');
                    }
                }
                // look for Query child
                var query = childNode.getElementsByTagName('Query');
                if(query.length > 0) {
                    typeName = query[0].getAttribute('typeName');
                    if (!typeName) {
                        // because of Ionic bug
                        typeName = query[0].getAttribute('typename');
                    }
                }
                var layerDescription = {
                    layerName: layerName, owsType: owsType,
                    owsURL: owsURL, typeName: typeName
                };
                describelayer.layerDescriptions.push(layerDescription);

                //TODO do this in deprecated.js instead:
                // array style index for backwards compatibility
                describelayer.length = describelayer.layerDescriptions.length;
                describelayer[describelayer.length - 1] = layerDescription;

            } else if (nodeName == 'ServiceException') {
                // an exception must have occurred, so parse it
                var parser = new OpenLayers.Format.OGCExceptionReport();
                return {
                    error: parser.read(data)
                };
            }
        }
        return describelayer;
    },

    CLASS_NAME: "OpenLayers.Format.WMSDescribeLayer.v1_1_1"

});

// Version alias - workaround for http://trac.osgeo.org/mapserver/ticket/2257
OpenLayers.Format.WMSDescribeLayer.v1_1_0 =
    OpenLayers.Format.WMSDescribeLayer.v1_1_1;

redpajama_set_name: RedPajamaGithub


text:
extern crate rand;

struct Error;

#[deriving(Clone)]
struct Struct {
    x: Error //~ ERROR
}

fn main() {}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Functional;

use Doctrine\ODM\MongoDB\Tests\BaseTest;
use Documents\Account;
use Documents\User;

class PersistingTest extends BaseTest
{
    public function testCascadeInsertUpdateAndRemove()
    {
        $account = new Account();
        $account->setName('Jon Test Account');

        $user = new User();
        $user->setUsername('jon');
        $user->setPassword('changeme');
        $user->setAccount($account);

        $this->dm->persist($user);
        $this->dm->flush();

        $account->setName('w00t');
        $this->dm->flush();

        $this->assertEquals('w00t', $user->getAccount()->getName());

        $this->dm->remove($user);
        $this->dm->flush();
        $this->dm->clear();
    }

    public function testUpdate()
    {
        $user = new User();
        $user->setInheritedProperty('cool');
        $user->setUsername('jon');
        $user->setPassword('changeme');

        $this->dm->persist($user);
        $this->dm->flush();
        $this->dm->clear();

        $user = $this->dm->find(User::class, $user->getId());

        $this->assertNotNull($user);
        $user->setUsername('w00t');
        $this->dm->flush();
        $this->dm->clear();

        $user = $this->dm->find(User::class, $user->getId());
        $this->assertNotNull($user);
        $this->assertEquals('w00t', $user->getUsername());
        $this->assertEquals('cool', $user->getInheritedProperty());
    }

    public function testDetach()
    {
        $user = new User();
        $user->setUsername('jon');
        $user->setPassword('changeme');
        $this->dm->persist($user);
        $this->dm->flush();

        $user->setUsername('whoop');
        $this->dm->detach($user);
        $this->dm->flush();
        $this->dm->clear();

        $user2 = $this->dm->find(User::class, $user->getId());
        $this->assertNotNull($user2);
        $this->assertEquals('jon', $user2->getUsername());
    }
}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * CreateVpnGatewayRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateVpnGatewayRequestMarshaller implements Marshaller<Request<CreateVpnGatewayRequest>, CreateVpnGatewayRequest> {

    public Request<CreateVpnGatewayRequest> marshall(CreateVpnGatewayRequest createVpnGatewayRequest) {

        if (createVpnGatewayRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<CreateVpnGatewayRequest> request = new DefaultRequest<CreateVpnGatewayRequest>(createVpnGatewayRequest, "AmazonEC2");
        request.addParameter("Action", "CreateVpnGateway");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (createVpnGatewayRequest.getAvailabilityZone() != null) {
            request.addParameter("AvailabilityZone", StringUtils.fromString(createVpnGatewayRequest.getAvailabilityZone()));
        }

        if (createVpnGatewayRequest.getType() != null) {
            request.addParameter("Type", StringUtils.fromString(createVpnGatewayRequest.getType()));
        }

        if (createVpnGatewayRequest.getAmazonSideAsn() != null) {
            request.addParameter("AmazonSideAsn", StringUtils.fromLong(createVpnGatewayRequest.getAmazonSideAsn()));
        }

        return request;
    }

}


text:
function [cmask, smask] = gabormask(Size, sigma, period, orient)
%GABORMASK Create Gabor-function masks according to the formulae
%                                     2         2
%       cmask(y+hy, x+hx) = N * exp(-r /(2*sigma )) * cos(x' * omega)
%                                     2         2
%       smask(y+hy, x+hx) = N * exp(-r /(2*sigma )) * sin(x' * omega)
%   where
%        2     2    2
%       r  =  x  + y
%       x' =  x * cos(orient) + y * sin(orient)
%       omega = 2*pi / period
%
%       N is a real normalisation constant such that if the mask is
%       convolved with a sine grating of unity amplitude and the period
%       and orientation of the mask, the output will have unity
%       amplitude.
%
%       hy and hx are the mask centre coordinates, i.e. for a
%       SIZEY-by-SIZEX mask they are (SIZEY-1)/2+1 and (SIZEX-1)/2+1.
%
%   [C,S] = GABORMASK creates a 27x27 arrays containing the masks with
%   sigma=5, period=10*sqrt(2) and orient=0.
%
%   [C,S] = GABORMASK(SIZE) is like the last case except that SIZE is a
%   1-by-2 vector giving the number of rows and columns in C and S. SIZE
%   can also be a scalar in which case the mask is SIZE-by-SIZE.
%
%   [C,S] = GABORMASK(SIZE, SIGMA) creates masks with the given size and
%   sigma. If SIZE is specified as [] then 2*round(2.575*SIGMA)+1 is
%   used for both rows and columns. The period is SIGMA*2*sqrt(2) and
%   orient=0.
%
%   [C,S] = GABORMASK(SIZE, SIGMA, PERIOD) is like the last case except
%   that both sigma and period are specified. Either may be given as []
%   in which case the ratio period/sigma is set to 2*sqrt(2).
%
%   [C,S] = GABORMASK(SIZE, SIGMA, PERIOD, ORIENT) is as the previous
%   cases except that the orientation of the masks is specified.

% David Young, Department of Informatics, University of Sussex, January 2002
% revised January 2009

% Sort out arguments and their defaults
if nargin < 4; orient = 0; end;
if nargin < 3; period = []; end;
if nargin < 2; sigma = []; end;
if nargin < 1; Size = []; end;

if isempty(period) && isempty(sigma); sigma = 5; end;
if isempty(period); period = sigma*2*sqrt(2); end;
if isempty(sigma); sigma = period/(2*sqrt(2)); end;
if isempty(Size); Size = 2*round(2.575*sigma) + 1; end; % small error

if length(Size) == 1
    sx = Size-1; sy = sx;
elseif all(size(Size) == [1 2])
    sy = Size(1)-1; sx = Size(2)-1;
else
    error('Size must be scalar or 1-by-2 vector');
end;

% Basic grid
hy = sy/2; hx = sx/2;
[x, y] = meshgrid(-hx:sx-hx, -hy:sy-hy);

% Parameters
omega = 2*pi/period;
cs = omega * cos(orient);
sn = omega * sin(orient);
k = -1/(2*sigma*sigma);

% Main computations
g = exp(k * (x.*x + y.*y));     % Gaussian mask
xp = x * cs + y * sn;           % Rotated x coords, phase
cx = cos(xp);                   % cos grating
cmask = g .* cx;                % modulated cos grating
sx = sin(xp);                   % sin grating
smask = g .* sx;                % modulated sin grating

% Normalise so that convolution of mask with a harmonic curve of the
% matching frequency gives unity peaks
cnorm = sum(sum(cmask.*cx));
cmask = cmask/cnorm;
snorm = sum(sum(smask.*sx));
smask = smask/snorm;


text:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-main-menu',
  templateUrl: './main-menu.component.html',
  styleUrls: ['./main-menu.component.css']
})
export class MainMenuComponent implements OnInit {

  constructor(private auth: AuthService) { }

  ngOnInit() {
  }

  onLogout() {
    this.auth.onLogout();
  }

}


text:
namespace fml {
namespace icu {

void InitializeICU(const std::string& icu_data_path = "");

}  // namespace icu
}  // namespace fml

#endif  // FLUTTER_FML_ICU_UTIL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>quarkus-integration-tests-parent</artifactId>
        <groupId>io.quarkus</groupId>
        <version>999-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>quarkus-integration-test-jpa-derby</artifactId>
    <name>Quarkus - Integration Tests - JPA - Derby</name>
    <description>Module that contains JPA related tests running with the Derby database</description>
    <dependencies>
        <!-- Enables the JPA capabilities -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-hibernate-orm</artifactId>
        </dependency>
        <!-- We'll be using the Derby database -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-jdbc-derby</artifactId>
        </dependency>
        <!-- .. and some REST endpoints -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-undertow</artifactId>
        </dependency>

        <!-- test dependencies -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-junit5</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-test-derby</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Minimal test dependencies to *-deployment artifacts for consistent build order -->
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-hibernate-orm-deployment</artifactId>
            <version>${project.version}</version>
            <type>pom</type>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-jdbc-derby-deployment</artifactId>
            <version>${project.version}</version>
            <type>pom</type>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-undertow-deployment</artifactId>
            <version>${project.version}</version>
            <type>pom</type>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>io.quarkus</groupId>
                <artifactId>quarkus-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
IS24 API SDK v0.2.16 (restapi-java-sdk)
==========================
Author:     Martin Flügge

Copyright:  Immobilien Scout GmbH

Link:       http://www.immobilienscout24.de

Das IS24 API SDK von ImmobilienScout24 steht unter der Apache Common License v2.0 zur Verfügung und kann für private sowie kommerzielle Projekte eingesetzt werden. Lediglich die Verweise wie Copyright, Autor, etc. müssen in den Dateien erhalten bleiben. Weitere Infos zur Lizenz befinden sich unter http://www.apache.org/licenses/LICENSE-2.0.

History
=======

Who  		  | When 		  | What
------------- | ------------- | -------------
mfluegge  	  | 10th June 2014| initial commit
mfluegge  	  | 10th June 2014| v0.1 beta
mfluegge  	  | 3th November 2014| v0.2 beta
mfluegge  	  | 4th November 2014| v0.2.3
dsostin  	  | 26th February 2015| v0.2.9
dsostin  	  | 02th July 2015| v0.2.10
fmielke       | 31th August 2015| v0.2.11
fmielke       | 5th September 2016| v0.2.15
mfluegge      | 5th February 2018| v0.2.16

v0.2.16
----------

Ensured that "https" is mandatory as IS24 will not support "http" anymore.

v0.2.15
----------

Delete xml-non-confirm characters at reading response bodies as xml.

v0.2.11
----------

bugfix POST attachment(url)

v0.2.10
----------
sdk make all requests using https.

v0.2.9
----------

bug fix for create video attachment

v0.2.3
----------

Added externalId, message and messageCode to ShowcasePlacement, TopPlacment and PremiumPlacement.

v0.2.1
----------

Had to change artifactid to "restapi-java-sdk".

v0.2 beta
----------

- createRealestate(String username, RealEstate realestate) uses energy certificate data by default
- update realeste
- upload of FileMultimediaObject now throw MaximumNumberOfAttachmentsReachedException when trying to upload attchment #31
- user can retrieve realestate project for a given realestate id
- realestate projects can be upated
- several methods to add realestates to a realestes projects were introduced
- realestates can be deleted from realestate projects
- On top products can be placed on realestates
- user can retrieve a list of on top products placed an a specific realestate
- On top products can be removed from realestates
- user can get a list of entitlements for a given username
- user can get a specific entitlement by name for a given user


text:
@extends('admin.home')

@section('title', 'Group List')

@section('content')

Group List

			Create New Group

				@if (count($errors) > 0)

						@foreach ($errors->all() as $error)

{{ $error }}

						@endforeach

				@endif

					@if (Session::has('success'))

{{ Session::get('success') }}

			    	@endif

					@if(count($role)>0)

									{!! Form::checkbox('check_all_groups', 'value', null, ['id' => 'check_all_groups'])!!}
									SELECT ALL

							Name
							Slug

						@foreach($role as $data => $value)

								{!! Form::checkbox('group_list[]', $value->id, null, ['class' => 'group_list'])!!}

							{{ $value->name }}
							{{ $value->slug }}

								id) }}">Show

								id.'/edit') }}">Edit

								{!! Form::open(array('class' => 'inline_form','method'=>'DELETE','url' =>'admin/group/'.$value->id)) !!}
									{!! Form::submit('Delete', array('class' => 'btn btn-small btn-warning btn-sm')) !!}
								{!!  Form::close() !!}

						@endforeach

								{!! Form::open(array('method'=>'POST', 'url' =>'admin/group/delete-all','id' => 'delete_wrapper_form')) !!}
									{!! Form::submit('Delete All', array('class' => 'btn btn-small btn-warning btn-sm', 'id' => 'delete_all')) !!}
								{!!  Form::close() !!}

					@else

"Sorry no records found!"

					@endif

@endsection
@section('footer')
@parent

@endsection


text:
package uk.co.ribot.androidboilerplate.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import uk.co.ribot.androidboilerplate.R;
import uk.co.ribot.androidboilerplate.data.model.net.response.MessageResponse;
import uk.co.ribot.androidboilerplate.injection.component.frament.MessageFragmentComponent;
import uk.co.ribot.androidboilerplate.injection.module.ActivityModule;
import uk.co.ribot.androidboilerplate.ui.adapter.MessageAdapter;
import uk.co.ribot.androidboilerplate.ui.base.BaseFragment;
import uk.co.ribot.androidboilerplate.ui.presenter.MessagePresenter;
import uk.co.ribot.androidboilerplate.ui.view_interface.MessageMvpView;

/**
 * Created by mike on 2017/10/31.
 * 消息Frgament
 */

public class MessageFragment extends BaseFragment implements MessageMvpView {

    @Inject
    MessagePresenter mMessagePresenter;
    @Inject
    MessageAdapter mMessageAdapter;

    Unbinder unbinder;
    @BindView(R.id.rv_message)
    RecyclerView rvMessage;

    @Inject
    public MessageFragment(){}
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_message, null);
        unbinder = ButterKnife.bind(this, view);
        return warpTitleView(view);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MessageFragmentComponent messageFragmentComponent = mFragmentBaseComponent.
                messageFragmentComponent(new ActivityModule(getActivity()));
        messageFragmentComponent.inject(this);
        setTitle(R.string.fragment_message);

        rvMessage.setAdapter(mMessageAdapter);
        rvMessage.setLayoutManager(new LinearLayoutManager(getActivity()));

        mMessagePresenter.attachView(this);
        mMessagePresenter.getMessages();
        mMessageAdapter.setCanSeePrice(mMessagePresenter.isCanSeePrice());

    }

    @Override
    public void showMessage(List<MessageResponse.OrderBean> message) {
        mMessageAdapter.setRibots(message);
        mMessageAdapter.notifyDataSetChanged();

    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void showMessagesEmpty() {

    }

    @Override
    public void showMessagesError() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}


text:
package fr.fteychene.gradlejug.repository.integration;

import com.ninja_squad.dbsetup.operation.Operation;

import static com.ninja_squad.dbsetup.Operations.deleteAllFrom;

/**
 * Created by fteychene on 06/02/2015.
 */
public final class DbSetupCommonOperation {

    public static final Operation DELETE_ALL =
            deleteAllFrom("TODO");
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Heliomyces subspadoides Murrill

### Remarks
null


text:
package com.microsoft.live.test.util;

public final class AssertMessages {

    public static final String NO_EXCEPTION_THROWN = "Method was expected to throw a(n) %s";

    private AssertMessages() { throw new AssertionError(); }
}


text:
"""
File: make_lens_catalog.py
Author: Chris Davis
Description: Given database information, creates the cluster catalog and
downloads fields and cutouts.

This file is part of the Space Warps project, and is distributed
under the MIT license by the Space Warps Science Team.
http://spacewarps.org/

"""

from __future__ import print_function, division

import sys, getopt, numpy as np

import matplotlib
# Force matplotlib to not use any Xwindows backend:
matplotlib.use('Agg')

# Fonts, latex:
matplotlib.rc('font', **{'family':'serif', 'serif':['TimesNewRoman']})
matplotlib.rc('text', usetex=True)

from matplotlib import pyplot as plt

bfs, sfs = 20, 16
params = { 'axes.labelsize': bfs,
            'text.fontsize': bfs,
          'legend.fontsize': bfs,
          'xtick.labelsize': sfs,
          'ytick.labelsize': sfs}
plt.rcParams.update(params)

origin = 'lower'

import numpy as np
import pandas as pd
from urllib import FancyURLopener
from scipy.ndimage import imread
from scipy.misc import imsave
from os import path, makedirs
from ast import literal_eval

# ======================================================================
# Some parameter definitions. Can config catalog properties here or in the
# functions...
# ======================================================================

collection_categories = ['ID', 'ZooID', 'location', 'mean_probability', 'category', 'kind', 'flavor', 'state', 'status', 'truth', 'stage']
annotation_categories = ['At_X', 'At_Y', 'PD', 'PL', 'ItWas']
cluster_catalog_labels = ['object_id', 'x', 'y', 'markers_in_object', 'skill_sum', 'markers_in_field', 'people_marking_objects', 'people_marking_field', 'people_looking_at_field', 'object_size']
field_size = 440
# eps is largely determined by looking at the distribution of dispersion values
# as well as looking at actual images to get a rough sense of the tradeoff
# between accidentally misclassifying a large object as multiple and
# multiple objects as one
eps = 30#48
min_samples = 3#2
stamp_size = 96
convert_outliers = False#True

# ======================================================================

def augment_catalog(catalog, cluster_directory, augmented_directory):
    """Routine for augmenting an existent catalog

    Parameters
    ----------
    catalog : dataframe
        Catalog of all the cluster images.

    cluster_directory : path
        Location of the directory containing the cluster images.

    augmented_directory : path
        Location of the directory where the augmented data will be saved.

    Returns
    -------
    augmented_catalog : dataframe
        Takes the cluster_catalog and applies several affine transformations.

    Notes
    -----
    augmentation type: 0-3 are 90 degree rotations, 4-7 are 90 rotations plus flip

    """

    augmented_catalog = []
    augmented_catalog_columns = list(catalog.columns) + ['stamp_id', 'stamp_name', 'augment_type']
    for cati in catalog.iterrows():
        entry = cati[1]
        image_path = cluster_directory + entry['object_name']
        image = imread(image_path)
        augmented_images = augment_image(image)
        for ai, augmented_image in enumerate(augmented_images):
            stamp_id = entry['object_id'] + len(catalog) * ai
            stamp_name = '{2}_{1}_{0}.png'.format(entry['ZooID'],
                                                  entry['object_id'],
                                                  stamp_id)
            augment_type = ai
            augmented_entry = np.append(entry.values,
                                        [stamp_id, stamp_name, augment_type])
            augmented_catalog.append(augmented_entry)
            # save augmented image
            imsave(augmented_directory + stamp_name, augmented_image)
    augmented_catalog = pd.DataFrame(augmented_catalog,
                                     columns=augmented_catalog_columns)

    return augmented_catalog

def augment_image(image):
    """Do all combinations of rotations and flips

    Parameters
    ----------
    image : HxWxC array

    Returns
    -------
    augmented_images : list of images
        Eight images in total, for each combination of flip and rot90.

    """
    augmented_images = []
    for do_flip in [False, True]:
        for k in [0, 1, 2, 3]:
            augmented_image = np.rot90(image, k=k)
            if do_flip:
                augmented_image = augmented_image[:, ::-1, :]
            augmented_images.append(augmented_image)
    return augmented_images

def create_cluster_catalog_and_cutouts(collection,
        field_directory, cluster_directory,
        knownlens=None,
        eps=eps, min_samples=min_samples,
        convert_outliers=convert_outliers,
        do_a_few=None):
    """Main routine for creating the cluster catalog.

    Parameters
    ----------
    collection : dataframe of swap objects.
        Contains collection_categories and annotation_categories

    knownlens : pandas dataframe

    Returns
    -------
    catalog : cluster catalog with the following columns

    Notes
    -----

    """

    # create cluster catalog from collection
    print('creating incomplete cluster catalog')
    catalog = create_incomplete_cluster_catalog(collection,
        eps=eps, min_samples=min_samples,
        convert_outliers=convert_outliers,
        do_a_few=do_a_few)
    print('incomplete cluster catalog created!')

    # update the cluster catalog with some file information
    field_names = []
    cluster_names = []
    for cati in catalog.iterrows():
        entry = cati[1]
        field_names.append('{0}.png'.format(entry['ZooID']))
        cluster_names.append('{1}_{0}.png'.format(entry['ZooID'],
                                                  entry['object_id']))
    catalog['field_name'] = field_names
    catalog['object_name'] = cluster_names

    # now download and create the cutouts
    # make sure these paths exist!
    alphas = create_cluster_cutouts(catalog,
        field_directory, cluster_directory, stamp_size=stamp_size)
    print('cluster cutouts created!')

    # alphas
    cluster_types = []
    for cati in catalog.iterrows():
        cati, entry = cati
        alpha = alphas[cati]
        field_flavor = entry['field_flavor']
        if 'lens' in field_flavor:
            if alpha == 1:
                cluster_type = 'simulated ' + field_flavor
            else:
                cluster_type = 'dud'
        elif 'test' in field_flavor:
            cluster_type = 'unknown'
        elif 'dud' in field_flavor:
            cluster_type = 'dud'
        else:
            raise Exception('Unrecognized field_flavor {0}'.format(field_flavor))
        cluster_types.append(cluster_type)
    print('alphas done')

    # knownlens
    # cludgey way to ensure we have the item
    if type(knownlens) != type(None):
        catalog_zooid_index = catalog.index
        catalog_zooid = catalog.set_index(['ZooID'])
        catalog_zooid['index'] = catalog_zooid_index
        for kl in knownlens.iterrows():
            x = kl[1]['x']
            y = 440 - kl[1]['y']
            zooid = kl[1]['ZooID']
            if zooid in catalog_zooid.index:
                cci = catalog_zooid.loc[zooid]
                ccx = cci['x']
                ccy = cci['y']
                l2 = np.square(x - ccx) + np.square(y - ccy)
                if type(l2) == np.float64:
                    index = cci['index']
                    cluster_types[index] = 'known lens'
                elif type(l2) != np.float64:
                    index = cci['index'][np.argmin(l2.values)]
                    cluster_types[index] = 'known lens'
        print('known lens done!')

    catalog['object_flavor'] = cluster_types

    return catalog

def create_incomplete_cluster_catalog(catalog,
                                      stamp_size=stamp_size,
                                      field_size_x=field_size,
                                      field_size_y=field_size,
                                      eps=eps, min_samples=min_samples,
                                      convert_outliers=convert_outliers,
                                      do_a_few=None):
    """Creates clustering catalog just based off of swap user clicks.

    Parameters
    ----------
    catalog : dataframe
        Contains collection_ and annotation_categories

    stamp_size : int, optional
        How big an image are we looking to make?

    field_size_x, field_size_y : int, optional
        How big are the fields we are extracting stamps from?

    eps, min_samples, convert_outliers : config parameters for outlier_clusters_dbscan

    Returns
    -------
    cluster_catalog : another dataframe
        Catalog with all the cluster entries.

    Notes
    -----
    I call this 'incomplete' because it does not have the full information I
    would like to have in the cluster catalog: things like whether the cutout
    contains a knownlens or is a bonafide training simulation cutout.

    """

    cluster_catalog = []
    cluster_id = 0
    # step through the objects in catalog
    # TODO: remove this small sampling thing
    if do_a_few:
        cat_list = np.random.choice(len(catalog), size=do_a_few)
    else:
        cat_list = xrange(len(catalog))
    for cati in cat_list:

        # get markers. The literal_eval is because the catalog entries are strings.
        x_unflat = literal_eval(catalog['At_X'][cati])
        y_unflat = literal_eval(catalog['At_Y'][cati])
        # flatten out x and y. also cut out empty entries
        x = np.array([xi for xj in x_unflat for xi in xj])
        y = np.array([yi for yj in y_unflat for yi in yj])
        did_mark = np.array([True if len(xj) > 0 else False for xj in x_unflat])
        users = np.array([xj for xj in xrange(len(x_unflat))
                          for xi in x_unflat[xj]])
        total_marked_looks = np.sum(did_mark)
        total_looks = len(x_unflat)

        # repeat for PD and PL = proxies for weight
        PL_everyone = literal_eval(catalog['PL'][cati])
        PL_unflat = []
        PD_everyone = literal_eval(catalog['PD'][cati])
        PD_unflat = []
        for i, xj in enumerate(x_unflat):
            # len(xj) of empty = 0
            PL_unflat.append([PL_everyone[i]] * len(xj))
            PD_unflat.append([PD_everyone[i]] * len(xj))

        PL = np.array([PLi for PLj in PL_unflat for PLi in PLj])
        PD = np.array([PDi for PDj in PD_unflat for PDi in PDj])
        skill = expectedInformationGain(0.5, PL, PD)

        # create weights
        # if a user clicks multiple times, downweight by that fraction
        binusers = np.bincount(users)
        w = 1. / binusers[users]

        # TODO: weight by skill?

        # cluster
        cluster_centers, cluster_labels, labels = \
            outlier_clusters_dbscan(x, y, w=w, eps=eps, min_samples=min_samples)

        # add to catalog
        for cluster_label_i, cluster_label in enumerate(cluster_labels):

            cluster_center = cluster_centers[cluster_label_i]
            x_i, y_i = cluster_center

            if np.int(np.ceil(x_i - stamp_size / 2)) >= field_size_x:
                print('Mislabled cluster? {0} {1} {2} {3}'.format(
                    cati, cluster_label_i, x_i, y_i))
                continue
            elif np.int(np.ceil(y_i - stamp_size / 2)) >= field_size_y:
                print('Mislabled cluster? {0} {1} {2} {3}'.format(
                    cati, cluster_label_i, x_i, y_i))
                continue
            elif np.int(np.floor(x_i + stamp_size / 2)) < 0:
                print('Mislabled cluster? {0} {1} {2} {3}'.format(
                    cati, cluster_label_i, x_i, y_i))
                continue
            elif np.int(np.floor(y_i + stamp_size / 2)) < 0:
                print('Mislabled cluster? {0} {1} {2} {3}'.format(
                    cati, cluster_label_i, x_i, y_i))
                continue

            members = (labels == cluster_label)  # array of booleans

            N0 = np.sum(members)
            S = np.sum(skill[members])
            Ntot = len(members)

            cluster_marked_looks = len(np.unique(users[members]))

            dispersion = np.sqrt(np.mean(np.square(x_i - x[members]) +
                                         np.square(y_i - y[members])))

            cluster_catalog_i = [catalog[category][cati] for category
                                 in collection_categories]
            # now add to the entry the things we learned about the cluster
            cluster_catalog_i += [cluster_id, x_i, y_i, N0, S, Ntot, cluster_marked_looks, total_marked_looks, total_looks, dispersion]
            cluster_catalog.append(cluster_catalog_i)
            cluster_id += 1

    cluster_catalog = pd.DataFrame(cluster_catalog, columns=collection_categories + cluster_catalog_labels)

    # we now rename one of the cluster_catalog columns
    cluster_catalog.rename(columns={'flavor': 'field_flavor'}, inplace=True)

    return cluster_catalog

def create_cluster_cutouts(catalog, field_directory, cluster_directory,
                           stamp_size=stamp_size):
    """Take a cluster catalog, download field and stamps
    """
    alphas = np.zeros(len(catalog))
    for clusteri in xrange(len(catalog)):
        # define the outputs for the images
        outname_field = field_directory + catalog['field_name'][clusteri]
        outname_cluster = cluster_directory + catalog['object_name'][clusteri]

        # get the centers
        x = catalog['x'][clusteri]
        y = catalog['y'][clusteri]

        # download the field
        im = get_online_png(catalog['location'][clusteri], outname_field)

        # create the stamp
        min_x = np.int(np.floor(x - stamp_size / 2))
        max_x = np.int(np.ceil(x + stamp_size / 2))
        min_y = np.int(np.floor(y - stamp_size / 2))
        max_y = np.int(np.ceil(y + stamp_size / 2))
        pad_min_x = 0
        pad_max_x = 0
        pad_min_y = 0
        pad_max_y = 0
        pad_trip = False
        if min_x < 0:
            pad_min_x = -min_x
            min_x = 0
            pad_trip = True
        if max_x >= im.shape[1]:
            pad_max_x = max_x - im.shape[1]
            max_x = im.shape[1]
            pad_trip = True
        if min_y < 0:
            pad_min_y = -min_y
            min_y = 0
            pad_trip = True
        if max_y >= im.shape[0]:
            pad_max_y = max_y - im.shape[0]
            max_y = im.shape[0]
            pad_trip = True

        im_cut = np.pad(im[min_y: max_y, min_x: max_x],
                        ((pad_min_y, pad_max_y), (pad_min_x, pad_max_x), (0, 0)),
                        mode='constant')
        im_cut = im_cut[:stamp_size, :stamp_size]

        # now check if the center is in a high alpha region (if alpha is included, as it is with training)
        if im.shape[2] == 4:
            im_mask = im_cut[:, :, 3].copy()
            im_cut = im_cut[:, :, :3]

            # # for some reason the numbers are not obviously formatted...
            # im_mask -= im_mask.mean()
            # im_mask /= im_mask.std()
            # im_mask[im_mask < 5] = 0
            # im_mask[im_mask >= 5] = 1

            if np.any(im_mask > 254 / 255.):
                alphas[clusteri] = 1

        imsave(outname_cluster, im_cut)

    return alphas

def convert_swap_collection_to_dataframe(collection, stage,
        collection_categories=collection_categories,
        annotation_categories=annotation_categories):
    """

    Parameters
    ----------
    collection : swap object

    stage : string
        Stage of the swap object

    collection_categories : list of strings
        Columns in the subjects that we want to collect.

    annotation_categories : list of strings
        Columns in the subjects's annotationhistory that we want to collect.

    Returns
    -------
    catalog : pandas dataframe

    Notes
    -----
    ('category', array(['test', 'training'], dtype=object))
    ('kind', array(['dud', 'sim', 'test'], dtype=object))
    ('flavor', array(['dud', u'lensed galaxy', u'lensed quasar',
                      u'lensing cluster','test'], dtype=object))
    ('state', array(['active', 'inactive'], dtype=object))
    ('status', array(['detected', 'rejected', 'undecided'], dtype=object))
    ('truth', array(['LENS', 'NOT', 'UNKNOWN'], dtype=object))

    conclusion: only need flavor, status

    """

    catalog = []
    for ID in collection.list():

        subject = collection.member[ID]
        catalog_i = []

        # flatten out x and y.
        annotationhistory = subject.annotationhistory
        x_unflat = annotationhistory['At_X']  # list of lists of clicks
        x = np.array([xi for xj in x_unflat for xi in xj])

        # cut out entries with no clicks
        if len(x) < 1:
            continue
        # oh yeah there's that absolutely nutso entry with 50k clicks. I think
        # it was the first training image? So everyone saw it. . . .
        if len(x) > 10000:
            continue

        for category in collection_categories:
            if category == 'stage':
                catalog_i.append(stage)
            else:
                catalog_i.append(subject.__dict__[category])
        for category in annotation_categories:
            catalog_i.append(list(annotationhistory[category]))

        catalog.append(catalog_i)
    # convert catalog to a dataframe
    catalog = pd.DataFrame(catalog, columns=collection_categories + annotation_categories)

    return catalog

def shannon(x):
    if isinstance(x, np.ndarray) == False:

        if x>0:
            res = x*np.log2(x)
        else:
            res = 0.0

    else:
        x[x == 0] = 1.0
        res = x*np.log2(x)

    return res

def expectedInformationGain(p0, M_ll, M_nn):
    p1 = 1-p0

    I =   p0 * (shannon(M_ll) + shannon(1-M_ll)) \
        + p1 * (shannon(M_nn) + shannon(1-M_nn)) \
        - shannon(M_ll*p0 + (1-M_nn)*p1) \
        - shannon((1-M_ll)*p0 + M_nn*p1)

    return I

def outlier_clusters_dbscan(x, y, w=None,
                            eps=eps, min_samples=min_samples,
                            convert_outliers=convert_outliers):
    """
    Parameters
    ----------
    x, y : lists of floats
        The x and y axis locations of each click.

    eps : float, optional
        The maximum distance between two samples for them to be considered
        as in the same neighborhood.
    min_samples : int, optional
        The number of samples in a neighborhood for a point to be considered
        as a core point.

    convert_outliers : binary, optional
        DBSCAN assigns outliers a cluster label -1. This says take each -1 and
        give it a unique positive value. Every click then becomes a cluster.

    Returns
    -------
    cluster_centers : array
        Each entry in cluster_centers is the center of that cluster

    cluster_labels : array
        The i-th cluster_center has label cluster_labels[i]

    labels : array
        The labels of all the points.

    Notes
    -----
    http://en.wikipedia.org/wiki/DBSCAN is a useful reference!
    Here is what wikipedia says about the algorithm:

    DBSCAN requires two parameters: eps and the minimum number of points
    required to form a dense region[a] (min_samples). It starts with an
    arbitrary starting point that has not been visited. This point's
    eps-neighborhood is retrieved, and if it contains sufficiently many points,
    a cluster is started. Otherwise, the point is labeled as noise. Note that
    this point might later be found in a sufficiently sized eps-environment of
    a different point and hence be made part of a cluster.

    If a point is found to be a dense part of a cluster, its eps-neighborhood
    is also part of that cluster. Hence, all points that are found within the
    eps-neighborhood are added, as is their own eps-neighborhood when they are
    also dense. This process continues until the density-connected cluster is
    completely found. Then, a new unvisited point is retrieved and processed,
    leading to the discovery of a further cluster or noise.
    """
    from sklearn.cluster import DBSCAN
    from sklearn.metrics import pairwise_distances

    data = np.vstack((x, y)).T

    if len(data) < min_samples:
        #print('clustering: only 1 data point!')
        #print('clustering: clustering {0} points, which is fewer than the minimum number of points {1}!'.format(len(data), min_samples))
        cluster_centers = np.array([[-1, -1]])
        cluster_labels = []
        labels = np.array([])

    else:

        clusterer = DBSCAN(eps=eps, min_samples=min_samples)
        db = clusterer.fit(data, sample_weight=w)
        labels = db.labels_
        cluster_labels = list(set(labels))
        if convert_outliers:
            # now step through all the labels and set the -1s each to a new unique label
            label_max = np.max((max(cluster_labels) + 1, 101))
            for label_i, label in enumerate(labels):
                if label == -1:
                    labels[label_i] = label_max
                    label_max += 1
            cluster_labels = list(set(labels))
        else:
            # remove -1 from cluster label definition
            cluster_labels = list(set(labels[labels != -1]))

        # it is possible that I have removed all data!
        if len(labels) == 0:
            #print('clustering: no labels remaining after outlier rejection!')
            cluster_centers = np.array([[-1, -1]])

        else:
            # find the centers of the clusters via mean
            cluster_centers = np.array([np.mean(data[labels == i], axis=0)
                                        for i in cluster_labels])

    return cluster_centers, cluster_labels, labels

# the fancy way of scraping images from the web; you gotta pretend you are a browser
class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

def get_online_png(url, outname, myopener=MyOpener()):
    fname = url.split('/')[-1]

    # download file if we don't already have it
    if not path.exists(outname):
        F = myopener.retrieve(url, outname)
    else:
        # TODO: this is glitched?
        F = [outname]
    try:
        I = imread(F[0]) * 1. / 255
    except Exception as er:
        # this field probably didn't download for *reasons*
        print(F, url, outname)
        try:
            import time
            time.sleep(10)
            I = imread(F[0]) * 1. / 255
        except TypeError as er:

            # okay let's give this another shot
            from os import remove
            remove(outname)
            F = myopener.retrieve(url, outname)
            I = imread(F[0]) * 1. / 255

    return I

if __name__ == '__main__':
    """
    python create_catalogs.py --collection /Users/cpd/Google\ Drive/cs231n/annotated_catalog.csv --knownlens /Users/cpd/Projects/strongcnn/catalog/knownlens.csv --fields /Users/cpd/Desktop/test/fields/ --clusters /Users/cpd/Desktop/test/clusters/ --augment /Users/cpd/Desktop/test/augmented/ --do_a_few 10
    """
    import argparse
    parser = argparse.ArgumentParser(description=create_cluster_catalog_and_cutouts.__doc__)

    # Required args
    parser.add_argument('--collection',
                        action='store',
                        dest='collection',
                        help='Path to annotated catalog used to create clusters and cutouts.')
    parser.add_argument('--knownlens',
                        action='store',
                        dest='knownlens',
                        default=None,
                        help='Path to csv of the knownlens catalog. If none, skips!')
    parser.add_argument('--clusters',
                        action='store',
                        dest='clusters',
                        help='Where are the clusters stored?')
    parser.add_argument('--fields',
                        action='store',
                        dest='fields',
                        default=None,  # can have an empty default!
                        help='Where are we outputting fields? If not specified, defaults to clusters argument.')
    parser.add_argument('--augment',
                        action='store',
                        dest='augment',
                        default=None,
                        help='Where are we outputting augmented results?')
    # Optional args
    parser.add_argument('--do_a_few',
                        action='store',
                        dest='do_a_few',
                        type=int,
                        default=0,
                        help='When greater than 0, do this many entries.')

    options = parser.parse_args()
    options.fields = options.fields if options.fields else options.clusters
    args = vars(options)

    do_a_few = args['do_a_few']
    field_directory = args['fields']
    cluster_directory = args['clusters']
    catalog_path = cluster_directory + '/catalog.csv'
    # make these directories
    if not path.exists(cluster_directory):
        makedirs(cluster_directory)
    if not path.exists(field_directory):
        makedirs(field_directory)

    # load up requisite files
    collection_path = args['collection']
    if '.pickle' in collection_path:
        # will need PJM's swap to interpret the spacewarps database
        try:
            import swap
        except:
            raise Exception('create_catalogs: Unable to import SpaceWarps analysis code!')

        #collection_path = base_collection_path + 'stage{0}'.format(stage) + '/CFHTLS_collection.pickle'
        collection_pickle = swap.read_pickle(collection_path, 'collection')
        stage = -1
        collection = convert_swap_collection_to_dataframe(collection_pickle, stage)
    elif '.csv' in collection_path:
        collection = pd.read_csv(collection_path)
    else:
        raise Exception('create_catalogs: No idea what kind of collection you are giving me here for {0}'.format(collection_path))

    if args['knownlens']:
        knownlens = pd.read_csv(args['knownlens'])
    else:
        knownlens = None

    # create the cluster args
    cluster_args = {'collection': collection,
                    'knownlens': knownlens,
                    'field_directory': field_directory,
                    'cluster_directory': cluster_directory,
                    'do_a_few': do_a_few}

    catalog = create_cluster_catalog_and_cutouts(**cluster_args)
    catalog.to_csv(catalog_path)

    augmented_directory = args['augment']
    if augmented_directory:
        print('create_catalogs: making augmented data!')
        augmented_catalog_path = augmented_directory + '/augmented_catalog.csv'
        if not path.exists(augmented_directory):
            makedirs(augmented_directory)
        augmented_catalog = augment_catalog(catalog, cluster_directory,
                                            augmented_directory)
        augmented_catalog.to_csv(augmented_catalog_path)


text:
<?php

// $Id$

require_once(DIR_INC.'modules/admin_panel/site_admin_ajax_grid_ctrl_ua.class.php');
require_once('ci_nom_select_grid_ctrl.class.php');

class CI_Nom_Select_Grid_Ajax_Ctrl extends Site_Admin_Ajax_Grid_Ctrl_UA {
	protected function init_transit_vars() {
		$this->add_transit_var('nom');
		$this->add_transit_var('ret');
		$this->add_transit_var('ci');
		$this->add_transit_var('ciat');
	}

	protected function create_grid_ctrl() {
		$ciat_id = $this->get_transit_var('ciat');
		$ci_id = $this->get_transit_var('ci');

		$nom_hid = $this->get_transit_var('nom');
		$nomenclature = new TCMS_Nomenclature_DBC();

		$dbc = $this->get_dbc();
		if (!$nomenclature->load_by_hid($dbc, $nom_hid)) {
			throw new Tangra_Module_Exception('Cannot find nomenclature with hid = '.$nom_hid);
		}

		$tvm = $this->get_tvm();
		$ret = new CI_Nom_select_Grid_Ctrl('ci_nom_select', $tvm, Tangra_Parameter_Method::GET, $nomenclature->get_id(), $ci_id, $ciat_id);

		return $ret;
	}
}


text:
from ctypes import *
from conman import libconman
from conman.state import *
from conman.resource import Resource

class Group(Resource):
	def __init__(self, name, state=present, gid=0):
		self._type = self._gettype()
		self.name = name
		self.state = state
		self.gid = gid

	def get(self):
		self.init()
		super(Group, self).get()
		self.deinit()

	def set(self):
		self.init()
		self._data.state = self.state
		self._data.gid = self.gid
		super(Group, self).set()


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

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

            Ruby on Rails 4.2.2

            Module
            ActiveRecord::AttributeMethods::Read::ClassMethods

/Users/benfreeman/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.2/lib/active_record/attribute_methods/read.rb

Methods

C

                cached_attributes_deprecation_warning

D

                define_method_attribute

Instance Protected methods

              cached_attributes_deprecation_warning(method_name)

            Link

                Source:
                show

# File ../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.2/lib/active_record/attribute_methods/read.rb, line 48
def cached_attributes_deprecation_warning(method_name)
  ActiveSupport::Deprecation.warn "Calling `#{method_name}` is no longer necessary. All attributes are cached."
end

              define_method_attribute(name)

            Link

                Source:
                show

# File ../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.2/lib/active_record/attribute_methods/read.rb, line 53
def define_method_attribute(name)
  method = ReaderMethodCache[name]
  generated_attribute_methods.module_eval { define_method name, method }
end


text:
package tiams.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import tiams.service.RepairServiceI;

/**
 * 在系统启动时,修复数据库
 *
 * @author 孙宇
 *
 */
public class RepairListener implements ServletContextListener, ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener, HttpSessionBindingListener, ServletRequestListener, ServletRequestAttributeListener {
	private static final Logger logger = Logger.getLogger(RepairListener.class);

	private static ApplicationContext ctx = null;

	public RepairListener() {
	}

	public void requestDestroyed(ServletRequestEvent arg0) {
	}

	public void attributeAdded(HttpSessionBindingEvent evt) {
	}

	public void contextInitialized(ServletContextEvent evt) {
		logger.info("修复数据库");
		ctx = WebApplicationContextUtils.getWebApplicationContext(evt.getServletContext());
		RepairServiceI repairService = (RepairServiceI) ctx.getBean("repairService");
		repairService.repair();
	}

	public void sessionDidActivate(HttpSessionEvent arg0) {
	}

	public void valueBound(HttpSessionBindingEvent arg0) {
	}

	public void attributeAdded(ServletContextAttributeEvent arg0) {
	}

	public void attributeRemoved(ServletContextAttributeEvent arg0) {
	}

	public void sessionDestroyed(HttpSessionEvent evt) {
	}

	public void attributeRemoved(HttpSessionBindingEvent arg0) {
	}

	public void attributeAdded(ServletRequestAttributeEvent evt) {
	}

	public void valueUnbound(HttpSessionBindingEvent arg0) {
	}

	public void sessionWillPassivate(HttpSessionEvent arg0) {
	}

	public void sessionCreated(HttpSessionEvent arg0) {
	}

	public void attributeReplaced(HttpSessionBindingEvent arg0) {
	}

	public void attributeReplaced(ServletContextAttributeEvent arg0) {
	}

	public void attributeRemoved(ServletRequestAttributeEvent arg0) {
	}

	public void contextDestroyed(ServletContextEvent evt) {
	}

	public void attributeReplaced(ServletRequestAttributeEvent arg0) {
	}

	public void requestInitialized(ServletRequestEvent arg0) {
	}

}


text:
namespace SE.DSP.Foundation.Infrastructure.Constant
{
    public static class BLConfiguratgionKey
    {
        public const string PASSWORDMAILFROM = "PasswordMailFrom";
        public const string PASSWORDMAILUSERNAME = "PasswordMailUserName";
        public const string PASSWORDMAILPASSWORD = "PasswordMailPassword";

        public const long PLATFORMSPID = -1;
        public const int PLATFORMUSERTYPE = -1;

        public const string CONTACTUSMAILFROM = "ContactUsMailFrom";
        public const string CONTACTUSMAILTO = "ContactUsMailTo";
        public const string CONTACTUSMAILUSERNAME = "ContactUsMailUserName";
        public const string CONTACTUSMAILPASSWORD = "ContactUsMailPassword";

    }
}


text:
// ------------------------------------------------------------------------------
//  Copyright (c) 2016 Goodgame Studios. All Rights Reserved.
//
//  NOTICE: You are permitted to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
// ------------------------------------------------------------------------------

import { IMediatorUnmapper } from "../dsl/IMediatorUnmapper";

/**
 * @private
 */
export class NullMediatorUnmapper implements IMediatorUnmapper {

    /*============================================================================*/
    /* Public Functions                                                           */
    /*============================================================================*/

    /**
     * @private
     */
    public fromMediator(mediatorClass: FunctionConstructor): void {
    }

    /**
     * @private
     */
    public fromAll(): void {
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Text;
using System.Security.Cryptography;

namespace TestME
{
    public static class Utilities
    {
        public static void txtBoxReplaceNewLine(TextBox txtb)
        {
            int cpos = txtb.SelectionStart;
            txtb.Text = txtb.Text.Replace(Environment.NewLine, "");
            txtb.SelectionStart = cpos;
        }

        public static void txtBoxReplaceSpaceNewLine(TextBox txtb)
        {
            int cpos = txtb.SelectionStart;
            txtb.Text = txtb.Text.Replace(Environment.NewLine, "");
            txtb.Text = txtb.Text.Replace(" ", "");
            txtb.SelectionStart = cpos;
        }

        public static void txtCustomReplaceSpace(XylosTextBox txtb)
        {
            int cpos = txtb.SelectionStart;
            txtb.Text = txtb.Text.Replace(Environment.NewLine, "");
            txtb.Text = txtb.Text.Replace(" ", "");
            txtb.SelectionStart = cpos;
        }

        public static void Cell_TextChanged(object sender, DataGridView dgv, Control e)
        {
            if (e != null)
            {
                Utilities.txtBoxReplaceNewLine((TextBox)e);
                dgv.CurrentCell.Value = e.Text;
            }
        }
        public static void dgvCellEditing(DataGridView dgv,string columnName, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dgv.CurrentCell != null && dgv.CurrentCell.ColumnIndex == dgv.Columns[columnName].Index)
            {
                Control cntObject = new Control();
                e.Control.TextChanged += new EventHandler((object sse, EventArgs se) => Utilities.Cell_TextChanged(sse, dgv, cntObject));
                cntObject = e.Control;
                cntObject.TextChanged += (object sse, EventArgs se) => Utilities.Cell_TextChanged(sse, dgv, cntObject);
            }
            dgv.RefreshEdit();
        }

        public static Question dgvRowIntoQuestion(DataGridViewRow dgvRow)
        {
            Question TempQuest = new Question();
            TempQuest.id = int.Parse(dgvRow.Cells[1].Value.ToString());
            TempQuest.question = dgvRow.Cells[2].Value.ToString();
            TempQuest.anwsers = JsonConvert.DeserializeObject<List<Answer>>(dgvRow.Cells[3].Value.ToString());
            TempQuest.dlevel = int.Parse(dgvRow.Cells[4].Value.ToString());
            TempQuest.prive = Boolean.Parse(dgvRow.Cells[5].Value.ToString());

            return TempQuest;
        }

        public static void dgvRowMoveUpDown(DataGridView dgv,bool moveDown)
        {
            if (dgv.SelectedRows.Count > 0)
            {
                int rowCount = dgv.Rows.Count;
                int index = dgv.SelectedCells[0].OwningRow.Index;

                if (moveDown)
                {
                    if (index == (rowCount - 1))
                    {
                        return;
                    }
                }
                else
                {
                    if (index == 0)
                    {
                        return;
                    }
                }

                DataGridViewRowCollection rows = dgv.Rows;
                DataGridViewRow tempRow;

                if (moveDown)
                {
                    tempRow = rows[index + 1];
                }
                else
                {
                    tempRow = rows[index - 1];
                }

                rows.Remove(tempRow);
                tempRow.Frozen = false;
                rows.Insert(index, tempRow);
                dgv.ClearSelection();
                if (moveDown)
                {
                    dgv.Rows[index + 1].Selected = true;
                }
                else
                {
                    dgv.Rows[index - 1].Selected = true;
                }

            }
        }

        public static void dgvRandomShuffle(DataGridView dgv)
        {
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                dgv.Rows[i].Selected = true;

                Random rnd = new Random();
                int timesToShuffle = rnd.Next(1, dgv.Rows.Count);
                for (int k = 0; k < timesToShuffle; k++)
                {
                    int upOrDown = rnd.Next(1, 10);
                    if (upOrDown <= 5)
                    {
                        dgvRowMoveUpDown(dgv, true);
                    }
                    else
                    {
                        dgvRowMoveUpDown(dgv, false);
                    }
                }
            }
        }

        public static void contextMenuEnable(DataGridView dgv,params ToolStripMenuItem[] controls)
        {
            bool qExists;
            if (dgv.Rows.Count < 1)
            {
                qExists = false;
            }
            else
            {
                qExists = true;
            }
            foreach (ToolStripMenuItem ctrl in controls)
            {
                ctrl.Enabled = qExists;
            }
        }

        public static void rightClickSelect(DataGridView dgv, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.ColumnIndex >=0 && e.RowIndex >=0)
            {
                dgv.CurrentCell = dgv[e.ColumnIndex, e.RowIndex];
            }
        }

        public static void notifyThem(NotificationBox ntfbox,string msg,NotificationBox.Type ntype)
        {
            InvokeMe(ntfbox, () =>
            {
                ntfbox.Text = msg;
                ntfbox.NotificationType = ntype;
                ntfbox.Visible = true;
                ntfbox.Show();
                switch (ntype)
                {
                    case NotificationBox.Type.Success:
                        ntfbox.Image = TestME.Properties.Resources.tick;
                        break;
                    case NotificationBox.Type.Error:
                        ntfbox.Image = TestME.Properties.Resources.error;
                        break;
                    case NotificationBox.Type.Warning:
                        ntfbox.Image = TestME.Properties.Resources.warning;
                        break;
                    case NotificationBox.Type.Notice:
                        ntfbox.Image = TestME.Properties.Resources.notice;
                        break;
                    case NotificationBox.Type.Other:
                        ntfbox.Image = TestME.Properties.Resources.star;
                        break;
                }
            });
        }

        public static Thread runInThread(Action func)
        {
            return new Thread(new ThreadStart(func));
        }

        public static DB AsyncDB(bool DebugMe = false)
        {
            DB tempDB = new DB(Globals.ConnectionStr());
            tempDB.Debug = DebugMe;
            return tempDB;
        }

        public static void InvokeMe(Control ctrl, MethodInvoker mInvoke)
        {
            try
            {
                ctrl.Invoke((MethodInvoker) (mInvoke));
            }
            catch (Exception){}
        }

        public static Control FindControl(Form form, string name)
        {
            foreach (Control control in form.Controls)
            {
                Control result = FindControl(form, control, name);
                if (result != null)
                    return result;
            }

            return null;
        }

        private static Control FindControl(Form form, Control control, string name)
        {
            if (control.Name == name)
            {
                return control;
            }

            foreach (Control subControl in control.Controls)
            {
                Control result = FindControl(form, subControl, name);
                if (result != null)
                    return result;
            }

            return null;
        }

        public static void clearText(params Control[] controls)
        {
            for (int i= 0; i < controls.Length; i++) {
                InvokeMe(controls[i], () => {
                    switch (controls[i].GetType().ToString())
                    {
                        case "XylosTextBox":
                            controls[i].Text = "";
                            break;
                        case "System.Windows.Forms.TextBox":
                            controls[i].Text = "";
                            break;
                    }
                });
            }
        }

        public static string MD5Hash(string txt)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(txt));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }

    } //end of class Utilities
}


text:
import tinycolor from 'tinycolor2';

import { forEach, find, values, includes, uniq, keys } from 'constants/lodash';
import { getTopLevelEntity } from 'utils/entity';
import { distanceBetween } from 'utils/canvas-helpers';
import Entities from 'constants/entities';
import { getHexPoints } from 'utils/hex/common';
import { isValidColor } from 'utils/common';
import { TARGET_COLOR_WIDTH } from 'constants/defaults';

const NAVIGATION_WIDTHS = {
  thin: 1,
  normal: 2.5,
  wide: 5,
};

const COLORS = {
  DARK4: '#091833',
  DARK3: '#11203b',
  DARK2: '#182742',
  DARK1: '#3c4b66',
  LIGHT: '#dbdbdb',
  PRIMARY: '#863c4e',
  PRIMARY_ALT: '#792f41',
  TRANSPARENT: 'transparent',
};

const ARROW_SIZE = 10;
const drawArrowhead = (ctx, radians, x, y, ratio, isForward) => {
  const size = ARROW_SIZE * ratio;
  ctx.fillStyle = COLORS.LIGHT;
  ctx.lineWidth = 2;
  ctx.save();
  ctx.beginPath();
  ctx.translate(x, y);
  ctx.rotate(radians);
  ctx.moveTo(0, 6 * (isForward ? -1 : 1));
  ctx.lineTo(size / 2, size * (isForward ? 1 : -1) + 6 * (isForward ? -1 : 1));
  ctx.lineTo(-size / 2, size * (isForward ? 1 : -1) + 6 * (isForward ? -1 : 1));
  ctx.closePath();
  ctx.restore();
  ctx.fill();
};

export default ({
  ctx,
  ratio,
  hexes,
  topLevelEntities,
  hoverKey,
  holdKey,
  activeKey,
  width,
  height,
  isShared,
  sectorLayers,
  navigationRoutes,
  routeLocator,
  paintRegion,
  layerHexes,
  showNumberOfChildren,
  showEntityName,
  showCoordinates,
}) => {
  ctx.fillStyle = COLORS.DARK3;
  ctx.rect(0, 0, width * ratio, height * ratio);
  ctx.fill();

  const step = 2 * ratio;
  ctx.strokeStyle = COLORS.DARK3;
  ctx.lineWidth = 3 * ratio;

  const hexEntities = hexes
    .map(hex => ({
      ...hex,
      xOffset: hex.xOffset * ratio,
      yOffset: hex.yOffset * ratio,
      width: hex.width * ratio,
      height: hex.height * ratio,
      ...getTopLevelEntity(topLevelEntities, hex.hexKey),
    }))
    .map(hex => ({
      ...hex,
      points: getHexPoints(hex),
    }));

  const allRouteKeys = values(navigationRoutes).reduce(
    (routeKeys, sectorNav) => uniq([...routeKeys, ...sectorNav.route]),
    [],
  );
  const routeLocations = {};
  const hexesWithDarkText = [];
  const newRoute = find(navigationRoutes, { isCreatingRoute: true });
  let holdLocation;
  let hoverLocation;
  let isVectorSwitch = false;

  hexEntities.forEach(
    ({ points, highlighted, hexKey, xOffset, yOffset, entity }) => {
      ctx.beginPath();
      const [first, ...rest] = points;
      ctx.moveTo(first.x, first.y);
      rest.forEach(({ x, y }) => {
        ctx.lineTo(x, y);
      });
      ctx.closePath();
      ctx.fillStyle = COLORS.DARK4;
      if (highlighted) {
        ctx.fillStyle = COLORS.DARK2;
      }
      if (hoverKey === hexKey) {
        ctx.fillStyle = COLORS.PRIMARY;
      }
      if (activeKey === hexKey) {
        ctx.fillStyle = COLORS.PRIMARY_ALT;
        ctx.strokeStyle = COLORS.LIGHT;
      } else {
        ctx.strokeStyle = COLORS.TRANSPARENT;
      }
      if (holdKey === hexKey || (hoverKey === hexKey && holdKey)) {
        ctx.fillStyle = COLORS.DARK1;
      }
      if (
        includes(keys(layerHexes), hexKey) ||
        (hoverKey === hexKey && paintRegion)
      ) {
        let hexLayer = layerHexes[hexKey] || [];
        if (
          hoverKey === hexKey &&
          paintRegion &&
          !includes(hexLayer, paintRegion.color)
        ) {
          hexLayer = [paintRegion.color, ...hexLayer];
        }

        const lightColors = hexLayer.reduce(
          (num, color) => num + tinycolor(color).getBrightness(),
          0,
        );
        if (lightColors / hexLayer.length >= 100) {
          hexesWithDarkText.push(hexKey);
        }

        if (hexLayer.length === 1) {
          const [fillStyle] = hexLayer;
          if (isValidColor(fillStyle)) {
            ctx.fillStyle = fillStyle;
          } else {
            console.warn(
              `WARNING: Invalid color "${fillStyle}". Replacing with black.`,
            );
            ctx.fillStyle = 'black';
          }
        } else if (hexLayer.length > 1) {
          const gradient = ctx.createLinearGradient(
            points[1].x,
            points[1].y,
            points[4].x,
            points[4].y,
          );
          let numSteps = Math.round(
            distanceBetween(points[1], points[4]) /
              (TARGET_COLOR_WIDTH * ratio),
          );
          numSteps = numSteps < hexLayer.length ? hexLayer.length : numSteps;
          const gStep = 1 / numSteps;
          for (let i = 0; i < numSteps; i += 1) {
            let color = hexLayer[i % hexLayer.length];
            if (!isValidColor(color)) {
              console.warn(
                `WARNING: Invalid color "${color}". Replacing with black.`,
              );
              color = 'black';
            }
            gradient.addColorStop(gStep * i, color);
            const nextColor = hexLayer[(i + 1) % hexLayer.length];
            if (nextColor) {
              gradient.addColorStop(
                Math.min(gStep * (i + 1) - 0.001, 1),
                color,
              );
            }
          }
          ctx.fillStyle = gradient;
        }
      }
      if (newRoute && includes(newRoute.route, hexKey)) {
        ctx.fillStyle = COLORS.DARK1;
      }
      ctx.stroke();
      ctx.fill();

      if (hexKey === holdKey) {
        holdLocation = { x: xOffset, y: yOffset };
      }
      if (hexKey === hoverKey) {
        hoverLocation = { x: xOffset, y: yOffset };
        isVectorSwitch = !!entity;
      }
      if (includes(allRouteKeys, hexKey) && highlighted) {
        routeLocations[hexKey] = { x: xOffset, y: yOffset };
      }
    },
  );

  const renderNavigation =
    sectorLayers.navigation === undefined || sectorLayers.navigation;
  if (renderNavigation || newRoute) {
    forEach(navigationRoutes, (navRoute, routeId) => {
      if (navRoute.route.length < 2 || (isShared && navRoute.isHidden)) {
        return;
      }
      const isLocating = routeId === routeLocator;
      let lineWidth = NAVIGATION_WIDTHS[navRoute.width] * ratio;
      if (isLocating) {
        lineWidth = NAVIGATION_WIDTHS.wide * ratio;
        ctx.strokeStyle = 'red';
      } else {
        ctx.strokeStyle = navRoute.color;
      }
      if (navRoute.type === 'solid' || isLocating) {
        ctx.setLineDash([1, 0]);
      } else if (navRoute.type === 'dotted') {
        ctx.setLineDash([lineWidth, 12]);
      } else if (navRoute.type === 'short') {
        ctx.setLineDash([15, 15]);
      } else {
        ctx.setLineDash([35, 35]);
      }
      ctx.lineWidth = lineWidth;
      ctx.beginPath();
      navRoute.route.forEach((routeLocation, index) => {
        const { x, y } = routeLocations[routeLocation] || {};
        if (index) {
          ctx.lineTo(x, y);
        } else {
          ctx.moveTo(x, y);
        }
      });
      ctx.stroke();
    });
  }

  if (holdLocation && hoverLocation && holdKey !== hoverKey) {
    const vectorRatio =
      (isVectorSwitch ? 16 : 10) / distanceBetween(holdLocation, hoverLocation);
    const xEnd =
      (1 - vectorRatio) * hoverLocation.x + vectorRatio * holdLocation.x;
    const yEnd =
      (1 - vectorRatio) * hoverLocation.y + vectorRatio * holdLocation.y;

    let xStart = holdLocation.x;
    let yStart = holdLocation.y;
    if (isVectorSwitch) {
      xStart =
        (1 - vectorRatio) * holdLocation.x + vectorRatio * hoverLocation.x;
      yStart =
        (1 - vectorRatio) * holdLocation.y + vectorRatio * hoverLocation.y;
    }

    // Draw Path
    ctx.lineWidth = 2 * ratio;
    ctx.strokeStyle = COLORS.LIGHT;
    ctx.setLineDash([1, 0]);
    ctx.beginPath();
    ctx.moveTo(xStart, yStart);
    ctx.lineTo(xEnd, yEnd);
    ctx.stroke();

    // Draw arrow heads
    let radians = Math.atan((yEnd - yStart) / (xEnd - xStart));
    radians += ((xEnd >= xStart ? 90 : -90) * Math.PI) / 180;
    drawArrowhead(ctx, radians, xEnd, yEnd, ratio, true);
    if (isVectorSwitch) {
      drawArrowhead(ctx, radians, xStart, yStart, ratio, false);
    }
  }

  hexEntities
    .filter(hex => hex.highlighted)
    .forEach(hex => {
      // Draw Text
      ctx.font = `${9 * ratio}px Titillium Web,sans-serif`;
      ctx.textAlign = 'center';
      ctx.fillStyle = includes(hexesWithDarkText, hex.hexKey)
        ? '#000000'
        : '#b2b2b2';
      const renderText =
        hex.width > 45 * ratio &&
        (sectorLayers.systemText === undefined || sectorLayers.systemText);
      if (renderText && showCoordinates) {
        ctx.fillText(
          hex.hexKey,
          hex.xOffset,
          hex.yOffset + hex.height / 2 - step * 2,
        );
      }
      if (hex.entity) {
        if (renderText) {
          if (showEntityName) {
            ctx.fillText(
              hex.entity.name,
              hex.xOffset,
              hex.yOffset + hex.height / 2 - step * 7,
            );
          }
          if (showNumberOfChildren) {
            ctx.fillText(
              hex.entity.numChildren,
              hex.xOffset,
              hex.yOffset - hex.height / 2 + step * 4,
            );
          }
        }
        ctx.fillStyle =
          hex.entityType === Entities.blackHole.key ? '#000000' : '#dbdbdb';
        ctx.beginPath();
        ctx.arc(hex.xOffset, hex.yOffset, hex.width / 13, 0, 2 * Math.PI);
        ctx.fill();
      }
    });
};


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        <link rel="stylesheet" href="lib/reset.css">

        <button onclick="setOption()">setOption()</button>


text:
/*
 * Xero Accounting API
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * Contact: api@xero.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.xero.models.accounting;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/** BankTransfers */
public class BankTransfers {
  StringUtil util = new StringUtil();

  @JsonProperty("BankTransfers")
  private List<BankTransfer> bankTransfers = new ArrayList<BankTransfer>();
  /**
   * bankTransfers
   *
   * @param bankTransfers List<BankTransfer>
   * @return BankTransfers
   */
  public BankTransfers bankTransfers(List<BankTransfer> bankTransfers) {
    this.bankTransfers = bankTransfers;
    return this;
  }

  /**
   * bankTransfers
   *
   * @param bankTransfersItem BankTransfer
   * @return BankTransfers
   */
  public BankTransfers addBankTransfersItem(BankTransfer bankTransfersItem) {
    if (this.bankTransfers == null) {
      this.bankTransfers = new ArrayList<BankTransfer>();
    }
    this.bankTransfers.add(bankTransfersItem);
    return this;
  }

  /**
   * Get bankTransfers
   *
   * @return bankTransfers
   */
  @ApiModelProperty(value = "")
  /**
   * bankTransfers
   *
   * @return bankTransfers List<BankTransfer>
   */
  public List<BankTransfer> getBankTransfers() {
    return bankTransfers;
  }

  /**
   * bankTransfers
   *
   * @param bankTransfers List<BankTransfer>
   */
  public void setBankTransfers(List<BankTransfer> bankTransfers) {
    this.bankTransfers = bankTransfers;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    BankTransfers bankTransfers = (BankTransfers) o;
    return Objects.equals(this.bankTransfers, bankTransfers.bankTransfers);
  }

  @Override
  public int hashCode() {
    return Objects.hash(bankTransfers);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class BankTransfers {\n");
    sb.append("    bankTransfers: ").append(toIndentedString(bankTransfers)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php
/**
 * @package: cahpi
 *
 * @author:  msiebeneicher
 * @since:   2016-11-10
 *
 */

namespace Chapi\Service\JobValidator;

use Chapi\Entity\Chronos\JobEntity;
use Chapi\Entity\JobEntityInterface;

interface PropertyValidatorInterface
{
    /**
     * @param string $property
     * @param JobEntityInterface $jobEntity
     * @return bool
     */
    public function isValid($property, JobEntityInterface $jobEntity);

    /**
     * @return string
     */
    public function getLastErrorMessage();
}


text:
package day5;

import java.util.List;

public class BaseAdapter {
	List<Book> books;

	public View getView(ListView listView, int index) {

		return null;
	}

}


text:
layout:     post
author:     Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title:      New APC data harvested from Bielefeld University
date:       2020-07-08 10:00:00
summary:
categories: [general, openAPC]
comments: true
---

New APC data has been harvested from the [institutional repository](https://pub.uni-bielefeld.de) of Bielefeld University, which had shifted to APC data provision via OAI-PMH.

[Bielefeld University Library](http://www.ub.uni-bielefeld.de/english/) is in charge of [Bielefeld University's Open Access Publishing Fund](http://oa.uni-bielefeld.de/en/publikationsfonds.html), which is supported by the DFG under its [Open-Access Publishing Programme](http://www.dfg.de/en/research_funding/programmes/infrastructure/lis/funding_opportunities/open_access/).

Contact person is [Dirk Pieper](<mailto:oa.ub@uni-bielefeld.de>).

## Cost data

The new data covers publication fees for 3 articles. Total expenditure amounts to 4 231€ and the average fee is 1 410€.

|                | Articles| Fees paid in EURO| Mean Fee paid|
|:---------------|--------:|-----------------:|-------------:|
|Wiley-Blackwell |        3|              4231|          1410|

## Overview

With the recent set of harvest data included, the overall APC data for Bielefeld now looks as follows:

### Fees paid per publisher (in EURO)

![plot of chunk tree_bielefeld_2020_07_08_full](/figure/tree_bielefeld_2020_07_08_full-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_bielefeld_2020_07_08_year_full](/figure/box_bielefeld_2020_07_08_year_full-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_bielefeld_2020_07_08_publisher_full](/figure/box_bielefeld_2020_07_08_publisher_full-1.png)


text:
from __future__ import division, absolute_import, print_function

import sys
import subprocess

import numpy as np
import pytest
try:
    import ctypes
except ImportError:
    ctypes = None

def check_dir(module, module_name=None):
    """Returns a mapping of all objects with the wrong __module__ attribute."""
    if module_name is None:
        module_name = module.__name__
    results = {}
    for name in dir(module):
        item = getattr(module, name)
        if (hasattr(item, '__module__') and hasattr(item, '__name__')
                and item.__module__ != module_name):
            results[name] = item.__module__ + '.' + item.__name__
    return results

@pytest.mark.skipif(
    sys.version_info[0] < 3,
    reason="NumPy exposes slightly different functions on Python 2")
def test_numpy_namespace():
    # None of these objects are publicly documented.
    undocumented = {
        'Tester': 'numpy.testing._private.nosetester.NoseTester',
        '_add_newdoc_ufunc': 'numpy.core._multiarray_umath._add_newdoc_ufunc',
        'add_docstring': 'numpy.core._multiarray_umath.add_docstring',
        'add_newdoc': 'numpy.core.function_base.add_newdoc',
        'add_newdoc_ufunc': 'numpy.core._multiarray_umath._add_newdoc_ufunc',
        'byte_bounds': 'numpy.lib.utils.byte_bounds',
        'compare_chararrays': 'numpy.core._multiarray_umath.compare_chararrays',
        'deprecate': 'numpy.lib.utils.deprecate',
        'deprecate_with_doc': 'numpy.lib.utils.<lambda>',
        'disp': 'numpy.lib.function_base.disp',
        'fastCopyAndTranspose': 'numpy.core._multiarray_umath._fastCopyAndTranspose',
        'get_array_wrap': 'numpy.lib.shape_base.get_array_wrap',
        'get_include': 'numpy.lib.utils.get_include',
        'int_asbuffer': 'numpy.core._multiarray_umath.int_asbuffer',
        'mafromtxt': 'numpy.lib.npyio.mafromtxt',
        'ndfromtxt': 'numpy.lib.npyio.ndfromtxt',
        'recfromcsv': 'numpy.lib.npyio.recfromcsv',
        'recfromtxt': 'numpy.lib.npyio.recfromtxt',
        'safe_eval': 'numpy.lib.utils.safe_eval',
        'set_string_function': 'numpy.core.arrayprint.set_string_function',
        'show_config': 'numpy.__config__.show',
        'who': 'numpy.lib.utils.who',
    }
    # These built-in types are re-exported by numpy.
    builtins = {
        'bool': 'builtins.bool',
        'complex': 'builtins.complex',
        'float': 'builtins.float',
        'int': 'builtins.int',
        'long': 'builtins.int',
        'object': 'builtins.object',
        'str': 'builtins.str',
        'unicode': 'builtins.str',
    }
    whitelist = dict(undocumented, **builtins)
    bad_results = check_dir(np)
    # pytest gives better error messages with the builtin assert than with
    # assert_equal
    assert bad_results == whitelist

@pytest.mark.parametrize('name', ['testing', 'Tester'])
def test_import_lazy_import(name):
    """Make sure we can actually the the modules we lazy load.

    While not exported as part of the public API, it was accessible.  With the
    use of __getattr__ and __dir__, this isn't always true It can happen that
    an infinite recursion may happen.

    This is the only way I found that would force the failure to appear on the
    badly implemented code.

    We also test for the presence of the lazily imported modules in dir

    """
    exe = (sys.executable, '-c', "import numpy; numpy." + name)
    result = subprocess.check_output(exe)
    assert not result

    # Make sure they are still in the __dir__
    assert name in dir(np)

def test_numpy_linalg():
    bad_results = check_dir(np.linalg)
    assert bad_results == {}

def test_numpy_fft():
    bad_results = check_dir(np.fft)
    assert bad_results == {}

@pytest.mark.skipif(ctypes is None,
                    reason="ctypes not available in this python")
def test_NPY_NO_EXPORT():
    cdll = ctypes.CDLL(np.core._multiarray_tests.__file__)
    # Make sure an arbitrary NPY_NO_EXPORT function is actually hidden
    f = getattr(cdll, 'test_not_exported', None)
    assert f is None, ("'test_not_exported' is mistakenly exported, "
                      "NPY_NO_EXPORT does not work")


text:
console.log(person1.firstName); //'Arkadiusz';
console.log(person1.lastName); //Ar;
person1.print();    //firstName Arkadiusz lastName Ar

//2)Dodaj odpowiedni kod aby ponizszy kod dzialal

person2_1 = new Person2("Ala","Kowalska");
person2_2 = new Person2('Arkadiusz', 'Nowak');
person2_3 = new Person2("Anna","Nowak");

person2_1.print();  //First name: Ala, Second name: Kowalska
person2_2.print();  //First name: Arkadiusz, Second name: Nowak
person2_3.print();  //First name: Anna, Second name: Nowak

//3) Dziedziczenie:
// Stworz hierachie obiektow Shape<--Rectangle,
// Shape<--Triangle
//Shape powinien zawierac pole name,
//Triangle: name, a,b,c,
// Rectangle: a,b


text:
namespace MAD
{
	class CPhysicsComponent;

	// The PhysicsWorld is responsible for performing collision detection and collision resolution (where the PhysicsComponent is responsible for simulating the rigid bodies)
	class UPhysicsWorld : public UObject
	{
		MAD_DECLARE_CLASS(UPhysicsWorld, UObject)
	public:
		using PhysicsBody_t = CPhysicsComponent;
		using PhysicsBodyWeakPtr_t = eastl::weak_ptr<PhysicsBody_t>;
		using PhysicsComponentContainer_t = eastl::vector<PhysicsBodyWeakPtr_t>;
	public:
		explicit UPhysicsWorld(OGameWorld* inOwningWorld);

		void SimulatePhysics();
	private:
		PhysicsComponentContainer_t m_physicsComponents;
	};
}


text:
masking tpl

<ui-view>

 default masking sidebar

to mask drawing

</ui-view>


text:
#ifndef SFML_WINDOWSTYLE_HPP
#define SFML_WINDOWSTYLE_HPP

namespace sf
{
namespace Style
{
    ////////////////////////////////////////////////////////////
    /// \ingroup window
    /// \brief Enumeration of the window styles
    ///
    ////////////////////////////////////////////////////////////
    enum
    {
        None       = 0,      ///< No border / title bar (this flag and all others are mutually exclusive)
        Titlebar   = 1 << 0, ///< Title bar + fixed border
        Resize     = 1 << 1, ///< Titlebar + resizable border + maximize button
        Close      = 1 << 2, ///< Titlebar + close button
        Fullscreen = 1 << 3, ///< Fullscreen mode (this flag and all others are mutually exclusive)

        Default = Titlebar | Resize | Close ///< Default window style
    };
}

} // namespace sf

#endif // SFML_WINDOWSTYLE_HPP


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>package.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  </head>

  <body>
  	工具类
  </body>
</html>


text:
package vtk.web.referencedata.provider;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import vtk.util.Version;
import vtk.web.referencedata.ReferenceDataProvider;

/**
 * Reference data provider for information about the current version of
 * the framework.  The information is made available in the model as
 * a submodel of the name version.
 *
 * Model data provided:
 *

 *
version - the current version
 *
buildDate - the build date of the framework
 *
buildHost - the host of the build
 *
buildVendor -
 *
frameworkTitle -
 *

 */
public class FrameworkVersionProvider implements ReferenceDataProvider {

    @Override
    public void referenceData(Map<String, Object> model, HttpServletRequest request) {
        Map<String, Object> versionModel = new HashMap<>();
        versionModel.put("version", Version.getVersion());
        versionModel.put("buildDate", Version.getBuildDate());
        versionModel.put("buildHost", Version.getBuildHost());
        versionModel.put("buildVendor", Version.getBuildVendor());
        versionModel.put("frameworkTitle", Version.getFrameworkTitle());
        model.put("version", versionModel);
    }
}


text:
using FluentAssertions;
using VkNet.Tests.Infrastructure;
using Xunit;

namespace VkNet.Tests.Categories.Ads;

public class GetRejectionReasonTest : CategoryBaseTest
{
	protected override string Folder => "Ads";

	[Fact]
	public void GetRejectionReason()
	{
		Url = "https://api.vk.com/method/ads.getRejectionReason";

		ReadCategoryJsonPath(nameof(Api.Ads.GetRejectionReason));

		var result = Api.Ads.GetRejectionReason(123, 123);

		result.Comment.Should()
			.Be("123");
	}
}