text:
<?php

declare(strict_types=1);

namespace GuzzleHttp\Psr7;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;

final class Utils
{
    /**
     * Remove the items given by the keys, case insensitively from the data.
     *
     * @param string[] $keys
     */
    public static function caselessRemove(array $keys, array $data): array
    {
        $result = [];

        foreach ($keys as &$key) {
            $key = strtolower($key);
        }

        foreach ($data as $k => $v) {
            if (!is_string($k) || !in_array(strtolower($k), $keys)) {
                $result[$k] = $v;
            }
        }

        return $result;
    }

    /**
     * Copy the contents of a stream into another stream until the given number
     * of bytes have been read.
     *
     * @param StreamInterface $source Stream to read from
     * @param StreamInterface $dest   Stream to write to
     * @param int             $maxLen Maximum number of bytes to read. Pass -1
     *                                to read the entire stream.
     *
     * @throws \RuntimeException on error.
     */
    public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void
    {
        $bufferSize = 8192;

        if ($maxLen === -1) {
            while (!$source->eof()) {
                if (!$dest->write($source->read($bufferSize))) {
                    break;
                }
            }
        } else {
            $remaining = $maxLen;
            while ($remaining > 0 && !$source->eof()) {
                $buf = $source->read(min($bufferSize, $remaining));
                $len = strlen($buf);
                if (!$len) {
                    break;
                }
                $remaining -= $len;
                $dest->write($buf);
            }
        }
    }

    /**
     * Copy the contents of a stream into a string until the given number of
     * bytes have been read.
     *
     * @param StreamInterface $stream Stream to read
     * @param int             $maxLen Maximum number of bytes to read. Pass -1
     *                                to read the entire stream.
     *
     * @throws \RuntimeException on error.
     */
    public static function copyToString(StreamInterface $stream, int $maxLen = -1): string
    {
        $buffer = '';

        if ($maxLen === -1) {
            while (!$stream->eof()) {
                $buf = $stream->read(1048576);
                if ($buf === '') {
                    break;
                }
                $buffer .= $buf;
            }
            return $buffer;
        }

        $len = 0;
        while (!$stream->eof() && $len < $maxLen) {
            $buf = $stream->read($maxLen - $len);
            if ($buf === '') {
                break;
            }
            $buffer .= $buf;
            $len = strlen($buffer);
        }

        return $buffer;
    }

    /**
     * Calculate a hash of a stream.
     *
     * This method reads the entire stream to calculate a rolling hash, based
     * on PHP's `hash_init` functions.
     *
     * @param StreamInterface $stream    Stream to calculate the hash for
     * @param string          $algo      Hash algorithm (e.g. md5, crc32, etc)
     * @param bool            $rawOutput Whether or not to use raw output
     *
     * @throws \RuntimeException on error.
     */
    public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string
    {
        $pos = $stream->tell();

        if ($pos > 0) {
            $stream->rewind();
        }

        $ctx = hash_init($algo);
        while (!$stream->eof()) {
            hash_update($ctx, $stream->read(1048576));
        }

        $out = hash_final($ctx, $rawOutput);
        $stream->seek($pos);

        return $out;
    }

    /**
     * Clone and modify a request with the given changes.
     *
     * This method is useful for reducing the number of clones needed to mutate
     * a message.
     *
     * The changes can be one of:
     * - method: (string) Changes the HTTP method.
     * - set_headers: (array) Sets the given headers.
     * - remove_headers: (array) Remove the given headers.
     * - body: (mixed) Sets the given body.
     * - uri: (UriInterface) Set the URI.
     * - query: (string) Set the query string value of the URI.
     * - version: (string) Set the protocol version.
     *
     * @param RequestInterface $request Request to clone and modify.
     * @param array            $changes Changes to apply.
     */
    public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface
    {
        if (!$changes) {
            return $request;
        }

        $headers = $request->getHeaders();

        if (!isset($changes['uri'])) {
            $uri = $request->getUri();
        } else {
            // Remove the host header if one is on the URI
            if ($host = $changes['uri']->getHost()) {
                $changes['set_headers']['Host'] = $host;

                if ($port = $changes['uri']->getPort()) {
                    $standardPorts = ['http' => 80, 'https' => 443];
                    $scheme = $changes['uri']->getScheme();
                    if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
                        $changes['set_headers']['Host'] .= ':' . $port;
                    }
                }
            }
            $uri = $changes['uri'];
        }

        if (!empty($changes['remove_headers'])) {
            $headers = self::caselessRemove($changes['remove_headers'], $headers);
        }

        if (!empty($changes['set_headers'])) {
            $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers);
            $headers = $changes['set_headers'] + $headers;
        }

        if (isset($changes['query'])) {
            $uri = $uri->withQuery($changes['query']);
        }

        if ($request instanceof ServerRequestInterface) {
            $new = (new ServerRequest(
                $changes['method'] ?? $request->getMethod(),
                $uri,
                $headers,
                $changes['body'] ?? $request->getBody(),
                $changes['version'] ?? $request->getProtocolVersion(),
                $request->getServerParams()
            ))
            ->withParsedBody($request->getParsedBody())
            ->withQueryParams($request->getQueryParams())
            ->withCookieParams($request->getCookieParams())
            ->withUploadedFiles($request->getUploadedFiles());

            foreach ($request->getAttributes() as $key => $value) {
                $new = $new->withAttribute($key, $value);
            }

            return $new;
        }

        return new Request(
            $changes['method'] ?? $request->getMethod(),
            $uri,
            $headers,
            $changes['body'] ?? $request->getBody(),
            $changes['version'] ?? $request->getProtocolVersion()
        );
    }

    /**
     * Read a line from the stream up to the maximum allowed buffer length.
     *
     * @param StreamInterface $stream    Stream to read from
     * @param int|null        $maxLength Maximum buffer length
     */
    public static function readLine(StreamInterface $stream, ?int $maxLength = null): string
    {
        $buffer = '';
        $size = 0;

        while (!$stream->eof()) {
            if ('' === ($byte = $stream->read(1))) {
                return $buffer;
            }
            $buffer .= $byte;
            // Break when a new line is found or the max length - 1 is reached
            if ($byte === "\n" || ++$size === $maxLength - 1) {
                break;
            }
        }

        return $buffer;
    }

    /**
     * Create a new stream based on the input type.
     *
     * Options is an associative array that can contain the following keys:
     * - metadata: Array of custom metadata.
     * - size: Size of the stream.
     *
     * This method accepts the following `$resource` types:
     * - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
     * - `string`: Creates a stream object that uses the given string as the contents.
     * - `resource`: Creates a stream object that wraps the given PHP stream resource.
     * - `Iterator`: If the provided value implements `Iterator`, then a read-only
     *   stream object will be created that wraps the given iterable. Each time the
     *   stream is read from, data from the iterator will fill a buffer and will be
     *   continuously called until the buffer is equal to the requested read size.
     *   Subsequent read calls will first read from the buffer and then call `next`
     *   on the underlying iterator until it is exhausted.
     * - `object` with `__toString()`: If the object has the `__toString()` method,
     *   the object will be cast to a string and then a stream will be returned that
     *   uses the string value.
     * - `NULL`: When `null` is passed, an empty stream object is returned.
     * - `callable` When a callable is passed, a read-only stream object will be
     *   created that invokes the given callable. The callable is invoked with the
     *   number of suggested bytes to read. The callable can return any number of
     *   bytes, but MUST return `false` when there is no more data to return. The
     *   stream object that wraps the callable will invoke the callable until the
     *   number of requested bytes are available. Any additional bytes will be
     *   buffered and used in subsequent reads.
     *
     * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
     * @param array{size?: int, metadata?: array}                                    $options  Additional options
     *
     * @throws \InvalidArgumentException if the $resource arg is not valid.
     */
    public static function streamFor($resource = '', array $options = []): StreamInterface
    {
        if (is_scalar($resource)) {
            $stream = self::tryFopen('php://temp', 'r+');
            if ($resource !== '') {
                fwrite($stream, (string) $resource);
                fseek($stream, 0);
            }
            return new Stream($stream, $options);
        }

        switch (gettype($resource)) {
            case 'resource':
                /*
                 * The 'php://input' is a special stream with quirks and inconsistencies.
                 * We avoid using that stream by reading it into php://temp
                 */

                /** @var resource $resource */
                if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') {
                    $stream = self::tryFopen('php://temp', 'w+');
                    stream_copy_to_stream($resource, $stream);
                    fseek($stream, 0);
                    $resource = $stream;
                }
                return new Stream($resource, $options);
            case 'object':
                /** @var object $resource */
                if ($resource instanceof StreamInterface) {
                    return $resource;
                } elseif ($resource instanceof \Iterator) {
                    return new PumpStream(function () use ($resource) {
                        if (!$resource->valid()) {
                            return false;
                        }
                        $result = $resource->current();
                        $resource->next();
                        return $result;
                    }, $options);
                } elseif (method_exists($resource, '__toString')) {
                    return self::streamFor((string) $resource, $options);
                }
                break;
            case 'NULL':
                return new Stream(self::tryFopen('php://temp', 'r+'), $options);
        }

        if (is_callable($resource)) {
            return new PumpStream($resource, $options);
        }

        throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
    }

    /**
     * Safely opens a PHP stream resource using a filename.
     *
     * When fopen fails, PHP normally raises a warning. This function adds an
     * error handler that checks for errors and throws an exception instead.
     *
     * @param string $filename File to open
     * @param string $mode     Mode used to open the file
     *
     * @return resource
     *
     * @throws \RuntimeException if the file cannot be opened
     */
    public static function tryFopen(string $filename, string $mode)
    {
        $ex = null;
        set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool {
            $ex = new \RuntimeException(sprintf(
                'Unable to open "%s" using mode "%s": %s',
                $filename,
                $mode,
                $errstr
            ));

            return true;
        });

        try {
            /** @var resource $handle */
            $handle = fopen($filename, $mode);
        } catch (\Throwable $e) {
            $ex = new \RuntimeException(sprintf(
                'Unable to open "%s" using mode "%s": %s',
                $filename,
                $mode,
                $e->getMessage()
            ), 0, $e);
        }

        restore_error_handler();

        if ($ex) {
            /** @var $ex \RuntimeException */
            throw $ex;
        }

        return $handle;
    }

    /**
     * Safely gets the contents of a given stream.
     *
     * When stream_get_contents fails, PHP normally raises a warning. This
     * function adds an error handler that checks for errors and throws an
     * exception instead.
     *
     * @param resource $stream
     *
     * @throws \RuntimeException if the stream cannot be read
     */
    public static function tryGetContents($stream): string
    {
        $ex = null;
        set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool {
            $ex = new \RuntimeException(sprintf(
                'Unable to read stream contents: %s',
                $errstr
            ));

            return true;
        });

        try {
            /** @var string|false $contents */
            $contents = stream_get_contents($stream);

            if ($contents === false) {
                $ex = new \RuntimeException('Unable to read stream contents');
            }
        } catch (\Throwable $e) {
            $ex = new \RuntimeException(sprintf(
                'Unable to read stream contents: %s',
                $e->getMessage()
            ), 0, $e);
        }

        restore_error_handler();

        if ($ex) {
            /** @var $ex \RuntimeException */
            throw $ex;
        }

        return $contents;
    }

    /**
     * Returns a UriInterface for the given value.
     *
     * This function accepts a string or UriInterface and returns a
     * UriInterface for the given value. If the value is already a
     * UriInterface, it is returned as-is.
     *
     * @param string|UriInterface $uri
     *
     * @throws \InvalidArgumentException
     */
    public static function uriFor($uri): UriInterface
    {
        if ($uri instanceof UriInterface) {
            return $uri;
        }

        if (is_string($uri)) {
            return new Uri($uri);
        }

        throw new \InvalidArgumentException('URI must be a string or UriInterface');
    }
}


text:
package com.github.aleksandermielczarek.observablecacheexample.component;

import com.github.aleksandermielczarek.napkin.module.NapkinActivityModule;
import com.github.aleksandermielczarek.napkin.scope.ActivityScope;
import com.github.aleksandermielczarek.observablecacheexample.ui.Observable1Activity;
import com.github.aleksandermielczarek.observablecacheexample.ui.Observable2Activity;

import dagger.Subcomponent;

/**
 * Created by Aleksander Mielczarek on 12.11.2016.
 */
@ActivityScope
@Subcomponent(modules = NapkinActivityModule.class)
public interface ActivityComponent {

    void inject(Observable1Activity observable1Activity);

    void inject(Observable2Activity observable2Activity);
}

redpajama_set_name: RedPajamaGithub


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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- Parent info -->
    <parent>
        <artifactId>codingame-training-easy</artifactId>
        <groupId>fr.ptavares.codingame.codingame-training</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!-- Artifact info -->
    <groupId>fr.ptavares.codingame.codingame-training.easy</groupId>
    <artifactId>codingame-defibrillators</artifactId>

</project>


text:
<ticket-note>
    <content>{{CONTENT}}</content>
    <time-added>{{TIME_ADDED}}</time-added>
    <changes>
        <status-id>{{STATUS_ID}}</status-id>
        <priority-id>{{PRIORITY_ID}}</priority-id>
        <category-id>{{CATEGORY_ID}}</category-id>
        <assignee-id>{{ASSIGNEE_ID}}</assignee-id>
        <milestone-id>{{MILESTONE_ID}}</milestone-id>
        <summary>{{SUMMARY}}</summary>
    </changes>
</ticket-note>


text:
package org.springboot.integration.handler;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/6/17.
 */

@Configuration
public class RedisConfig extends JCacheConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisTemplate<String,String> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)
        return cacheManager;

    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    //指定缓存key的生成器。 @CachePut(keyGenerator = "wiselyKeyGenerator")
    @Bean
    public KeyGenerator wiselyKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

}


text:
'use strict';

angular.module('${artifactId}').controller('AppCtrl', function (${symbol_dollar}scope) {
    // TODO: implement this
});


text:
<?php

namespace Laravie\Authen;

use Illuminate\Support\Str;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class AuthenUserProvider extends EloquentUserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array<string,string>  $credentials
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials): ?UserContract
    {
        $name = Authen::getIdentifierName();

        if (! isset($credentials[$name]) || empty($credentials[$name])) {
            return parent::retrieveByCredentials($credentials);
        }

        $identifier = $credentials[$name];
        unset($credentials[$name]);

        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.

        $query = $this->createModel()
            ->newQuery()
            ->findByIdentifiers($identifier);

        foreach ($credentials as $key => $value) {
            if (! Str::contains($key, 'password')) {
                $query->where($key, $value);
            }
        }

        return $query->first();
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array<string,string>  $credentials
     *
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials): bool
    {
        $plain = $credentials['password'];
        $hashed = $user->getAuthPassword();

        if (\strlen($hashed) === 0) {
            return false;
        }

        return password_verify($plain, $hashed) || $this->hasher->check($plain, $hashed);
    }
}


text:
package org.sagebionetworks.repo.model.dbo.persistence;

import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SUBJECT_ACCESS_REQUIREMENT_REQUIREMENT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_TYPE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_FILE_SUBJECT_ACCESS_REQUIREMENT;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_SUBJECT_ACCESS_REQUIREMENT;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.dbo.FieldColumn;
import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.migration.DBOSubjectAccessRequirementBackup;
import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation;
import org.sagebionetworks.repo.model.migration.MigrationType;

public class DBOSubjectAccessRequirement implements MigratableDatabaseObject<DBOSubjectAccessRequirement, DBOSubjectAccessRequirementBackup> {

	private Long subjectId;
	private String subjectType;
	private Long accessRequirementId;

	private static FieldColumn[] FIELDS = new FieldColumn[] {
		new FieldColumn("subjectId", COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_ID, true),
		new FieldColumn("subjectType", COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_TYPE, true),
		new FieldColumn("accessRequirementId", COL_SUBJECT_ACCESS_REQUIREMENT_REQUIREMENT_ID).withIsBackupId(true),
	};

	@Override
	public TableMapping<DBOSubjectAccessRequirement> getTableMapping() {

		return new TableMapping<DBOSubjectAccessRequirement>(){

			@Override
			public DBOSubjectAccessRequirement mapRow(ResultSet rs, int rowNum) throws SQLException {
				DBOSubjectAccessRequirement sar = new DBOSubjectAccessRequirement();
				sar.setSubjectId(rs.getLong(COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_ID));
				sar.setSubjectType(rs.getString(COL_SUBJECT_ACCESS_REQUIREMENT_SUBJECT_TYPE));
				sar.setAccessRequirementId(rs.getLong(COL_SUBJECT_ACCESS_REQUIREMENT_REQUIREMENT_ID));
				return sar;
			}

			@Override
			public String getTableName() {
				return TABLE_SUBJECT_ACCESS_REQUIREMENT;
			}

			@Override
			public String getDDLFileName() {
				return DDL_FILE_SUBJECT_ACCESS_REQUIREMENT;
			}

			@Override
			public FieldColumn[] getFieldColumns() {
				return FIELDS;
			}

			@Override
			public Class<? extends DBOSubjectAccessRequirement> getDBOClass() {
				return DBOSubjectAccessRequirement.class;
			}};
	}

	public Long getSubjectId() {
		return subjectId;
	}

	public void setSubjectId(Long subjectId) {
		this.subjectId = subjectId;
	}

	public String getSubjectType() {
		return subjectType;
	}

	public void setSubjectType(String subjectType) {
		this.subjectType = subjectType;
	}

	public Long getAccessRequirementId() {
		return accessRequirementId;
	}

	public void setAccessRequirementId(Long accessRequirementId) {
		this.accessRequirementId = accessRequirementId;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((accessRequirementId == null) ? 0 : accessRequirementId.hashCode());
		result = prime * result + ((subjectId == null) ? 0 : subjectId.hashCode());
		result = prime * result + ((subjectType == null) ? 0 : subjectType.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DBOSubjectAccessRequirement other = (DBOSubjectAccessRequirement) obj;
		if (accessRequirementId == null) {
			if (other.accessRequirementId != null)
				return false;
		} else if (!accessRequirementId.equals(other.accessRequirementId))
			return false;
		if (subjectId == null) {
			if (other.subjectId != null)
				return false;
		} else if (!subjectId.equals(other.subjectId))
			return false;
		if (subjectType == null) {
			if (other.subjectType != null)
				return false;
		} else if (!subjectType.equals(other.subjectType))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "DBOSubjectAccessRequirement [subjectId=" + subjectId + ", subjectType=" + subjectType
				+ ", accessRequirementId=" + accessRequirementId + "]";
	}

	@Override
	public MigrationType getMigratableTableType() {
		return MigrationType.NODE_ACCESS_REQUIRMENT;
	}

	@Override
	public MigratableTableTranslation<DBOSubjectAccessRequirement, DBOSubjectAccessRequirementBackup> getTranslator() {

		return new MigratableTableTranslation<DBOSubjectAccessRequirement, DBOSubjectAccessRequirementBackup>(){

			@Override
			public DBOSubjectAccessRequirement createDatabaseObjectFromBackup(
					DBOSubjectAccessRequirementBackup backup) {
				DBOSubjectAccessRequirement dbo = new DBOSubjectAccessRequirement();
				dbo.setAccessRequirementId(backup.getAccessRequirementId());
				if (null==backup.getSubjectType()) {
					dbo.setSubjectId(backup.getNodeId());
					dbo.setSubjectType(RestrictableObjectType.ENTITY.toString());
				} else {
					dbo.setSubjectId(backup.getSubjectId());
					dbo.setSubjectType(backup.getSubjectType());
				}
				return dbo;
			}

			@Override
			public DBOSubjectAccessRequirementBackup createBackupFromDatabaseObject(
					DBOSubjectAccessRequirement dbo) {
				DBOSubjectAccessRequirementBackup backup = new DBOSubjectAccessRequirementBackup();
				backup.setAccessRequirementId(dbo.getAccessRequirementId());
				backup.setSubjectId(dbo.getSubjectId());
				backup.setSubjectType(dbo.getSubjectType());
				return backup;
			}
		};
	}

	@Override
	public Class<? extends DBOSubjectAccessRequirementBackup> getBackupClass() {
		return DBOSubjectAccessRequirementBackup.class;
	}

	@Override
	public Class<? extends DBOSubjectAccessRequirement> getDatabaseObjectClass() {
		return DBOSubjectAccessRequirement.class;
	}

	@Override
	public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() {
		return null;
	}
}


text:
from __future__ import absolute_import, unicode_literals

from datetime import datetime

from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field, FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils import six
from django.utils.translation import ugettext_lazy

from .models import Article

class ModelTest(TestCase):

    def test_lookup(self):
        # No articles are in the system yet.
        self.assertQuerysetEqual(Article.objects.all(), [])

        # Create an Article.
        a = Article(
            id=None,
            headline='Area man programs in Python',
            pub_date=datetime(2005, 7, 28),
        )

        # Save it into the database. You have to call save() explicitly.
        a.save()

        # Now it has an ID.
        self.assertTrue(a.id != None)

        # Models have a pk property that is an alias for the primary key
        # attribute (by default, the 'id' attribute).
        self.assertEqual(a.pk, a.id)

        # Access database columns via Python attributes.
        self.assertEqual(a.headline, 'Area man programs in Python')
        self.assertEqual(a.pub_date, datetime(2005, 7, 28, 0, 0))

        # Change values by changing the attributes, then calling save().
        a.headline = 'Area woman programs in Python'
        a.save()

        # Article.objects.all() returns all the articles in the database.
        self.assertQuerysetEqual(Article.objects.all(),
            ['<Article: Area woman programs in Python>'])

        # Django provides a rich database lookup API.
        self.assertEqual(Article.objects.get(id__exact=a.id), a)
        self.assertEqual(Article.objects.get(headline__startswith='Area woman'), a)
        self.assertEqual(Article.objects.get(pub_date__year=2005), a)
        self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), a)
        self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), a)
        self.assertEqual(Article.objects.get(pub_date__week_day=5), a)

        # The "__exact" lookup type can be omitted, as a shortcut.
        self.assertEqual(Article.objects.get(id=a.id), a)
        self.assertEqual(Article.objects.get(headline='Area woman programs in Python'), a)

        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2005),
            ['<Article: Area woman programs in Python>'],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2004),
            [],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__year=2005, pub_date__month=7),
            ['<Article: Area woman programs in Python>'],
        )

        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__week_day=5),
            ['<Article: Area woman programs in Python>'],
        )
        self.assertQuerysetEqual(
            Article.objects.filter(pub_date__week_day=6),
            [],
        )

        # Django raises an Article.DoesNotExist exception for get() if the
        # parameters don't match any object.
        six.assertRaisesRegex(self,
            ObjectDoesNotExist,
            "Article matching query does not exist. Lookup parameters were "
            "{'id__exact': 2000}",
            Article.objects.get,
            id__exact=2000,
        )
        # To avoid dict-ordering related errors check only one lookup
        # in single assert.
        six.assertRaisesRegex(self,
            ObjectDoesNotExist,
            ".*'pub_date__year': 2005.*",
            Article.objects.get,
            pub_date__year=2005,
            pub_date__month=8,
        )
        six.assertRaisesRegex(self,
            ObjectDoesNotExist,
            ".*'pub_date__month': 8.*",
            Article.objects.get,
            pub_date__year=2005,
            pub_date__month=8,
        )

        six.assertRaisesRegex(self,
            ObjectDoesNotExist,
            "Article matching query does not exist. Lookup parameters were "
            "{'pub_date__week_day': 6}",
            Article.objects.get,
            pub_date__week_day=6,
        )

        # Lookup by a primary key is the most common case, so Django
        # provides a shortcut for primary-key exact lookups.
        # The following is identical to articles.get(id=a.id).
        self.assertEqual(Article.objects.get(pk=a.id), a)

        # pk can be used as a shortcut for the primary key name in any query.
        self.assertQuerysetEqual(Article.objects.filter(pk__in=[a.id]),
            ["<Article: Area woman programs in Python>"])

        # Model instances of the same type and same ID are considered equal.
        a = Article.objects.get(pk=a.id)
        b = Article.objects.get(pk=a.id)
        self.assertEqual(a, b)

    def test_object_creation(self):
        # Create an Article.
        a = Article(
            id=None,
            headline='Area man programs in Python',
            pub_date=datetime(2005, 7, 28),
        )

        # Save it into the database. You have to call save() explicitly.
        a.save()

        # You can initialize a model instance using positional arguments,
        # which should match the field order as defined in the model.
        a2 = Article(None, 'Second article', datetime(2005, 7, 29))
        a2.save()

        self.assertNotEqual(a2.id, a.id)
        self.assertEqual(a2.headline, 'Second article')
        self.assertEqual(a2.pub_date, datetime(2005, 7, 29, 0, 0))

        # ...or, you can use keyword arguments.
        a3 = Article(
            id=None,
            headline='Third article',
            pub_date=datetime(2005, 7, 30),
        )
        a3.save()

        self.assertNotEqual(a3.id, a.id)
        self.assertNotEqual(a3.id, a2.id)
        self.assertEqual(a3.headline, 'Third article')
        self.assertEqual(a3.pub_date, datetime(2005, 7, 30, 0, 0))

        # You can also mix and match position and keyword arguments, but
        # be sure not to duplicate field information.
        a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
        a4.save()
        self.assertEqual(a4.headline, 'Fourth article')

        # Don't use invalid keyword arguments.
        six.assertRaisesRegex(self,
            TypeError,
            "'foo' is an invalid keyword argument for this function",
            Article,
            id=None,
            headline='Invalid',
            pub_date=datetime(2005, 7, 31),
            foo='bar',
        )

        # You can leave off the value for an AutoField when creating an
        # object, because it'll get filled in automatically when you save().
        a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31))
        a5.save()
        self.assertEqual(a5.headline, 'Article 6')

        # If you leave off a field with "default" set, Django will use
        # the default.
        a6 = Article(pub_date=datetime(2005, 7, 31))
        a6.save()
        self.assertEqual(a6.headline, 'Default headline')

        # For DateTimeFields, Django saves as much precision (in seconds)
        # as you give it.
        a7 = Article(
            headline='Article 7',
            pub_date=datetime(2005, 7, 31, 12, 30),
        )
        a7.save()
        self.assertEqual(Article.objects.get(id__exact=a7.id).pub_date,
            datetime(2005, 7, 31, 12, 30))

        a8 = Article(
            headline='Article 8',
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a8.save()
        self.assertEqual(Article.objects.get(id__exact=a8.id).pub_date,
            datetime(2005, 7, 31, 12, 30, 45))

        # Saving an object again doesn't create a new object -- it just saves
        # the old one.
        current_id = a8.id
        a8.save()
        self.assertEqual(a8.id, current_id)
        a8.headline = 'Updated article 8'
        a8.save()
        self.assertEqual(a8.id, current_id)

        # Check that != and == operators behave as expecte on instances
        self.assertTrue(a7 != a8)
        self.assertFalse(a7 == a8)
        self.assertEqual(a8, Article.objects.get(id__exact=a8.id))

        self.assertTrue(Article.objects.get(id__exact=a8.id) != Article.objects.get(id__exact=a7.id))
        self.assertFalse(Article.objects.get(id__exact=a8.id) == Article.objects.get(id__exact=a7.id))

        # You can use 'in' to test for membership...
        self.assertTrue(a8 in Article.objects.all())

        # ... but there will often be more efficient ways if that is all you need:
        self.assertTrue(Article.objects.filter(id=a8.id).exists())

        # dates() returns a list of available dates of the given scope for
        # the given field.
        self.assertQuerysetEqual(
            Article.objects.dates('pub_date', 'year'),
            ["datetime.datetime(2005, 1, 1, 0, 0)"])
        self.assertQuerysetEqual(
            Article.objects.dates('pub_date', 'month'),
            ["datetime.datetime(2005, 7, 1, 0, 0)"])
        self.assertQuerysetEqual(
            Article.objects.dates('pub_date', 'day'),
            ["datetime.datetime(2005, 7, 28, 0, 0)",
             "datetime.datetime(2005, 7, 29, 0, 0)",
             "datetime.datetime(2005, 7, 30, 0, 0)",
             "datetime.datetime(2005, 7, 31, 0, 0)"])
        self.assertQuerysetEqual(
            Article.objects.dates('pub_date', 'day', order='ASC'),
            ["datetime.datetime(2005, 7, 28, 0, 0)",
             "datetime.datetime(2005, 7, 29, 0, 0)",
             "datetime.datetime(2005, 7, 30, 0, 0)",
             "datetime.datetime(2005, 7, 31, 0, 0)"])
        self.assertQuerysetEqual(
            Article.objects.dates('pub_date', 'day', order='DESC'),
            ["datetime.datetime(2005, 7, 31, 0, 0)",
             "datetime.datetime(2005, 7, 30, 0, 0)",
             "datetime.datetime(2005, 7, 29, 0, 0)",
             "datetime.datetime(2005, 7, 28, 0, 0)"])

        # dates() requires valid arguments.
        six.assertRaisesRegex(self,
            TypeError,
            "dates\(\) takes at least 3 arguments \(1 given\)",
            Article.objects.dates,
        )

        six.assertRaisesRegex(self,
            FieldDoesNotExist,
            "Article has no field named 'invalid_field'",
            Article.objects.dates,
            "invalid_field",
            "year",
        )

        six.assertRaisesRegex(self,
            AssertionError,
            "'kind' must be one of 'year', 'month' or 'day'.",
            Article.objects.dates,
            "pub_date",
            "bad_kind",
        )

        six.assertRaisesRegex(self,
            AssertionError,
            "'order' must be either 'ASC' or 'DESC'.",
            Article.objects.dates,
            "pub_date",
            "year",
            order="bad order",
        )

        # Use iterator() with dates() to return a generator that lazily
        # requests each result one at a time, to save memory.
        dates = []
        for article in Article.objects.dates('pub_date', 'day', order='DESC').iterator():
            dates.append(article)
        self.assertEqual(dates, [
            datetime(2005, 7, 31, 0, 0),
            datetime(2005, 7, 30, 0, 0),
            datetime(2005, 7, 29, 0, 0),
            datetime(2005, 7, 28, 0, 0)])

        # You can combine queries with & and |.
        s1 = Article.objects.filter(id__exact=a.id)
        s2 = Article.objects.filter(id__exact=a2.id)
        self.assertQuerysetEqual(s1 | s2,
            ["<Article: Area man programs in Python>",
             "<Article: Second article>"])
        self.assertQuerysetEqual(s1 & s2, [])

        # You can get the number of objects like this:
        self.assertEqual(len(Article.objects.filter(id__exact=a.id)), 1)

        # You can get items using index and slice notation.
        self.assertEqual(Article.objects.all()[0], a)
        self.assertQuerysetEqual(Article.objects.all()[1:3],
            ["<Article: Second article>", "<Article: Third article>"])

        s3 = Article.objects.filter(id__exact=a3.id)
        self.assertQuerysetEqual((s1 | s2 | s3)[::2],
            ["<Article: Area man programs in Python>",
             "<Article: Third article>"])

        # Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
        if not six.PY3:
            self.assertEqual(Article.objects.all()[long(0)], a)
            self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)],
                ["<Article: Second article>", "<Article: Third article>"])
            self.assertQuerysetEqual((s1 | s2 | s3)[::long(2)],
                ["<Article: Area man programs in Python>",
                "<Article: Third article>"])

            # And can be mixed with ints.
            self.assertQuerysetEqual(Article.objects.all()[1:long(3)],
                ["<Article: Second article>", "<Article: Third article>"])

        # Slices (without step) are lazy:
        self.assertQuerysetEqual(Article.objects.all()[0:5].filter(),
            ["<Article: Area man programs in Python>",
             "<Article: Second article>",
             "<Article: Third article>",
             "<Article: Article 6>",
             "<Article: Default headline>"])

        # Slicing again works:
        self.assertQuerysetEqual(Article.objects.all()[0:5][0:2],
            ["<Article: Area man programs in Python>",
             "<Article: Second article>"])
        self.assertQuerysetEqual(Article.objects.all()[0:5][:2],
            ["<Article: Area man programs in Python>",
             "<Article: Second article>"])
        self.assertQuerysetEqual(Article.objects.all()[0:5][4:],
            ["<Article: Default headline>"])
        self.assertQuerysetEqual(Article.objects.all()[0:5][5:], [])

        # Some more tests!
        self.assertQuerysetEqual(Article.objects.all()[2:][0:2],
            ["<Article: Third article>", "<Article: Article 6>"])
        self.assertQuerysetEqual(Article.objects.all()[2:][:2],
            ["<Article: Third article>", "<Article: Article 6>"])
        self.assertQuerysetEqual(Article.objects.all()[2:][2:3],
            ["<Article: Default headline>"])

        # Using an offset without a limit is also possible.
        self.assertQuerysetEqual(Article.objects.all()[5:],
            ["<Article: Fourth article>",
             "<Article: Article 7>",
             "<Article: Updated article 8>"])

        # Also, once you have sliced you can't filter, re-order or combine
        six.assertRaisesRegex(self,
            AssertionError,
            "Cannot filter a query once a slice has been taken.",
            Article.objects.all()[0:5].filter,
            id=a.id,
        )

        six.assertRaisesRegex(self,
            AssertionError,
            "Cannot reorder a query once a slice has been taken.",
            Article.objects.all()[0:5].order_by,
            'id',
        )

        try:
            Article.objects.all()[0:1] & Article.objects.all()[4:5]
            self.fail('Should raise an AssertionError')
        except AssertionError as e:
            self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.")
        except Exception as e:
            self.fail('Should raise an AssertionError, not %s' % e)

        # Negative slices are not supported, due to database constraints.
        # (hint: inverting your ordering might do what you need).
        try:
            Article.objects.all()[-1]
            self.fail('Should raise an AssertionError')
        except AssertionError as e:
            self.assertEqual(str(e), "Negative indexing is not supported.")
        except Exception as e:
            self.fail('Should raise an AssertionError, not %s' % e)

        error = None
        try:
            Article.objects.all()[0:-5]
        except Exception as e:
            error = e
        self.assertTrue(isinstance(error, AssertionError))
        self.assertEqual(str(error), "Negative indexing is not supported.")

        # An Article instance doesn't have access to the "objects" attribute.
        # That's only available on the class.
        six.assertRaisesRegex(self,
            AttributeError,
            "Manager isn't accessible via Article instances",
            getattr,
            a7,
            "objects",
        )

        # Bulk delete test: How many objects before and after the delete?
        self.assertQuerysetEqual(Article.objects.all(),
            ["<Article: Area man programs in Python>",
             "<Article: Second article>",
             "<Article: Third article>",
             "<Article: Article 6>",
             "<Article: Default headline>",
             "<Article: Fourth article>",
             "<Article: Article 7>",
             "<Article: Updated article 8>"])
        Article.objects.filter(id__lte=a4.id).delete()
        self.assertQuerysetEqual(Article.objects.all(),
            ["<Article: Article 6>",
             "<Article: Default headline>",
             "<Article: Article 7>",
             "<Article: Updated article 8>"])

    @skipUnlessDBFeature('supports_microsecond_precision')
    def test_microsecond_precision(self):
        # In PostgreSQL, microsecond-level precision is available.
        a9 = Article(
            headline='Article 9',
            pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
        )
        a9.save()
        self.assertEqual(Article.objects.get(pk=a9.pk).pub_date,
            datetime(2005, 7, 31, 12, 30, 45, 180))

    @skipIfDBFeature('supports_microsecond_precision')
    def test_microsecond_precision_not_supported(self):
        # In MySQL, microsecond-level precision isn't available. You'll lose
        # microsecond-level precision once the data is saved.
        a9 = Article(
            headline='Article 9',
            pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
        )
        a9.save()
        self.assertEqual(Article.objects.get(id__exact=a9.id).pub_date,
            datetime(2005, 7, 31, 12, 30, 45))

    def test_manually_specify_primary_key(self):
        # You can manually specify the primary key when creating a new object.
        a101 = Article(
            id=101,
            headline='Article 101',
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a101.save()
        a101 = Article.objects.get(pk=101)
        self.assertEqual(a101.headline, 'Article 101')

    def test_create_method(self):
        # You can create saved objects in a single step
        a10 = Article.objects.create(
            headline="Article 10",
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        self.assertEqual(Article.objects.get(headline="Article 10"), a10)

    def test_year_lookup_edge_case(self):
        # Edge-case test: A year lookup should retrieve all objects in
        # the given year, including Jan. 1 and Dec. 31.
        a11 = Article.objects.create(
            headline='Article 11',
            pub_date=datetime(2008, 1, 1),
        )
        a12 = Article.objects.create(
            headline='Article 12',
            pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
        )
        self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008),
            ["<Article: Article 11>", "<Article: Article 12>"])

    def test_unicode_data(self):
        # Unicode data works, too.
        a = Article(
            headline='\u6797\u539f \u3081\u3050\u307f',
            pub_date=datetime(2005, 7, 28),
        )
        a.save()
        self.assertEqual(Article.objects.get(pk=a.id).headline,
            '\u6797\u539f \u3081\u3050\u307f')

    def test_hash_function(self):
        # Model instances have a hash function, so they can be used in sets
        # or as dictionary keys. Two models compare as equal if their primary
        # keys are equal.
        a10 = Article.objects.create(
            headline="Article 10",
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a11 = Article.objects.create(
            headline='Article 11',
            pub_date=datetime(2008, 1, 1),
        )
        a12 = Article.objects.create(
            headline='Article 12',
            pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
        )

        s = set([a10, a11, a12])
        self.assertTrue(Article.objects.get(headline='Article 11') in s)

    def test_field_ordering(self):
        """
        Field instances have a `__lt__` comparison function to define an
        ordering based on their creation. Prior to #17851 this ordering
        comparison relied on the now unsupported `__cmp__` and was assuming
        compared objects were both Field instances raising `AttributeError`
        when it should have returned `NotImplemented`.
        """
        f1 = Field()
        f2 = Field(auto_created=True)
        f3 = Field()
        self.assertTrue(f2 < f1)
        self.assertTrue(f3 > f1)
        self.assertFalse(f1 == None)
        self.assertFalse(f2 in (None, 1, ''))

    def test_extra_method_select_argument_with_dashes_and_values(self):
        # The 'select' argument to extra() supports names with dashes in
        # them, as long as you use values().
        a10 = Article.objects.create(
            headline="Article 10",
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a11 = Article.objects.create(
            headline='Article 11',
            pub_date=datetime(2008, 1, 1),
        )
        a12 = Article.objects.create(
            headline='Article 12',
            pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
        )

        dicts = Article.objects.filter(
            pub_date__year=2008).extra(
                select={'dashed-value': '1'}
            ).values('headline', 'dashed-value')
        self.assertEqual([sorted(d.items()) for d in dicts],
            [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])

    def test_extra_method_select_argument_with_dashes(self):
        # If you use 'select' with extra() and names containing dashes on a
        # query that's *not* a values() query, those extra 'select' values
        # will silently be ignored.
        a10 = Article.objects.create(
            headline="Article 10",
            pub_date=datetime(2005, 7, 31, 12, 30, 45),
        )
        a11 = Article.objects.create(
            headline='Article 11',
            pub_date=datetime(2008, 1, 1),
        )
        a12 = Article.objects.create(
            headline='Article 12',
            pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
        )

        articles = Article.objects.filter(
            pub_date__year=2008).extra(
                select={'dashed-value': '1', 'undashedvalue': '2'})
        self.assertEqual(articles[0].undashedvalue, 2)

    def test_create_relation_with_ugettext_lazy(self):
        """
        Test that ugettext_lazy objects work when saving model instances
        through various methods. Refs #10498.
        """
        notlazy = 'test'
        lazy = ugettext_lazy(notlazy)
        reporter = Article.objects.create(headline=lazy, pub_date=datetime.now())
        article = Article.objects.get()
        self.assertEqual(article.headline, notlazy)
        # test that assign + save works with Promise objecs
        article.headline = lazy
        article.save()
        self.assertEqual(article.headline, notlazy)
        # test .update()
        Article.objects.update(headline=lazy)
        article = Article.objects.get()
        self.assertEqual(article.headline, notlazy)
        # still test bulk_create()
        Article.objects.all().delete()
        Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())])
        article = Article.objects.get()
        self.assertEqual(article.headline, notlazy)


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class VirtualDiskPartitionedRawDiskVer2BackingOption extends VirtualDiskRawDiskVer2BackingOption
{
}


text:
@import MediaPlayer;
#import "CLVideoPlayerControls.h"

NS_ASSUME_NONNULL_BEGIN

static NSString* const CLVideoPlayerContentURLDidChangeNotification = @"CLVideoPlayerContentURLDidChangeNotification";

@protocol CLVideoPlayerControllerDelegate <NSObject>
@optional
- (void)movieTimedOut;
- (void)playerDidStopPlaying:(NSURL*)nsurl atPlayBackTime:(float)timeinterval;
- (void)videoPlayerTapped:(id) sender;
- (void)transcriptLoaded:(NSArray *)transcript;
- (void)didFinishVideoPlaying;
@required
- (void)moviePlayerWillMoveFromWindow;
@end

@interface CLVideoPlayer : MPMoviePlayerController<CLVideoPlayerControlsDelegate> {
}

- (void)setFullscreen:(BOOL)fullscreen animated:(BOOL)animated forceRotate:(BOOL)rotate;
- (void)setFrame:(CGRect)frame;
- (id)initWithFrame:(CGRect)frame;
- (void)setFullscreen:(BOOL)fullscreen withOrientation:(UIInterfaceOrientation)orientation;
- (void)setFullscreen:(BOOL)fullscreen withOrientation:(UIInterfaceOrientation) orientation animated:(BOOL)animated forceRotate:(BOOL)rotate;
- (void)resetMoviePlayer;

@property (nonatomic, weak, nullable) id <CLVideoPlayerControllerDelegate> delegate;
@property (nonatomic, strong, nullable) CLVideoPlayerControls* controls;
@property(nonatomic, strong) NSString* videoTitle;
@property(nonatomic) float lastPlayedTime;
@property(nonatomic) float startTime;
@property(nonatomic, assign) BOOL autoPlaying;

@end

NS_ASSUME_NONNULL_END


text:
  Celsius:

  <input id="celsius" type="number" min="-100" max="100" value="0">

  Fahrenheit:

  <input id="fahrenheit" type="number" min="-100" max="100" value="32">

Open and execute temperature-demo.js in a separate workspace


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Overview List (unirest-java 1.4.10-SNAPSHOT API)</title>
<meta name="date" content="2017-02-10">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

com.mashape.unirest.http

com.mashape.unirest.http.async

com.mashape.unirest.http.async.utils

com.mashape.unirest.http.exceptions

com.mashape.unirest.http.options

com.mashape.unirest.http.utils

com.mashape.unirest.request

com.mashape.unirest.request.body


text:
"""
Project Euler 62
https://projecteuler.net/problem=62

The cube, 41063625 (345^3), can be permuted to produce two other cubes:
56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube
which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are
cube.
"""

from collections import defaultdict

def solution(max_base: int = 5) -> int:
    """
    Iterate through every possible cube and sort the cube's digits in
    ascending order. Sorting maintains an ordering of the digits that allows
    you to compare permutations. Store each sorted sequence of digits in a
    dictionary, whose key is the sequence of digits and value is a list of
    numbers that are the base of the cube.

    Once you find 5 numbers that produce the same sequence of digits, return
    the smallest one, which is at index 0 since we insert each base number in
    ascending order.

    >>> solution(2)
    125
    >>> solution(3)
    41063625
    """
    freqs = defaultdict(list)
    num = 0

    while True:
        digits = get_digits(num)
        freqs[digits].append(num)

        if len(freqs[digits]) == max_base:
            base = freqs[digits][0] ** 3
            return base

        num += 1

def get_digits(num: int) -> str:
    """
    Computes the sorted sequence of digits of the cube of num.

    >>> get_digits(3)
    '27'
    >>> get_digits(99)
    '027999'
    >>> get_digits(123)
    '0166788'
    """
    return "".join(sorted(str(num**3)))

if __name__ == "__main__":
    print(f"{solution() = }")


text:
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;

public class FeatureSelection {

	public static void main(String[] args) throws IOException {
		String str =  FileIO.readFile("D:\\Lecture Notes\\eclipse\\feature selection application\\src\\dataset.txt",Charset.forName("UTF-8"));

	      List<FeatureInstance> lst =  StringToFeature.stringToFeature(str);
	      HashMap<Integer, Double> finalList=PMI.PMICheck(lst);

	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Acta bot. hung. 7: 134 (1961)

#### Original name
Monilia zeylanoides Castell.

### Remarks
null


text:
layout: post
title: Creating a Ionic Module and sharing through NPM
categories: [Ionic]
tags: [tutorial,ionic,npm]
author:
  name: Daniel Antonio Conte
  email: danconte72@gmail.com
  github: danconte72
  twitter: danielconte
  bio: Life, Universe, Everything
  email_md5: 8200df29874231d4d8c2c7beae170b31
---
Sometimes you found yourself writing same code to solve same problems. To avoid this situation a lot o frameworks allow to produce independent and re-usable modules. And ionic allows too.
So let's do it.
![Ionic logo]({{ site.BASE_PATH}}/assets/media/ionic/ionic.jpg)

I did a FilesProvider to manipulate files in an app and now we will start a simple module to share this service between all our ionic apps.

# To-do
- Copy Ionic Module Template;
- Overwrite template files with our code;
- Setup npm config files and dependencies;
- Publish our module on npm;

## Copying Template
The easyest way is just clone the git repository.
```bash
$ git clone https://github.com/ionic-team/ionic-module-template.git ionic-meumobi-utils
```

![Ionic Module Structure]({{ site.BASE_PATH}}/assets/media/ionic/module-folder1.png)

## Coding
I already have my code done from another project so now is just copy and paste.
For this project I only used a provider, but you can use to share components too.
![Ionic Module Structure Updated]({{ site.BASE_PATH}}/assets/media/ionic/module-folder2.png)

### Show me the code
**src/index.ts**
```typescript
export * from './ionic-meumobi-utils.module';
export * from './providers/files';
```
**src/ionic-meumobi-utils.module.ts.ts**
```typescript
import { Observable } from 'rxjs';
import { NgModule, ModuleWithProviders } from '@angular/core';
//My Components/Providers
import { FilesProvider } from './providers/files';
@NgModule({
  declarations: [
      //Here you need to add your components if you want
  ],
  exports: [
      //Here you put all components released to devs
  ]
})
export class IonicMeumobiUtils {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: IonicMeumobiUtils,
      providers: [ FilesProvider ], //providers ;)
    };
  }
}
```
Inside src folder you can work as a src folder in a regular ionic project.
My tip: Just follow the pattern and you will be fine.

## Setup
- For each module you project it depends. Run:
```bash
$ npm install --save <module-name>[@version]
```
- Update README.md file (explaining how to use your library);
- Update this fields on **package.json**
```json
{
  "name": "ionic-meumobi-utils", //name
  "version": "0.0.6", //version
  "description": "A package to share generic modules between ionic apps", //this too
  "main": "./dist/index.js",
  "typings": "./dist/index.d.ts",
  "files": [
    "dist"
  ], //put into brackets
  "scripts": {
    "ngc": "ngc",
    "build": "rm -rf aot dist && npm run ngc",
    "publishPackage": "npm run build && npm publish"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/meumobi/ionic-meumobi-utils.git" //where the project is available
  },
  "keywords": ["ionic", "files", "angular2"], //to index your library
  "author": "meumobi.com",
  "license": "MIT", //license
  "bugs": {
    "url": "https://github.com/meumobi/ionic-meumobi-utils/issues" //to report bugs
  },
  "homepage": "https://github.com/meumobi/ionic-meumobi-utils#readme", //your readme file
  "devDependencies": {
    ... //updated by npm install --save
  },
  "dependencies": {
    ... //updated by npm install --save
  }
}
```
- Create a **npm** account [here](https://www.npmjs.com/signup);

## Deploy
```bash
$ npm login
$ npm run build
$ npm publish
```
You can build for one version a lot of times, but each version can be published only one time.

To use your module in another project.
```bash
$ npm install <my-module-name>
```
```typescript
import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

// Import your module
import { MyModule } from 'ionic-module-template';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    MyModule // Put your module here
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: []
})
export class AppModule {}
```

# Furthermore
- [How to create a angular library](http://www.dzurico.com/how-to-create-an-angular-library/);
- [Ionic Module Template](https://github.com/ionic-team/ionic-module-template);
- [Ionic MeuMobi Utils on npm](https://www.npmjs.com/package/ionic-meumobi-utils);
- [How to Publish a Custom Ionic Module With NPM](https://devdactic.com/custom-ionic-module-npm/)


text:
class CreateRatings < ActiveRecord::Migration
  def self.up
    create_table :ratings do |t|
      t.integer :rater_id
      t.string   :rater_type
      t.integer  :ratable_id
      t.string   :ratable_type
      t.integer  :score

      t.timestamps
    end
  end

  def self.down
    drop_table :ratings
  end
end


text:
package net.dougqh.aggregator;

public interface InputProvider<I> {
	public abstract void run(final InputScheduler<? super I> scheduler) throws Exception;
}


text:
from helper import *

class TestMalformed(BaseXMPP, unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestMalformed, self).__init__(*args, **kwargs)
        self.setup_basic()
        self.username = self.config.get('general', 'username')
        self.password = self.config.get('general', 'password')
        self.jid = jid.JID(self.username)
        self.timeout = 2

    def missing(self, **kwargs):
        kwargs['type'] = kwargs.get('type', 'org.tyrion.service.bash')
        kwargs['handle_success'] = kwargs.get(
            'handle_success',
            self.handle_service_unavailable_success,
        )
        kwargs['handle_error'] = kwargs.get(
            'handle_error',
            self.handle_service_unavailable_error,
        )
        return self.create_service(**kwargs)

    def test_missing_service(self):
        return self.missing(service=None)

    def test_missing_type(self):
        return self.missing(type=None)

    def test_missing_id(self):
        return self.missing(id=None)

    def test_missing_input(self):
        return self.missing(input=None)


text:
from .case_insensitive_unique_index import CaseInsensitiveUniqueIndex
from .conditional_unique_index import ConditionalUniqueIndex
from .unique_index import UniqueIndex

__all__ = [
    "UniqueIndex",
    "ConditionalUniqueIndex",
    "CaseInsensitiveUniqueIndex",
]


text:
.class Landroid/widget/ExpandableListView$SavedState;
.super Landroid/view/View$BaseSavedState;
.source "ExpandableListView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/ExpandableListView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "SavedState"
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/widget/ExpandableListView$SavedState;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field expandedGroupMetadataList:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/widget/ExpandableListConnector$GroupMetadata;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 1141
    new-instance v0, Landroid/widget/ExpandableListView$SavedState$1;

    invoke-direct {v0}, Landroid/widget/ExpandableListView$SavedState$1;-><init>()V

    sput-object v0, Landroid/widget/ExpandableListView$SavedState;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method private constructor <init>(Landroid/os/Parcel;)V
    .locals 2
    .parameter "in"

    .prologue
    .line 1130
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcel;)V

    .line 1131
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/widget/ExpandableListView$SavedState;->expandedGroupMetadataList:Ljava/util/ArrayList;

    .line 1132
    iget-object v0, p0, Landroid/widget/ExpandableListView$SavedState;->expandedGroupMetadataList:Ljava/util/ArrayList;

    const-class v1, Landroid/widget/ExpandableListConnector;

    invoke-virtual {v1}, Ljava/lang/Class;->getClassLoader()Ljava/lang/ClassLoader;

    move-result-object v1

    invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->readList(Ljava/util/List;Ljava/lang/ClassLoader;)V

    .line 1133
    return-void
.end method

.method synthetic constructor <init>(Landroid/os/Parcel;Landroid/widget/ExpandableListView$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 1113
    invoke-direct {p0, p1}, Landroid/widget/ExpandableListView$SavedState;-><init>(Landroid/os/Parcel;)V

    return-void
.end method

.method constructor <init>(Landroid/os/Parcelable;Ljava/util/ArrayList;)V
    .locals 0
    .parameter "superState"
    .parameter
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/os/Parcelable;",
            "Ljava/util/ArrayList",
            "<",
            "Landroid/widget/ExpandableListConnector$GroupMetadata;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 1122
    .local p2, expandedGroupMetadataList:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Landroid/widget/ExpandableListConnector$GroupMetadata;>;"
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcelable;)V

    .line 1123
    iput-object p2, p0, Landroid/widget/ExpandableListView$SavedState;->expandedGroupMetadataList:Ljava/util/ArrayList;

    .line 1124
    return-void
.end method

# virtual methods
.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1
    .parameter "out"
    .parameter "flags"

    .prologue
    .line 1137
    invoke-super {p0, p1, p2}, Landroid/view/View$BaseSavedState;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1138
    iget-object v0, p0, Landroid/widget/ExpandableListView$SavedState;->expandedGroupMetadataList:Ljava/util/ArrayList;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeList(Ljava/util/List;)V

    .line 1139
    return-void
.end method


text:
import datetime
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty
from preferences import Preferences

class DatePicker(GridLayout):
  year = NumericProperty(datetime.datetime.now().year)
  month = NumericProperty(datetime.datetime.now().month)
  day = NumericProperty(datetime.datetime.now().day)

  def __init__(self, **kwargs):
    super(DatePicker, self).__init__(**kwargs)
    self.cols = 3
    self.rows = 3
    self.btn_up_year = Button()
    self.btn_up_month = Button()
    self.btn_up_day = Button()
    self.lbl_year = Label()
    self.lbl_month = Label()
    self.lbl_day = Label()
    self.lbl_year.color = Preferences.foreground
    self.lbl_month.color = Preferences.foreground
    self.lbl_day.color = Preferences.foreground
    self.btn_down_year = Button()
    self.btn_down_month = Button()
    self.btn_down_day = Button()
    self.btn_up_year.bind(on_press=self.inc_year)
    self.btn_up_month.bind(on_press=self.inc_month)
    self.btn_up_day.bind(on_press=self.inc_day)
    self.btn_down_year.bind(on_press=self.dec_year)
    self.btn_down_month.bind(on_press=self.dec_month)
    self.btn_down_day.bind(on_press=self.dec_day)
    self.add_widget(self.btn_up_year)
    self.add_widget(self.btn_up_month)
    self.add_widget(self.btn_up_day)
    self.add_widget(self.lbl_year)
    self.add_widget(self.lbl_month)
    self.add_widget(self.lbl_day)
    self.add_widget(self.btn_down_year)
    self.add_widget(self.btn_down_month)
    self.add_widget(self.btn_down_day)
    self.bind(year=self.update_date)
    self.bind(month=self.update_date)
    self.bind(day=self.update_date)
    self.listeners = []
    self.update_date()

  def update_date(self, *args):
    list_date = [str(self.year), str(self.month).zfill(2), str(self.day).zfill(2)]
    self.lbl_year.text = list_date[0]
    self.lbl_month.text = list_date[1]
    self.lbl_day.text = list_date[2]
    date = list_date[0] + "-" + list_date[1] + "-" + list_date[2]
    for listener in self.listeners:
      listener.set_date(date)

  def inc_year(self, *args):
    self.year += 1

  def dec_year(self, *args):
    self.year -= 1

  def inc_month(self, *args):
    if self.month == 12:
      self.month = 1
    else: self.month += 1

  def dec_month(self, *args):
    if self.month == 1:
      self.month = 12
    else: self.month -= 1

  def inc_day(self, *args):
    if self.day == 31:
      self.day = 1
    else: self.day += 1

  def dec_day(self, *args):
    if self.day == 1:
      self.day = 31
    else: self.day -= 1

  def append_listener(self, widget):
    self.listeners.append(widget)

  def remove_listener(self, widget):
    self.listeners.remove(widget)


text:
namespace apl
{
typedef ThreadBoost Thread;
};

#endif


text:
package hpoweb.uicontent.graph;

import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.util.Collection;
import java.util.Random;

import org.apache.commons.collections15.Transformer;

import com.vaadin.graph.layout.JungLayoutEngine;
import com.vaadin.graph.layout.JungLayoutEngineModel;
import com.vaadin.graph.shared.ArcProxy;
import com.vaadin.graph.shared.NodeProxy;

import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.algorithms.layout.DAGLayout;
import edu.uci.ics.jung.algorithms.layout.FRLayout2;
import edu.uci.ics.jung.algorithms.util.IterativeContext;
import edu.uci.ics.jung.graph.Graph;

public class JungDAGLayoutEngine extends JungLayoutEngine {
	private static final long serialVersionUID = 1L;
	private JungLayoutEngineModel model;

	public JungDAGLayoutEngine() {
		this(new JungLayoutEngineModel());
	}

	public JungDAGLayoutEngine(JungLayoutEngineModel model) {

		super(model);
		this.model = model;
	}

	@Override
	public void layout(final int width, final int height, Collection<NodeProxy> lockedNodes) {

		AbstractLayout<NodeProxy, ArcProxy> layout1 = createLayout(model.getGraph(), new Dimension(width, height));
		layoutWithLayout(width, height, lockedNodes, layout1, 5000);

		// int numberOfNodes = model.getNodes().size();
		// AbstractLayout<NodeProxy, ArcProxy> layout2 = createLayout2(model.getGraph(), new Dimension(width, height));
		// layoutWithLayout(width, height, lockedNodes, layout2, numberOfNodes);
	}

	private void layoutWithLayout(final int width, final int height, Collection<NodeProxy> lockedNodes, AbstractLayout<NodeProxy, ArcProxy> layout,
			int numSteps) {

		layout.lock(false);
		for (NodeProxy v : lockedNodes) {
			layout.lock(v, true);
		}
		layout.setInitializer(new Transformer<NodeProxy, Point2D>() {
			public Point2D transform(NodeProxy input) {
				int x = input.getX();
				int y = input.getY();
				return new Point2D.Double(x == -1 ? new Random().nextInt(width) : x, y == -1 ? new Random().nextInt(height) : y);
			}
		});

		layout.initialize();
		int iterationCounter = 0;
		if (layout instanceof IterativeContext) {
			IterativeContext layoutIt = ((IterativeContext) layout);
			while (!layoutIt.done()) {
				iterationCounter++;
				layoutIt.step();
				/*
				 * Sometimes this seems to cause problems and the .done() does not terminate. Thus we make a hard stop after a fixed number
				 * of iterations
				 */
				if (iterationCounter > numSteps)
					break;
			}
		}

		for (NodeProxy v : model.getGraph().getVertices()) {
			Point2D location = layout.transform(v);
			v.setX((int) location.getX());
			v.setY((int) location.getY());
		}
	}

	@Override
	protected AbstractLayout<NodeProxy, ArcProxy> createLayout(Graph<NodeProxy, ArcProxy> graph, Dimension size) {
		// FRLayout2<NodeProxy, ArcProxy> layout = new FRLayout2<NodeProxy,
		// ArcProxy>(graph);
		DAGLayout<NodeProxy, ArcProxy> layout = new DAGLayout<NodeProxy, ArcProxy>(graph);
		// Dimension d = new Dimension(2000, 2000);
		layout.setSize(size);
		return layout;
	}

	protected AbstractLayout<NodeProxy, ArcProxy> createLayout2(Graph<NodeProxy, ArcProxy> graph, Dimension size) {
		FRLayout2<NodeProxy, ArcProxy> layout = new FRLayout2<NodeProxy, ArcProxy>(graph);
		// DAGLayout<NodeProxy, ArcProxy> layout = new DAGLayout<NodeProxy,
		// ArcProxy>(graph);
		// Dimension d = new Dimension(2000, 2000);
		layout.setSize(size);
		return layout;
	}

}


text:
- Fix the bug that failed to run pytorchjob with RDMA
- Fix the bug that error dispaly gpu core resources on nodes
- Fix the bug that add evaluator and tensorboard to pod group

### Changed

- Refact installtion
- Modify restful-serving to http-serving of deployment services
- Optimize the operators to omit the Completed jobs into the queue

### Added

- Support modeljob adapts helm3
- Cron workload supports custom labels
- Java SDK submits training job with --label
- Add resource limits for tfjob
- Add subpathexpr for job