text:
// CLASS HEADER
#include <dali/public-api/rendering/decorated-visual-renderer.h>

// INTERNAL INCLUDES
#include <dali/internal/event/rendering/decorated-visual-renderer-impl.h>

namespace Dali
{
DecoratedVisualRenderer DecoratedVisualRenderer::New(Geometry& geometry, Shader& shader)
{
  Internal::DecoratedVisualRendererPtr renderer = Internal::DecoratedVisualRenderer::New();
  renderer->SetGeometry(GetImplementation(geometry));
  renderer->SetShader(GetImplementation(shader));
  return DecoratedVisualRenderer(renderer.Get());
}

DecoratedVisualRenderer::DecoratedVisualRenderer() = default;

DecoratedVisualRenderer::~DecoratedVisualRenderer() = default;

DecoratedVisualRenderer::DecoratedVisualRenderer(const DecoratedVisualRenderer& handle) = default;

DecoratedVisualRenderer DecoratedVisualRenderer::DownCast(BaseHandle handle)
{
  return DecoratedVisualRenderer(dynamic_cast<Dali::Internal::DecoratedVisualRenderer*>(handle.GetObjectPtr()));
}

DecoratedVisualRenderer& DecoratedVisualRenderer::operator=(const DecoratedVisualRenderer& handle) = default;

DecoratedVisualRenderer::DecoratedVisualRenderer(DecoratedVisualRenderer&& rhs) = default;

DecoratedVisualRenderer& DecoratedVisualRenderer::operator=(DecoratedVisualRenderer&& rhs) = default;

void DecoratedVisualRenderer::RegisterCornerRadiusUniform()
{
  GetImplementation(*this).RegisterCornerRadiusUniform();
}

void DecoratedVisualRenderer::RegisterBorderlineUniform()
{
  GetImplementation(*this).RegisterBorderlineUniform();
}

void DecoratedVisualRenderer::RegisterBlurRadiusUniform()
{
  GetImplementation(*this).RegisterBlurRadiusUniform();
}

DecoratedVisualRenderer::DecoratedVisualRenderer(Internal::DecoratedVisualRenderer* pointer)
: Dali::VisualRenderer(pointer)
{
}

} //namespace Dali


text:
from feed_grabber import FeedGrabber
import logging
import urllib2
import json
import time

logger = logging.getLogger(__name__)

class BlockChainGrabber(FeedGrabber):

    def __init__(self, *args, **kwds):
        super(BlockChainGrabber, self).__init__(*args, **kwds)

    def get_latest_transactions(self, number_of_blocks=12):
        response = urllib2.urlopen('https://blockchain.info/latestblock')
        last_block = json.load(response)['height']
        txs = []
        for i in range(0, number_of_blocks):
            block_index = last_block - i
            response = urllib2.urlopen('https://blockchain.info/rawblock/' + str(last_block))
            block_txs = json.load(response)['tx']
            # remove unneeded data
            txs_data = map(self._filter_data, block_txs)
            txs += txs_data
        return txs

    def _filter_data(self, block_tx):
        out =  dict(
                time        = block_tx['time'],
                size        = block_tx['size'],
                vout_sz      = block_tx['vout_sz'],
                vin_sz      = block_tx['vin_sz'],
                relayed_by  = block_tx['relayed_by'],
                )

        # calculate total output value
        outputs = map(lambda itx: itx['value'], block_tx['out'])
        out['output_value'] = sum(outputs)

        return out

redpajama_set_name: RedPajamaGithub


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : Jun 22, 2015, 8:54:59 AM
    Author     : Admin
*/

body{
font-family: 'Lato';

}

.loginBox{

    padding:100px;background-image: url('/img/leather.png');
    border: 10px solid transparent;
    border-image: url('/img/stich.png') 25 30 10 20 repeat stretch;

    border-radius: 10px 10px 10px 10px;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border: 1px dotted #523914;
   margin-top:150px;
   text-align: center;
}

.registerBox{
    margin-top:100px;
    padding-top:50px;
}

.btn-leather{
  background: #D8792C;
  background-image: -webkit-linear-gradient(top, #D8792C, #ebaa05);
  background-image: -moz-linear-gradient(top, #D8792C, #ebaa05);
  background-image: -ms-linear-gradient(top, #D8792C, #ebaa05);
  background-image: -o-linear-gradient(top, #D8792C, #ebaa05);
  background-image: linear-gradient(to bottom, #D8792C, #ebaa05);
  -webkit-border-radius: 52;
  -moz-border-radius: 52;
  border-radius: 52px;
  font-family: Arial;
  color: #ffffff;
  font-size: 19px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}

.btn-leather:hover {
  background: #D8792C;
  background-image: -webkit-linear-gradient(top, #D8792C, #e6884a);
  background-image: -moz-linear-gradient(top, #D8792C, #e6884a);
  background-image: -ms-linear-gradient(top, #D8792C, #e6884a);
  background-image: -o-linear-gradient(top, #D8792C, #e6884a);
  background-image: linear-gradient(to bottom, #D8792C, #e6884a);
  text-decoration: none;
}

.registerLink{
    color:rgb(168, 41, 41);
    position: absolute;
    right:25px;
    bottom:10px;

}

.registerLink a, .registerLink a:visited,.registerLink a:active{
    color:rgb(168, 41, 41);
    font-size:1.3em;
}
.registerLink a:hover{
    color:rgb(123, 16, 16);
    text-decoration: none;
     font-weight: bold;
}
.loginHomeLink{

    color: rgb(168, 41, 41);
    position: absolute;
    left:15px;
    top:20px;
    font-size:1.3em !important;
}
.loginHomeLink a, .loginHomeLink a:visited, .loginHomeLink a:active{

    color: rgb(168, 41, 41);
}
.loginHomeLink a:hover{

    color:rgb(123, 16, 16);
    text-decoration: none;

}
.form-group-lg{
    margin-bottom:20px;
}

.logoutBtn{
    position: absolute;
    right: 190px;
    top:40px;

    z-index: 1000;
}
.phonebookPage{
    padding-left:20px;
    padding-top:20px;
    vertical-align: top
}
.phonebookPage .contactLabel{
    min-width: 70px;
    float:left;
    text-align: right;
    margin-right: 10px;
    font-size: 1em;
    margin-bottom: 20px;

}
.phonebookPage .contactVal{
    min-width: 130px;
    clear:right;
    font-size: 1em;
    color:gray;
     margin-bottom: 20px;
}

.contactAdd{

    background-image: url('/img/add_gray.png');
}
.contactAdd:hover{

    background-image: url('/img/add_blue.jpg');
    cursor: pointer;
}

.contactEdit{

    background-image: url('/img/edit_gray.png');
}
.contactEdit:hover{

    background-image: url('/img/edit_blue.jpg');
     cursor: pointer;
}

.greeting{
     position: absolute;
    right: 290px;
    top:43px;

    z-index: 1000;

}

.deleteIcon{
    position:absolute;
    right:8px;
    top:8px;
}

.invalidForm{
    font-size: .8em;
    color: #66512c;
    text-transform: uppercase;
}
/* Prevents default click */

a[ng-click]{
    cursor: pointer;
}


text:
import json
import sys
from db_handle import db_handle
import argparse

arg_parser = argparse.ArgumentParser()

arg_parser.add_argument("-u", '--user-id', type=int, default=0, \
                        action='store', help="User ID")

arg_parser.add_argument('-p', '--print', help='print BL', \
                        action='store_true', default=False, dest='print')

arg_parser.add_argument('-r', '--remove', help='remove user from BL', \
                        action='store_true', default=False, dest='remove')

arg_parser.add_argument('-a', '--add', help='add user to BL', \
                        action='store_true', default=False, dest='add')

def main():
   args = arg_parser.parse_args()
   db = db_handle()
   if len(sys.argv) == 1:
      arg_parser.print_help()
   else:
      if len(sys.argv) == 2:
         if args.print:
            db.showBlackList()
         else:
            print("You specify a few args.")
      elif len(sys.argv) == 3:
         print ("Wrong set of arguments")
      elif len(sys.argv) == 4:
         try:
            if args.add and args.user_id>0:
               db.addUserToBL(args.user_id)
            elif args.remove and args.user_id>0:
               db.delUserFromBL(args.user_id)
            else:
               print("Error!")
         except TypeError:
            print ("UID must be positive integer")

if __name__ == '__main__':
   main()


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Content tagged as 'Academic' on Alvin Thomas</title>
    <link>https://alvinthomas.github.io/tags/academic/</link>
    <description>Recent content in Content tagged as 'Academic' on Alvin Thomas</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2017-2018 Alvin G. Thomas</copyright>
    <lastBuildDate>Sun, 01 Jan 2017 00:00:00 +0000</lastBuildDate>
    <atom:link href="/tags/academic/" rel="self" type="application/rss+xml" />

  </channel>
</rss>


text:
using System.Text;
using AsmResolver.IO;

namespace AsmResolver.PE.Win32Resources.Version
{
    /// <summary>
    /// Represents the raw version table entry header.
    /// </summary>
    public class VersionTableEntryHeader : SegmentBase
    {
        /// <summary>
        /// Creates a new version table entry header with the provided key.
        /// </summary>
        /// <param name="key">The name of the resource.</param>
        public VersionTableEntryHeader(string key)
        {
            Key = key;
        }

        /// <summary>
        /// Creates a new version table entry header with the provided key.
        /// </summary>
        /// <param name="length">The length in bytes of the structure.</param>
        /// <param name="valueLength">The size in bytes of the value member.</param>
        /// <param name="type">The type of data that is stored.</param>
        /// <param name="key">The name of the resource.</param>
        public VersionTableEntryHeader(ushort length, ushort valueLength, VersionTableValueType type, string key)
        {
            Length = length;
            ValueLength = valueLength;
            Type = type;
            Key = key;
        }

        /// <summary>
        /// Gets or sets the raw length in bytes of the structure.
        /// </summary>
        public ushort Length
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the raw length in bytes of the value member.
        /// </summary>
        public ushort ValueLength
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating the value is binary or textual.
        /// </summary>
        public VersionTableValueType Type
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the key name of the resource.
        /// </summary>
        public string Key
        {
            get;
            set;
        }

        /// <summary>
        /// Reads a single resource table header.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>The table header.</returns>
        public static VersionTableEntryHeader FromReader(ref BinaryStreamReader reader)
        {
            return new VersionTableEntryHeader(
                reader.ReadUInt16(),
                reader.ReadUInt16(),
                (VersionTableValueType) reader.ReadUInt16(),
                reader.ReadUnicodeString());
        }

        /// <summary>
        /// Computes the size of the raw header in bytes.
        /// </summary>
        /// <param name="key">The key of the entry.</param>
        /// <returns>The number of bytes.</returns>
        public static uint GetHeaderSize(string key)
        {
            return (uint) (
                sizeof(ushort) // Length
                + sizeof(ushort) // ValueLength
                + sizeof(ushort) // Type
                + Encoding.Unicode.GetByteCount(key) + sizeof(char) // Key
            );
        }

        /// <inheritdoc />
        public override uint GetPhysicalSize() => GetHeaderSize(Key);

        /// <inheritdoc />
        public override void Write(IBinaryStreamWriter writer)
        {
            writer.WriteUInt16(Length);
            writer.WriteUInt16(ValueLength);
            writer.WriteUInt16((ushort) Type);
            writer.WriteBytes(Encoding.Unicode.GetBytes(Key));
            writer.WriteUInt16(0);
        }
    }
}


text:
namespace autofill {

ChromeMetadataSource::ChromeMetadataSource(
    const std::string& validation_data_url,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : validation_data_url_(validation_data_url),
      url_loader_factory_(std::move(url_loader_factory)) {}

ChromeMetadataSource::~ChromeMetadataSource() {}

void ChromeMetadataSource::Get(const std::string& key,
                               const Callback& downloaded) const {
  const_cast<ChromeMetadataSource*>(this)->Download(key, downloaded);
}

void ChromeMetadataSource::OnSimpleLoaderComplete(
    RequestList::iterator it,
    std::unique_ptr<std::string> response_body) {
  const Callback& callback = it->get()->callback;
  const std::string& key = it->get()->key;
  std::unique_ptr<std::string> data(new std::string());
  bool ok = !!response_body;
  if (ok)
    data->swap(*response_body);
  callback(ok, key, data.release());
  requests_.erase(it);
}

ChromeMetadataSource::Request::Request(
    const std::string& key,
    std::unique_ptr<network::SimpleURLLoader> loader,
    const Callback& callback)
    : key(key), loader(std::move(loader)), callback(callback) {}

void ChromeMetadataSource::Download(const std::string& key,
                                    const Callback& downloaded) {
  GURL resource(validation_data_url_ + key);
  if (!resource.SchemeIsCryptographic()) {
    downloaded(false, key, NULL);
    return;
  }
  DCHECK(url_loader_factory_);
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("lib_address_input", R"(
        semantics {
          sender: "Address Format Metadata"
          description:
            "Address format metadata assists in handling postal addresses from "
            "all over the world."
          trigger:
            "User edits an address in Chromium settings, or shipping address "
            "in Android's 'web payments'."
          data:
            "The country code for the address being edited. No user identifier "
            "is sent."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This feature cannot be disabled in settings. It can only be "
            "prevented if user does not edit the address in Android 'Web "
            "Payments' settings, Android's Chromium settings ('Autofill and "
            "payments' -> 'Addresses'), and Chromium settings on desktop ("
            "'Manage Autofill Settings' -> 'Addresses')."
          policy_exception_justification: "Not implemented."
        })");
  auto resource_request = std::make_unique<network::ResourceRequest>();
  resource_request->url = resource;
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  std::unique_ptr<network::SimpleURLLoader> loader =
      network::SimpleURLLoader::Create(std::move(resource_request),
                                       traffic_annotation);
  auto it = requests_.insert(
      requests_.begin(),
      std::make_unique<Request>(key, std::move(loader), downloaded));
  network::SimpleURLLoader* raw_loader = it->get()->loader.get();
  raw_loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory_.get(),
      base::BindOnce(&ChromeMetadataSource::OnSimpleLoaderComplete,
                     base::Unretained(this), std::move(it)));
}

}  // namespace autofill


text:
#include <stdbool.h>
#include <stdint.h>
#include "lagopus_apis.h"
#include "openflow.h"
#include "openflow13packet.h"
#include "lagopus/ofp_handler.h"
#include "ofp_apis.h"
#include "ofp_bucket.h"
#include "lagopus/group.h"
#include "lagopus/ofp_dp_apis.h"
#include "lagopus/ofp_pdump.h"

static void
group_mod_trace(struct ofp_group_mod *group_mod,
                struct bucket_list *bucket_list) {
  if (lagopus_log_check_trace_flags(TRACE_OFPT_GROUP_MOD)) {
    lagopus_msg_pdump(TRACE_OFPT_GROUP_MOD, PDUMP_OFP_HEADER,
                      group_mod->header, "");
    lagopus_msg_pdump(TRACE_OFPT_GROUP_MOD, PDUMP_OFP_GROUP_MOD,
                      *group_mod, "");
    if (bucket_list != NULL) {
      ofp_bucket_list_trace(TRACE_OFPT_GROUP_MOD, bucket_list);
    }
  }
}

static lagopus_result_t
s_parse_bucket_list(struct pbuf *pbuf,
                    struct bucket_list *bucket_list,
                    struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_OK;
  if (TAILQ_EMPTY(bucket_list) == true && pbuf_plen_get(pbuf) == 0) {
    res = LAGOPUS_RESULT_OK;    /* bucket_list is empty */
  } else {
    /* decode buckets. */
    while (pbuf_plen_get(pbuf) > 0) {
      res = ofp_bucket_parse(pbuf, bucket_list, error);
      if (res != LAGOPUS_RESULT_OK) {
        lagopus_msg_warning("FAILED : ofp_bucket_parse (%s).\n",
                            lagopus_error_get_string(res));
        break;
      }
    }
    /* check plen. */
    if (res == LAGOPUS_RESULT_OK && pbuf_plen_get(pbuf) > 0) {
      lagopus_msg_warning("packet decode failed. (size over).\n");
      ofp_error_set(error, OFPET_GROUP_MOD_FAILED,
                    OFPGMFC_BAD_BUCKET);
      res = LAGOPUS_RESULT_OFP_ERROR;
    }
  }
  return res;
}

static lagopus_result_t
s_ofpgc_add(struct pbuf *pbuf,
            uint64_t dpid,
            struct ofp_group_mod *group_mod,
            struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_ANY_FAILURES;
  struct bucket_list bucket_list;
  TAILQ_INIT(&bucket_list);

  /* decode buckets. */
  res = s_parse_bucket_list(pbuf, &bucket_list, error);
  if (res == LAGOPUS_RESULT_OK) {
    res = ofp_group_mod_add(dpid, group_mod, &bucket_list, error);
  }

  /* dump trace. */
  group_mod_trace(group_mod, &bucket_list);

  ofp_bucket_list_free(&bucket_list);
  return res;
}

static lagopus_result_t
s_ofpgc_modify(struct pbuf *pbuf,
               uint64_t dpid,
               struct ofp_group_mod *group_mod,
               struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_ANY_FAILURES;
  struct bucket_list bucket_list;
  TAILQ_INIT(&bucket_list);

  /* decode buckets. */
  res = s_parse_bucket_list(pbuf, &bucket_list, error);
  if (res == LAGOPUS_RESULT_OK) {
    res = ofp_group_mod_modify(dpid, group_mod, &bucket_list, error);
  }

  /* dump trace. */
  group_mod_trace(group_mod, &bucket_list);

  ofp_bucket_list_free(&bucket_list);
  return res;
}

static lagopus_result_t
s_ofpgc_delete(struct pbuf *pbuf,
               uint64_t dpid,
               struct ofp_group_mod *group_mod,
               struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_ANY_FAILURES;

  /* dump trace. */
  group_mod_trace(group_mod, NULL);

  /* check plen. */
  if (pbuf_plen_get(pbuf) == 0) {
    res = ofp_group_mod_delete(dpid, group_mod, error);
  } else {
    lagopus_msg_warning("packet decode failed. (size over).\n");
    ofp_error_set(error, OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
    res = LAGOPUS_RESULT_OFP_ERROR;
  }
  return res;
}

static lagopus_result_t
s_group_type_check(uint8_t type, struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_OFP_ERROR;

  switch (type) {
    case OFPGT_ALL:
    case OFPGT_SELECT:
    case OFPGT_INDIRECT:
    case OFPGT_FF:
      res = LAGOPUS_RESULT_OK;
      break;
    default:
      lagopus_msg_warning("unknown group_mod type.\n");
      ofp_error_set(error, OFPET_GROUP_MOD_FAILED, OFPGMFC_BAD_TYPE);
      res = LAGOPUS_RESULT_OFP_ERROR;
      break;
  }

  return res;
}

/* Group mod received. */
lagopus_result_t
ofp_group_mod_handle(struct channel *channel, struct pbuf *pbuf,
                     struct ofp_header *xid_header,
                     struct ofp_error *error) {
  lagopus_result_t res = LAGOPUS_RESULT_ANY_FAILURES;
  uint64_t dpid;
  struct ofp_group_mod group_mod;

  /* check params */
  if (channel != NULL && pbuf != NULL &&
      xid_header != NULL && error != NULL) {
    /* Parse group_mod header. */
    res = ofp_group_mod_decode(pbuf, &(group_mod));
    if (res == LAGOPUS_RESULT_OK) {
      /* check type */
      res = s_group_type_check(group_mod.type, error);
      if (res == LAGOPUS_RESULT_OK) {
        /* exec group_mod command. */
        dpid = channel_dpid_get(channel);
        switch (group_mod.command) {
          case OFPGC_ADD:
            res = s_ofpgc_add(pbuf, dpid,
                              &group_mod, error);
            break;
          case OFPGC_MODIFY:
            res = s_ofpgc_modify(pbuf, dpid,
                                 &group_mod, error);
            break;
          case OFPGC_DELETE:
            res = s_ofpgc_delete(pbuf, dpid,
                                 &group_mod, error);
            break;
          default:
            lagopus_msg_warning("unknown group_mod command.\n");
            ofp_error_set(error, OFPET_GROUP_MOD_FAILED, OFPGMFC_BAD_COMMAND);
            res = LAGOPUS_RESULT_OFP_ERROR;
            break;
        }
      }

      if (res != LAGOPUS_RESULT_OK) {
        lagopus_msg_warning("FAILED (%s).\n",
                            lagopus_error_get_string(res));
      }
    } else {
      lagopus_msg_warning("group_mod decode error (%s)\n",
                          lagopus_error_get_string(res));
      ofp_error_set(error, OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
      res = LAGOPUS_RESULT_OFP_ERROR;
    }
  } else {
    /* params are NULL */
    res = LAGOPUS_RESULT_INVALID_ARGS;
  }

  return res;
}


text:
using System;
using System.Linq.Expressions;

using Kirkin.Reflection;
using Kirkin.Utilities;

namespace Kirkin.Mapping
{
    /// <summary>
    /// Mapped member definition.
    /// </summary>
    public abstract class Member<T> : IEquatable<Member<T>>
    {
        /// <summary>
        /// Name of the mapped member.
        /// </summary>
        public abstract string Name { get; }

        /// <summary>
        /// Runtime type of the member.
        /// </summary>
        public abstract Type MemberType { get; }

        /// <summary>
        /// Returns true if this member supports read operations.
        /// </summary>
        public abstract bool CanRead { get; }

        /// <summary>
        /// Returns true if this member supports write operations.
        /// </summary>
        public abstract bool CanWrite { get; }

        /// <summary>
        /// Produces an expression which retrieves the relevant member value from the source.
        /// </summary>
        protected internal abstract Expression ResolveGetter(ParameterExpression source);

        /// <summary>
        /// Produces an expression which stores the value in the relevant member of the target.
        /// </summary>
        protected internal abstract Expression ResolveSetter(ParameterExpression target);

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        public virtual bool Equals(Member<T> other)
        {
            return other != null
                && other.GetType() == GetType() // Exact type in case ResolveGetter/Setter overridden.
                && other.Name == Name
                && other.MemberType == MemberType
                && other.CanRead == CanRead
                && other.CanWrite == CanWrite;
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        public sealed override bool Equals(object obj)
        {
            return Equals(obj as Member<T>);
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        public override int GetHashCode()
        {
            return Hash.Combine(
                GetType().GetHashCode(),
                Name.GetHashCode(),
                MemberType.GetHashCode()
            );
        }

        /// <summary>
        /// Returns a string describing the object
        /// which includes values of all public properties.
        /// </summary>
        public override string ToString()
        {
            return PropertyList<Member<T>>.Default.ToString(this);
        }
    }
}


text:
<?php

declare (strict_types=1);
namespace Rector\Restoration\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Restoration\Type\ConstantReturnToParamTypeConverter;
use Rector\Restoration\ValueObject\InferParamFromClassMethodReturn;
use Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix20210615\Webmozart\Assert\Assert;
/**
 * @see \Rector\Tests\Restoration\Rector\ClassMethod\InferParamFromClassMethodReturnRector\InferParamFromClassMethodReturnRectorTest
 */
final class InferParamFromClassMethodReturnRector extends \Rector\Core\Rector\AbstractRector implements \Rector\Core\Contract\Rector\ConfigurableRectorInterface
{
    /**
     * @api
     * @var string
     */
    public const INFER_PARAMS_FROM_CLASS_METHOD_RETURNS = 'infer_param_from_class_method_returns';
    /**
     * @var InferParamFromClassMethodReturn[]
     */
    private $inferParamFromClassMethodReturn = [];
    /**
     * @var \Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer
     */
    private $returnTypeInferer;
    /**
     * @var \Rector\Restoration\Type\ConstantReturnToParamTypeConverter
     */
    private $constantReturnToParamTypeConverter;
    /**
     * @var \Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger
     */
    private $phpDocTypeChanger;
    public function __construct(\Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer $returnTypeInferer, \Rector\Restoration\Type\ConstantReturnToParamTypeConverter $constantReturnToParamTypeConverter, \Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger $phpDocTypeChanger)
    {
        $this->returnTypeInferer = $returnTypeInferer;
        $this->constantReturnToParamTypeConverter = $constantReturnToParamTypeConverter;
        $this->phpDocTypeChanger = $phpDocTypeChanger;
    }
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change @param doc based on another method return type', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample(<<<'CODE_SAMPLE'
class SomeClass
{
    public function getNodeTypes(): array
    {
        return [String_::class];
    }

    public function process(Node $node)
    {
    }
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class SomeClass
{
    public function getNodeTypes(): array
    {
        return [String_::class];
    }

    /**
     * @param String_ $node
     */
    public function process(Node $node)
    {
    }
}
CODE_SAMPLE
, [self::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS => [new \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn('SomeClass', 'process', 'getNodeTypes')]])]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Stmt\ClassMethod::class];
    }
    /**
     * @param ClassMethod $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        // must be exactly 1 param
        if (\count($node->params) !== 1) {
            return null;
        }
        $firstParam = $node->params[0];
        $paramName = $this->getName($firstParam);
        foreach ($this->inferParamFromClassMethodReturn as $singleInferParamFromClassMethodReturn) {
            $returnClassMethod = $this->matchReturnClassMethod($node, $singleInferParamFromClassMethodReturn);
            if (!$returnClassMethod instanceof \PhpParser\Node\Stmt\ClassMethod) {
                continue;
            }
            $returnType = $this->returnTypeInferer->inferFunctionLike($returnClassMethod);
            $currentPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
            $paramType = $this->constantReturnToParamTypeConverter->convert($returnType);
            if ($paramType instanceof \PHPStan\Type\MixedType) {
                continue;
            }
            if ($this->isParamDocTypeEqualToPhpType($firstParam, $paramType)) {
                return null;
            }
            $this->phpDocTypeChanger->changeParamType($currentPhpDocInfo, $paramType, $firstParam, $paramName);
            return $node;
        }
        return null;
    }
    /**
     * @param array<string, InferParamFromClassMethodReturn[]> $configuration
     */
    public function configure(array $configuration) : void
    {
        $inferParamsFromClassMethodReturns = $configuration[self::INFER_PARAMS_FROM_CLASS_METHOD_RETURNS] ?? [];
        \RectorPrefix20210615\Webmozart\Assert\Assert::allIsInstanceOf($inferParamsFromClassMethodReturns, \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn::class);
        $this->inferParamFromClassMethodReturn = $inferParamsFromClassMethodReturns;
    }
    private function matchReturnClassMethod(\PhpParser\Node\Stmt\ClassMethod $classMethod, \Rector\Restoration\ValueObject\InferParamFromClassMethodReturn $inferParamFromClassMethodReturn) : ?\PhpParser\Node\Stmt\ClassMethod
    {
        $scope = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::SCOPE);
        if (!$scope instanceof \PHPStan\Analyser\Scope) {
            return null;
        }
        $classReflection = $scope->getClassReflection();
        if (!$classReflection instanceof \PHPStan\Reflection\ClassReflection) {
            return null;
        }
        if (!$classReflection->isSubclassOf($inferParamFromClassMethodReturn->getClass())) {
            return null;
        }
        if (!$this->isName($classMethod->name, $inferParamFromClassMethodReturn->getParamMethod())) {
            return null;
        }
        $classLike = $classMethod->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE);
        if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) {
            return null;
        }
        return $classLike->getMethod($inferParamFromClassMethodReturn->getReturnMethod());
    }
    private function isParamDocTypeEqualToPhpType(\PhpParser\Node\Param $param, \PHPStan\Type\Type $paramType) : bool
    {
        $currentParamType = $this->nodeTypeResolver->getStaticType($param);
        return $currentParamType->equals($paramType);
    }
}


text:
class ReleaseLogPreviewsController < ReleaseLogsBaseController
  include ReleaseLogsHelper

  unloadable

  helper :release_logs

  before_filter :load_project
  before_filter :authorize
  before_filter :find_attachments
  before_filter :load_release_log

  layout false

  def release_log
  end

  def cancellation
  end

  def rollback
  end

  def publish_notification
    if @project.queue_release_log_enabled?
      @release_log.title = @release_log.queue_title_for_release_log
    end
  end

  def cancel_notification
    @release_log.canceller = User.current
    @release_log.cancelled_at = Time.current
  end

  def rollback_notification
    @release_log.rollbacker = User.current
    @release_log.rolled_back_at = Time.now
  end

  protected

  def load_project
    @project = Project.find_by_identifier(params[:project_id])
  end

  def load_release_log
    if params[:id]
      @release_log = ReleaseLog.find(params[:id])
      @attachments << @release_log.attachments.flatten
      @attachments.flatten!
    else
      @release_log = ReleaseLog.new
    end

    @release_log.assign_attributes(params[:release_log])
    @release_log.attachments = @attachments
    @release_log.project = @project
    @release_log.id ||= 0

    date = @release_log.released_at ||= Time.now
    @release_log.released_at = Time.now.change(:year => date.year, :month => date.month, :day => date.day, :hour => date.hour, :min => date.min)
  end
end


text:
import unittest

from tests.helpers.env import Env
from tests.helpers.factory import Factory as F
from algoliasearch.exceptions import RequestException

class TestPersonalizationClient(unittest.TestCase):
    def setUp(self):
        self.client = F.personalization_client()

    def tearDown(self):
        self.client.close()

    @unittest.skipIf(
        Env.is_community(), "Community can not test personalization operations"
    )
    def test_personalization(self):
        personalization_strategy = {
            "eventsScoring": [
                {"eventName": "Add to cart", "eventType": "conversion", "score": 50},
                {"eventName": "Purchase", "eventType": "conversion", "score": 100},
            ],
            "facetsScoring": [
                {"facetName": "brand", "score": 100},
                {"facetName": "categories", "score": 10},
            ],
            "personalizationImpact": 0,
        }

        try:
            response = self.client.set_personalization_strategy(
                personalization_strategy
            )
            self.assertEqual(
                response,
                {"status": 200, "message": "Strategy was successfully updated"},
            )
        except RequestException as err:
            self.assertEqual(
                err,
                RequestException("Number of strategy saves exceeded for the day", 429),
            )  # noqa: E501

        response = self.client.get_personalization_strategy()
        self.assertEqual(response, personalization_strategy)


text:
package com.portalworld;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class AnimationTest implements Screen {

	PortalWorld game;
	private static final int        FRAME_COLS = 6;
    private static final int        FRAME_ROWS = 5;
    private static final int 		SPEED = 4;

    Animation                       walkAnimation;
    Texture                         walkSheet;
    TextureRegion[]                 walkFrames;
    SpriteBatch                     spriteBatch;
    TextureRegion                   currentFrame;

    float stateTime;
    int i = -50;
    boolean isAtBorder;

    public AnimationTest(PortalWorld g) {
    	game = g;
    }

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void render(float delta) {
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.begin();
        spriteBatch.draw(currentFrame, i, 50);
        if (isAtBorder)
        	spriteBatch.draw(currentFrame, i - Gdx.graphics.getWidth(), 50);
        spriteBatch.end();
        i += SPEED;
        isAtBorder = (i >= Gdx.graphics.getWidth() - 60) ? true : false;
        if (i >= Gdx.graphics.getWidth()) {
        	i = i - Gdx.graphics.getWidth();
        	isAtBorder = false;
        }

	}

	@Override
	public void resize(int arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub

	}

	@Override
	public void show() {
		// TODO Auto-generated method stub
		walkSheet = new Texture(Gdx.files.internal("data/animation_sheet.png"));
        TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / FRAME_COLS, walkSheet.getHeight() / FRAME_ROWS);
        walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
                for (int j = 0; j < FRAME_COLS; j++) {
                        walkFrames[index++] = tmp[i][j];
                }
        }
        walkAnimation = new Animation(0.025f, walkFrames);
        spriteBatch = new SpriteBatch();
        stateTime = 0f;
	}

}


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>ImplicitObjectELResolver (JSP 2.3 API Documentation - Apache Tomcat 9.0.0.M11)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

JSP 2.3 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.servlet.jsp.el

Class ImplicitObjectELResolver

java.lang.Object

javax.el.ELResolver

javax.servlet.jsp.el.ImplicitObjectELResolver

public class ImplicitObjectELResolver
extends javax.el.ELResolver

Since:

2.1

Field Summary

Fields inherited from class javax.el.ELResolver

RESOLVABLE_AT_DESIGN_TIME, TYPE

Constructor Summary

Constructors

Constructor and Description

ImplicitObjectELResolver()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.Class<java.lang.String>
getCommonPropertyType(javax.el.ELContext context,
                     java.lang.Object base)

java.util.Iterator<java.beans.FeatureDescriptor>
getFeatureDescriptors(javax.el.ELContext context,
                     java.lang.Object base)

java.lang.Class
getType(javax.el.ELContext context,
       java.lang.Object base,
       java.lang.Object property)

java.lang.Object
getValue(javax.el.ELContext context,
        java.lang.Object base,
        java.lang.Object property)

boolean
isReadOnly(javax.el.ELContext context,
          java.lang.Object base,
          java.lang.Object property)

void
setValue(javax.el.ELContext context,
        java.lang.Object base,
        java.lang.Object property,
        java.lang.Object value)

Methods inherited from class javax.el.ELResolver

convertToType, invoke

Methods inherited from class java.lang.Object

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

Constructor Detail

ImplicitObjectELResolver

public ImplicitObjectELResolver()

Method Detail

getValue

public java.lang.Object getValue(javax.el.ELContext context,
                                 java.lang.Object base,
                                 java.lang.Object property)

Specified by:

getValue in class javax.el.ELResolver

Parameters:

context - The EL context for this evaluation

base - The base object on which the property is to be found

property - The property whose value is to be returned

Returns:

the value of the provided property

getType

public java.lang.Class getType(javax.el.ELContext context,
                               java.lang.Object base,
                               java.lang.Object property)

Specified by:

getType in class javax.el.ELResolver

Parameters:

context - The EL context for this evaluation

base - The base object on which the property is to be found

property - The property whose type is to be returned

Returns:

the type of the provided property

setValue

public void setValue(javax.el.ELContext context,
                     java.lang.Object base,
                     java.lang.Object property,
                     java.lang.Object value)

Specified by:

setValue in class javax.el.ELResolver

Parameters:

context - The EL context for this evaluation

base - The base object on which the property is to be found

property - The property whose value is to be set

value - The value to set the property to

isReadOnly

public boolean isReadOnly(javax.el.ELContext context,
                          java.lang.Object base,
                          java.lang.Object property)

Specified by:

isReadOnly in class javax.el.ELResolver

Parameters:

context - The EL context for this evaluation

base - The base object on which the property is to be found

property - The property to be checked for read only status

Returns:

true if the identified property is read only,
         otherwise false

getFeatureDescriptors

public java.util.Iterator<java.beans.FeatureDescriptor> getFeatureDescriptors(javax.el.ELContext context,
                                                                              java.lang.Object base)

Specified by:

getFeatureDescriptors in class javax.el.ELResolver

getCommonPropertyType

public java.lang.Class<java.lang.String> getCommonPropertyType(javax.el.ELContext context,
                                                               java.lang.Object base)

Specified by:

getCommonPropertyType in class javax.el.ELResolver

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

JSP 2.3 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.


text:
package net.offbeatpioneer.intellij.plugins.grav.extensions.module.wizard;

import com.intellij.icons.AllIcons;
import com.intellij.ide.util.BrowseFilesListener;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.fileChooser.*;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.ProjectGeneratorPeer;
import com.intellij.platform.templates.github.DownloadUtil;
import com.intellij.platform.templates.github.Outcome;
import com.intellij.ui.FieldPanel;
import com.intellij.ui.OptionGroup;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.util.download.DownloadableFileDescription;
import com.intellij.util.download.DownloadableFileService;
import com.intellij.util.download.FileDownloader;
import com.intellij.util.io.ZipUtil;
import com.intellij.util.net.IOExceptionDialog;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.GravSdkType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.ui.SquareButton;
import net.offbeatpioneer.intellij.plugins.grav.helper.GithubApi;
import net.offbeatpioneer.intellij.plugins.grav.helper.NotificationHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Wizard interface for creating a new Grav module.
 * <p>
 * The wizard offers the options to specify a local Grav installation or to download a Grav release from GitHub.
 * The latest Grav versions are retrieved directly from GitHub.
 *
 * @author Dominik Grzelak
 */
public class GravCreateProjectForm implements ActionListener {
    // points to the file that defines the URL format of the Grav release in GitHub
    private static final String DOWNLOAD_CONFIG_PROPERTIES = "download-config.properties";

    private final String[] DEFAULT_GRAV_VERSIONS = new String[]{"1.6.30", "1.6.29", "1.6.28"};
    private AtomicBoolean gotLatestVersions; //flag indicates if latest version tags could be retrieved from github
    private String[] gravVersions = null;
    private JPanel mainPanel;
    private JPanel ptop;
    private JPanel pbottom;
    private JLabel lblIntro;
    private ActionLink myDownloadLink;
    private FieldPanel gravDownloadFolderFieldPanel;
    private JLabel lblHint;
    private JComboBox<String> gravVersionComboBox;
    private JLabel lblVersionPrompt;
    private JLabel lblVersionDetermined;
    private ActionLink refreshLink;
    private JRadioButton rbDownloadGrav;
    private JRadioButton rbSelectGrav;
    private JPanel panelSelectGrav;
    private JPanel panelDownloadGrav;
    private JButton btnRefreshGravVersions;
    private JLabel lblGravDownloadPath;
    private OptionGroup panel1;
    private BrowseFilesListener browseFilesListener;
    Properties downloadProps;

    private final List<ProjectGeneratorPeer.SettingsListener> myStateListeners;

    public enum WizardOption {
        SELECT, DOWNLOAD
    }

    private WizardOption wizardOption;

    public GravCreateProjectForm() {
        initDownloadConfigurationFile();
        gotLatestVersions = Objects.isNull(gotLatestVersions) ? new AtomicBoolean(false) : gotLatestVersions;
        myStateListeners = new ArrayList<>();
        this.fireStateChanged();
    }

    public void addSettingsStateListener(ProjectGeneratorPeer.SettingsListener listener) {
        this.myStateListeners.add(listener);
    }

    private void fireStateChanged() {
        boolean validSettings = this.validate() == null;
        Iterator<ProjectGeneratorPeer.SettingsListener> var2 = this.myStateListeners.iterator();

        while (var2.hasNext()) {
            ProjectGeneratorPeer.SettingsListener listener = var2.next();
            listener.stateChanged(validSettings);
        }

    }

    @Nullable
    public ValidationInfo validate() {
        int code = validate0();
        switch (code) {
            case -1:
                return new ValidationInfo("The path pointing to Grav is empty for the selected option"); //.withOKEnabled();
            case -2:
                new ValidationInfo("The path pointing to Grav doesn't exist for the selected option"); //.withOKEnabled();
            case -3:
                return new ValidationInfo("The selected Grav 'SDK' seems not valid for the selected option"); //.withOKEnabled();
            default:
                return null;
        }
    }

    private int validate0() {
        String gravDir = getGravFinalInstallationDirectory().trim();
        if (gravDir.isEmpty()) {
            showHint(true);
            return -1;
        } else {
            VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(gravDir));
            if (vf == null) {
                showHint(true);
                return -2;
            } else {
                if (!GravSdkType.isValidGravSDK(vf)) {
                    showHint(true);
                    return -3;
                }
            }
            String gravSdkVersion = GravSdkType.findGravSdkVersion(gravDir);
            setDeterminedGravVersion(gravSdkVersion);
        }
        showHint(false);
        return 0;
    }

    public JPanel getContentPane() {
        return mainPanel;
    }

    private void initDownloadConfigurationFile() {
        if (Objects.isNull(downloadProps)) {
            downloadProps = loadDownloadConfig();
        }
    }

    public Properties loadDownloadConfig() {
        Properties props = new Properties();
        try (InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(DOWNLOAD_CONFIG_PROPERTIES)) {
            props.load(resourceStream);
        } catch (IOException e) {
//            e.printStackTrace();
        }
        return props;
    }

    public void initLayout() {
        if (!gotLatestVersions.get()) {
//            //download versions
            refreshVersionAction();
        }
        rbSelectGrav.setSelected(true);
        rbSelectGrav.setSelected(false);
        enablePanel(panelSelectGrav, true);
        enablePanel(panelDownloadGrav, false);
        wizardOption = WizardOption.SELECT;

    }

    public void createUIComponents() {
        Runnable consumer = () -> {
            this.fireStateChanged();
        };
        gotLatestVersions = new AtomicBoolean(false);
        initDownloadConfigurationFile();

        lblIntro = new JLabel();
        lblIntro.setText("Select a valid Grav installation or click the link to download the latest version.");
        lblIntro.setVisible(true);
        lblHint = new JLabel();
        lblHint.setVisible(false);

        panelSelectGrav = new JPanel();
        panelDownloadGrav = new JPanel();

        rbSelectGrav = new JRadioButton("Use existing Grav 'SDK'");
        rbSelectGrav.setActionCommand("selectGrav");
        rbSelectGrav.addActionListener(this);
        rbDownloadGrav = new JRadioButton("Download a new Grav 'SDK'");
        rbDownloadGrav.setActionCommand("downloadGrav");
        rbDownloadGrav.addActionListener(this);
        ButtonGroup group = new ButtonGroup();
        group.add(rbSelectGrav);
        group.add(rbDownloadGrav);

        // Download Grav
        btnRefreshGravVersions = new SquareButton();
        btnRefreshGravVersions.setBorderPainted(false);
        btnRefreshGravVersions.setBorder(null);
        btnRefreshGravVersions.setFocusable(false);
        btnRefreshGravVersions.setMargin(JBUI.emptyInsets());
        btnRefreshGravVersions.setContentAreaFilled(false);
        btnRefreshGravVersions.setIcon(AllIcons.Actions.Refresh);
        btnRefreshGravVersions.setFocusPainted(false);
        btnRefreshGravVersions.addActionListener(this);
        btnRefreshGravVersions.setActionCommand("refreshGrav");

        gravVersionComboBox = new ComboBox<>(DEFAULT_GRAV_VERSIONS);

        myDownloadLink = new ActionLink("Download selected Grav 'SDK'", new AnAction() {
            @Override
            public void actionPerformed(AnActionEvent e) {
                FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
                PathChooserDialog pathChooser = FileChooserFactory.getInstance()
                        .createPathChooser(descriptor, null, null);
                pathChooser.choose(VfsUtil.getUserHomeDir(), new FileChooser.FileChooserConsumer() {

                    @Override
                    public void consume(List<VirtualFile> virtualFiles) {
                        if (virtualFiles.size() != 1) {
                            return;
                        }

                        AtomicReference<VirtualFile> dir = new AtomicReference<>(virtualFiles.get(0));
                        String dirName = dir.get().getName();
                        gravDownloadFolderFieldPanel.setText(dir.get().getPath());
                        boolean completed = false;
                        if (!dirName.toLowerCase().contains("grav")) {
                            WriteAction.compute(() -> {
                                try {
                                    dir.set(dir.get().createChildDirectory(this, "grav-sdk"));
                                    return dir;
                                } catch (IOException e) {//
                                }
                                return dir;
                            });
                        }
                        String newdirpath = dir.get().getPresentableUrl() + File.separator + "grav-admin" + File.separator;

                        String downloadUrl = MessageFormat.format(downloadProps.getProperty("downloadUrl"), getSelectedGravVersion(), getSelectedGravVersion());
                        String filename = MessageFormat.format(downloadProps.getProperty("filename"), getSelectedGravVersion());
                        String presentableName = MessageFormat.format(downloadProps.getProperty("presentableDownloadName"), getSelectedGravVersion());

                        DownloadableFileService fileService = DownloadableFileService.getInstance();
                        DownloadableFileDescription fileDescription = fileService.createFileDescription(downloadUrl, filename);

                        List<DownloadableFileDescription> descriptions = new ArrayList<>();
                        descriptions.add(fileDescription);
                        FileDownloader downloader = fileService.createDownloader(descriptions, presentableName);
                        List<VirtualFile> files = downloader.downloadFilesWithProgress(dir.get().getPath(), null, null);
                        if (files != null && files.size() == 1) {
                            try {
                                VirtualFile finalDir = dir.get();
                                completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
//                                    ProgressIndicator parentIndicator2 = ProgressManager.getInstance().getProgressIndicator();
//                                    parentIndicator2.setIndeterminate(false);
//                                    //                                    parentIndicator = new EmptyProgressIndicator();
////                                    parentIndicator.setModalityProgress(parentIndicator);
//                                    parentIndicator2.setText("Please wait ...");
                                    try {
//                                        ZipUtil.extract(VfsUtil.virtualToIoFile(files.get(0)).toPath(),
//                                                VfsUtil.virtualToIoFile(finalDir).toPath(),
//                                                null);
                                        ZipUtil.extract(VfsUtil.virtualToIoFile(files.get(0)), VfsUtil.virtualToIoFile(finalDir), null);
                                    } catch (IOException e1) {
                                        NotificationHelper.showErrorNotification(null, e1.getMessage());
                                    }
                                }, "Extracting zip file", false, null, null);
                            } catch (Exception e) {
                                NotificationHelper.showErrorNotification(null, e.getMessage());
                            } finally {
                                dir.get().refresh(false, true);
                                if (completed) {
                                    PropertiesComponent.getInstance().setValue(CreateGravProjectWizardStep.LAST_USED_GRAV_HOME, newdirpath);
                                    refreshVersionViewAfterDownload(newdirpath);
                                }
                            }
                        }
                    }

                    @Override
                    public void cancelled() {
                    }
                });
            }
        });
        myDownloadLink.setIcon(AllIcons.Actions.Download);
        // must be place after downloadLink, otherwise downloadLink doesn't work ...
        JTextField textField = new JTextField();
        browseFilesListener = new BrowseFilesListener(textField, "Select Grav 'SDK' Download Folder", "", FileChooserDescriptorFactory.createSingleFileDescriptor());

//        gravDownloadFolderFieldPanel = ModuleWizardStep.createFieldPanel(textField, "", browseFilesListener);
        gravDownloadFolderFieldPanel = new FieldPanel(textField, "", null, browseFilesListener, consumer);
        gravDownloadFolderFieldPanel.getFieldLabel().setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD));
    }

    private void refreshVersionViewAfterDownload(final String newdirpath) {
        setDeterminedGravVersion(GravSdkType.findGravSdkVersion(newdirpath));
        showHint(false);
        gravDownloadFolderFieldPanel.getTextField().setText(newdirpath); // validation will be performed automatically (see GravInstallerGeneratorPeer)
        lblGravDownloadPath.setText(newdirpath);
        this.fireStateChanged();
    }

    private void refreshVersionAction() {
        Outcome<String[]> outcome = DownloadUtil.provideDataWithProgressSynchronously(
                null,
                "Grav versions",
                "Retrieving latest Grav versions ...",
                () -> {
                    List<String> gravVersionReleases = GithubApi.getGravVersionReleases(downloadProps.getProperty("gravReleases"));
                    gotLatestVersions.set(true);
                    return gravVersionReleases.toArray(new String[0]);
                }, () -> IOExceptionDialog.showErrorDialog("Download Error", "Could not retrieve current Grav releases from: '" + GithubApi.GravRepoUrl + "'")
        );

        gravVersions = outcome.get();
        Exception e = outcome.getException();
        if (e != null || gravVersions == null) {
            gravVersions = DEFAULT_GRAV_VERSIONS;
        }
        gravVersionComboBox.setModel(new DefaultComboBoxModel<>(gravVersions));
    }

    @SuppressWarnings("unused")
    public void initRefreshLink() {
        refreshLink = new ActionLink("Refresh Grav versions", new AnAction() {

            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                refreshVersionAction();
            }
        });
        refreshLink.setVisible(false);
    }

    public void showDeterminedVersion(boolean show) {
        lblVersionPrompt.setVisible(show);
        lblVersionDetermined.setVisible(show);
    }

    public void setDeterminedGravVersion(String version) {
        lblVersionDetermined.setText(version);
    }

    public void setDefaultInstallationPath(String path) {
        if ((gravDownloadFolderFieldPanel.getText() == null || gravDownloadFolderFieldPanel.getText().isEmpty()) && path != null) {
            gravDownloadFolderFieldPanel.setText(path);
            String gravSdkVersion = GravSdkType.findGravSdkVersion(path);
            setDeterminedGravVersion(gravSdkVersion);
            showDeterminedVersion(true);
        }
    }

    public String getSelectedGravVersion() {
        return (String) gravVersionComboBox.getSelectedItem();
    }

    public FieldPanel getGravDownloadFolderFieldPanel() {
        return gravDownloadFolderFieldPanel;
    }

    /**
     * Dependent on the option (Select or Download)
     *
     * @return the path to the grav directory, or empty string
     */
    public String getGravFinalInstallationDirectory() {
        if (wizardOption == WizardOption.SELECT) {
            return gravDownloadFolderFieldPanel.getText();
        } else if (wizardOption == WizardOption.DOWNLOAD) {
            return lblGravDownloadPath.getText();
        }
        return "";
    }

    public void showHint(boolean flag) {
        if (wizardOption == WizardOption.SELECT) {
            lblHint.setVisible(flag);
        }
        if (!flag && wizardOption == WizardOption.DOWNLOAD) {
            lblHint.setVisible(false);
        }
        showDeterminedVersion(!flag);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JRadioButton) {
            if (e.getActionCommand().equals("selectGrav")) {
                wizardOption = WizardOption.SELECT;
                enablePanel(panelDownloadGrav, false);
                enablePanel(panelSelectGrav, true);
            } else if (e.getActionCommand().equals("downloadGrav")) {
                wizardOption = WizardOption.DOWNLOAD;
                enablePanel(panelDownloadGrav, true);
                enablePanel(panelSelectGrav, false);
            }
        }

        if (e.getSource() instanceof JButton) {
            if (e.getActionCommand().equals("refreshGrav")) {
                refreshVersionAction();
            }
        }
    }

    private void enablePanel(JPanel panel, boolean enable) {
        Component[] comps = panel.getComponents();
        for (Component comp : comps) {
            comp.setEnabled(enable);
        }
    }

    @SuppressWarnings("unused")
    public WizardOption getWizardOption() {
        return wizardOption;
    }
}


text:
package nl.topicus.jdbc.test.integration.ddl;

import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;
import org.junit.Assert;
import nl.topicus.jdbc.test.integration.TestUtil;

/**
 * Class for testing Table DDL statements, such as CREATE TABLE, ALTER TABLE, DROP TABLE.
 *
 * @author loite
 *
 */
public class TableDDLTester {
  private static final Logger log = Logger.getLogger(TableDDLTester.class.getName());

  private Connection connection;

  public TableDDLTester(Connection connection) {
    this.connection = connection;
  }

  public void runCreateTests() throws IOException, URISyntaxException, SQLException {
    runCreateTableTests();
    runAlterTableTests();
  }

  public void runDropTests() {
    runDropTableTests();
  }

  private void runCreateTableTests() throws IOException, URISyntaxException, SQLException {
    log.info("Starting CreateTableTests");
    runCreateTableTest("TEST", "CreateTableTest.sql");
    log.info("Starting CreateTableIfNotExistsTests");
    runCreateTableTest("TEST", "CreateTableIfNotExistsTest.sql");
    log.info("Verifying primary keys of parent table");
    verifyPrimaryKey("TEST", "ID");
    runCreateTableTest("TESTCHILD", "CreateTableTestChild.sql");
    log.info("Verifying primary keys of child table");
    verifyPrimaryKey("TESTCHILD", "ID, CHILDID");
    log.info("Creating indices");
    runCreateIndexTests();

    log.info("Starting CreateQuotedTableTest");
    runCreateTableTest("TEST_QUOTED", "CreateQuotedTableTest.sql");
    log.info("Starting CreateTableWithArray");
    runCreateTableTest("TEST_WITH_ARRAY", "CreateTableWithArray.sql");

    log.info("Starting CreateAsyncTableTest");
    runCreateTableTest("ASYNCTEST", "CreateTableAsyncTest.sql");
    for (int expectedCount = 1; expectedCount >= 0; expectedCount--) {
      try (ResultSet rs = connection.createStatement().executeQuery("SHOW_DDL_OPERATIONS")) {
        int count = 0;
        while (rs.next()) {
          count++;
          Assert.assertTrue(rs.getBoolean("DONE"));
        }
        Assert.assertEquals("Number of running operations", expectedCount, count);
        connection.createStatement().executeUpdate("CLEAN_DDL_OPERATIONS");
      }
    }

    log.info("Finished CreateTableTests");
  }

  private void runCreateTableTest(String tableName, String fileName)
      throws IOException, URISyntaxException, SQLException {
    executeDdl(fileName);
    verifyTableExists(tableName);
  }

  private void runCreateIndexTests() throws IOException, URISyntaxException, SQLException {
    // CREATE UNIQUE INDEX takes forever, and also hinders bulk insert tests
    // executeDdl("CreateIndexTest.sql");
    executeDdl("CreateIndexTestChild.sql");
    executeDdl("CreateIndexIfNotExistsTestChild.sql");
  }

  private void verifyTableExists(String table) throws SQLException {
    String tableFound = "";
    try (ResultSet rs = connection.getMetaData().getTables("", "", table, null)) {
      int count = 0;
      while (rs.next()) {
        tableFound = rs.getString("TABLE_NAME");
        count++;
      }
      if (count != 1 || !table.equalsIgnoreCase(tableFound))
        throw new AssertionError("Table " + table + " not found");
    }
  }

  private void verifyPrimaryKey(String table, String expectedColumns) throws SQLException {
    String colsFound = "";
    try (ResultSet rs = connection.getMetaData().getPrimaryKeys("", "", table)) {
      while (rs.next()) {
        if (!colsFound.equals(""))
          colsFound = colsFound + ", ";
        colsFound = colsFound + rs.getString("COLUMN_NAME");
      }
      if (!expectedColumns.equalsIgnoreCase(colsFound))
        throw new AssertionError(
            "Primary key columns expected: " + expectedColumns + ", found: " + colsFound);
    }
  }

  private void runAlterTableTests() throws IOException, URISyntaxException, SQLException {
    log.info("Starting AlterTableTests");
    executeDdl("AlterTableTestChildAddColumn.sql");
    verifyColumn("TESTCHILD", "NEW_COLUMN", true, "STRING(50)");

    // This statement will fail as it is not allowed to change the type from
    // STRING(50) to INT64
    executeDdl("AlterTableTestChildAlterColumn.sql", true);
    verifyColumn("TESTCHILD", "NEW_COLUMN", true, "STRING(50)");

    executeDdl("AlterTableTestChildAlterColumn2.sql");
    verifyColumn("TESTCHILD", "NEW_COLUMN", true, "STRING(100)");

    executeDdl("AlterTableTestChildDropColumn.sql");
    verifyColumn("TESTCHILD", "NEW_COLUMN", false, "");
    log.info("Finished AlterTableTests");
  }

  private void verifyColumn(String table, String column, boolean mustExist, String type)
      throws SQLException {
    String colFound = "";
    String typeFound = "";
    ResultSet rs = connection.getMetaData().getColumns("", "", table, column);
    int count = 0;
    while (rs.next()) {
      colFound = rs.getString("COLUMN_NAME");
      typeFound = rs.getString("TYPE_NAME");
      count++;
    }
    if (mustExist) {
      if (count != 1 || !column.equalsIgnoreCase(colFound))
        throw new AssertionError("Column " + column + " not found");
      if (!type.equalsIgnoreCase(typeFound))
        throw new AssertionError(
            "Column " + column + " has type " + typeFound + ", expected was " + type);
    } else {
      if (count != 0)
        throw new AssertionError("Column " + column + " found, expected was no column");
    }
  }

  private void runDropTableTests() {}

  private void executeDdl(String file) throws IOException, URISyntaxException, SQLException {
    executeDdl(file, false);
  }

  private void executeDdl(String file, boolean expectsError)
      throws IOException, URISyntaxException, SQLException {
    String[] sqls = TestUtil.getMultipleStatements(getClass(), file);
    try {
      for (String sql : sqls)
        connection.createStatement().execute(sql);
    } catch (SQLException e) {
      if (!expectsError)
        throw e;
      return;
    }
    if (expectsError)
      throw new SQLException("Expected exception, but statement was succesfull");
  }

}


text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 *
 * @internal
 */
final class PhpdocVarWithoutNameFixerTest extends AbstractFixerTestBase
{
    public function testFixVar()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var string Hello!
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var string $foo Hello!
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixType()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var int|null
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var int|null $bar
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var Foo\Bar This is a variable.
     */

EOF;

        $this->makeTest($expected);
    }

    public function testSingleLine()
    {
        $expected = <<<'EOF'
<?php
    /** @var Foo\Bar $bar */
    $bar;
EOF;

        $this->makeTest($expected);
    }

    public function testEmpty()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }
}


text:
<?php

namespace Google\AdsApi\Dfp\v201611;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class Content
{

    /**
     * @var int $id
     */
    protected $id = null;

    /**
     * @var string $name
     */
    protected $name = null;

    /**
     * @var string $status
     */
    protected $status = null;

    /**
     * @var string $statusDefinedBy
     */
    protected $statusDefinedBy = null;

    /**
     * @var \Google\AdsApi\Dfp\v201611\DateTime $importDateTime
     */
    protected $importDateTime = null;

    /**
     * @var \Google\AdsApi\Dfp\v201611\DateTime $lastModifiedDateTime
     */
    protected $lastModifiedDateTime = null;

    /**
     * @var long[] $userDefinedCustomTargetingValueIds
     */
    protected $userDefinedCustomTargetingValueIds = null;

    /**
     * @var long[] $mappingRuleDefinedCustomTargetingValueIds
     */
    protected $mappingRuleDefinedCustomTargetingValueIds = null;

    /**
     * @var \Google\AdsApi\Dfp\v201611\CmsContent[] $cmsSources
     */
    protected $cmsSources = null;

    /**
     * @param int $id
     * @param string $name
     * @param string $status
     * @param string $statusDefinedBy
     * @param \Google\AdsApi\Dfp\v201611\DateTime $importDateTime
     * @param \Google\AdsApi\Dfp\v201611\DateTime $lastModifiedDateTime
     * @param long[] $userDefinedCustomTargetingValueIds
     * @param long[] $mappingRuleDefinedCustomTargetingValueIds
     * @param \Google\AdsApi\Dfp\v201611\CmsContent[] $cmsSources
     */
    public function __construct($id = null, $name = null, $status = null, $statusDefinedBy = null, $importDateTime = null, $lastModifiedDateTime = null, array $userDefinedCustomTargetingValueIds = null, array $mappingRuleDefinedCustomTargetingValueIds = null, array $cmsSources = null)
    {
      $this->id = $id;
      $this->name = $name;
      $this->status = $status;
      $this->statusDefinedBy = $statusDefinedBy;
      $this->importDateTime = $importDateTime;
      $this->lastModifiedDateTime = $lastModifiedDateTime;
      $this->userDefinedCustomTargetingValueIds = $userDefinedCustomTargetingValueIds;
      $this->mappingRuleDefinedCustomTargetingValueIds = $mappingRuleDefinedCustomTargetingValueIds;
      $this->cmsSources = $cmsSources;
    }

    /**
     * @return int
     */
    public function getId()
    {
      return $this->id;
    }

    /**
     * @param int $id
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setId($id)
    {
      $this->id = $id;
      return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
      return $this->name;
    }

    /**
     * @param string $name
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setName($name)
    {
      $this->name = $name;
      return $this;
    }

    /**
     * @return string
     */
    public function getStatus()
    {
      return $this->status;
    }

    /**
     * @param string $status
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setStatus($status)
    {
      $this->status = $status;
      return $this;
    }

    /**
     * @return string
     */
    public function getStatusDefinedBy()
    {
      return $this->statusDefinedBy;
    }

    /**
     * @param string $statusDefinedBy
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setStatusDefinedBy($statusDefinedBy)
    {
      $this->statusDefinedBy = $statusDefinedBy;
      return $this;
    }

    /**
     * @return \Google\AdsApi\Dfp\v201611\DateTime
     */
    public function getImportDateTime()
    {
      return $this->importDateTime;
    }

    /**
     * @param \Google\AdsApi\Dfp\v201611\DateTime $importDateTime
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setImportDateTime($importDateTime)
    {
      $this->importDateTime = $importDateTime;
      return $this;
    }

    /**
     * @return \Google\AdsApi\Dfp\v201611\DateTime
     */
    public function getLastModifiedDateTime()
    {
      return $this->lastModifiedDateTime;
    }

    /**
     * @param \Google\AdsApi\Dfp\v201611\DateTime $lastModifiedDateTime
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setLastModifiedDateTime($lastModifiedDateTime)
    {
      $this->lastModifiedDateTime = $lastModifiedDateTime;
      return $this;
    }

    /**
     * @return long[]
     */
    public function getUserDefinedCustomTargetingValueIds()
    {
      return $this->userDefinedCustomTargetingValueIds;
    }

    /**
     * @param long[] $userDefinedCustomTargetingValueIds
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setUserDefinedCustomTargetingValueIds(array $userDefinedCustomTargetingValueIds)
    {
      $this->userDefinedCustomTargetingValueIds = $userDefinedCustomTargetingValueIds;
      return $this;
    }

    /**
     * @return long[]
     */
    public function getMappingRuleDefinedCustomTargetingValueIds()
    {
      return $this->mappingRuleDefinedCustomTargetingValueIds;
    }

    /**
     * @param long[] $mappingRuleDefinedCustomTargetingValueIds
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setMappingRuleDefinedCustomTargetingValueIds(array $mappingRuleDefinedCustomTargetingValueIds)
    {
      $this->mappingRuleDefinedCustomTargetingValueIds = $mappingRuleDefinedCustomTargetingValueIds;
      return $this;
    }

    /**
     * @return \Google\AdsApi\Dfp\v201611\CmsContent[]
     */
    public function getCmsSources()
    {
      return $this->cmsSources;
    }

    /**
     * @param \Google\AdsApi\Dfp\v201611\CmsContent[] $cmsSources
     * @return \Google\AdsApi\Dfp\v201611\Content
     */
    public function setCmsSources(array $cmsSources)
    {
      $this->cmsSources = $cmsSources;
      return $this;
    }

}


text:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* Elemental concept of the packages on the projet
*
**************************************************
* A package must be on the way "#sec:character"	 |
* "sec" is the number of the packages 		     |
* ":" separatoro								 |
* "character" content of the packages 			 |
**************************************************
*/

public class Package{
	private String pack;
	private char content;
	int sec;
	Pattern p = Pattern.compile("(-?[0-9]+)");
	/*
	* basic constructor class
	* @param sec number of the package
	* @param content of the package
	*/
	public Package(int sec, char content){
		pack = "#"  + sec + ":" + content;
		this.sec = sec;
		this.content = content;
	}
	public Package(String pack){
		this.pack = pack;
	}
	public void setPackage(String pack){
		this.pack = pack;
	}
	public String getPackage(){
		return pack;
	}

	public char getPackageContent(){
		return pack.charAt((pack.length() - 1));
		//return this.content;
	}

	public int getPackageSec(){
		//return pack.substring(1,2);
		Matcher m = p.matcher(pack);
		int ret = 0;
		if (m.find()) {
			System.out.println(m.group(0));
    		ret = Integer.parseInt(m.group(0));

		}

		return ret;
	}
	public void setSec(int sec){
		this.sec = sec;
	}

}


text:
package android.taobao.atlas.hack;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflect {
    public static boolean sIsReflectAvailable;

    static {
        sIsReflectAvailable = true;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static java.lang.reflect.Method getMethod(java.lang.Class<?> r2, java.lang.String r3, java.lang.Class<?>... r4) {
        /*
        r0 = r2.getDeclaredMethod(r3, r4);	 Catch:{ SecurityException -> 0x0009, NoSuchMethodException -> 0x000f }
        r1 = 1;
        r0.setAccessible(r1);	 Catch:{ SecurityException -> 0x0009, NoSuchMethodException -> 0x000f }
    L_0x0008:
        return r0;
    L_0x0009:
        r0 = move-exception;
        r0.printStackTrace();
    L_0x000d:
        r0 = 0;
        goto L_0x0008;
    L_0x000f:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x000d;
        */
        throw new UnsupportedOperationException("Method not decompiled: android.taobao.atlas.hack.Reflect.getMethod(java.lang.Class, java.lang.String, java.lang.Class[]):java.lang.reflect.Method");
    }

    public static Object invokeMethod(Method method, Object obj, Object... objArr) {
        try {
            method.setAccessible(true);
            return method.invoke(obj, objArr);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalAccessException e2) {
            e2.printStackTrace();
            return null;
        } catch (InvocationTargetException e3) {
            e3.printStackTrace();
            return null;
        }
    }

    public static Object fieldGet(Class<?> cls, Object obj, String str) {
        try {
            Field declaredField = cls.getDeclaredField(str);
            declaredField.setAccessible(true);
            return declaredField.get(obj);
        } catch (SecurityException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchFieldException e2) {
            e2.printStackTrace();
            return null;
        } catch (IllegalArgumentException e3) {
            e3.printStackTrace();
            return null;
        } catch (IllegalAccessException e4) {
            e4.printStackTrace();
            return null;
        }
    }

    public static Object fieldGet(Field field, Object obj) {
        try {
            field.setAccessible(true);
            return field.get(obj);
        } catch (SecurityException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
            return null;
        } catch (IllegalAccessException e3) {
            e3.printStackTrace();
            return null;
        }
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static boolean fieldSet(java.lang.reflect.Field r2, java.lang.Object r3, java.lang.Object r4) {
        /*
        r0 = 1;
        r1 = 1;
        r2.setAccessible(r1);	 Catch:{ SecurityException -> 0x0009, IllegalArgumentException -> 0x000f, IllegalAccessException -> 0x0014 }
        r2.set(r3, r4);	 Catch:{ SecurityException -> 0x0009, IllegalArgumentException -> 0x000f, IllegalAccessException -> 0x0014 }
    L_0x0008:
        return r0;
    L_0x0009:
        r0 = move-exception;
        r0.printStackTrace();
    L_0x000d:
        r0 = 0;
        goto L_0x0008;
    L_0x000f:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x000d;
    L_0x0014:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x000d;
        */
        throw new UnsupportedOperationException("Method not decompiled: android.taobao.atlas.hack.Reflect.fieldSet(java.lang.reflect.Field, java.lang.Object, java.lang.Object):boolean");
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static boolean fieldSet(java.lang.Class<?> r3, java.lang.Object r4, java.lang.String r5, java.lang.Object r6) {
        /*
        r0 = 1;
        r1 = r3.getDeclaredField(r5);	 Catch:{ SecurityException -> 0x000d, NoSuchFieldException -> 0x0013, IllegalArgumentException -> 0x0018, IllegalAccessException -> 0x001d }
        r2 = 1;
        r1.setAccessible(r2);	 Catch:{ SecurityException -> 0x000d, NoSuchFieldException -> 0x0013, IllegalArgumentException -> 0x0018, IllegalAccessException -> 0x001d }
        r1.set(r4, r6);	 Catch:{ SecurityException -> 0x000d, NoSuchFieldException -> 0x0013, IllegalArgumentException -> 0x0018, IllegalAccessException -> 0x001d }
    L_0x000c:
        return r0;
    L_0x000d:
        r0 = move-exception;
        r0.printStackTrace();
    L_0x0011:
        r0 = 0;
        goto L_0x000c;
    L_0x0013:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x0011;
    L_0x0018:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x0011;
    L_0x001d:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x0011;
        */
        throw new UnsupportedOperationException("Method not decompiled: android.taobao.atlas.hack.Reflect.fieldSet(java.lang.Class, java.lang.Object, java.lang.String, java.lang.Object):boolean");
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public static java.lang.reflect.Field getField(java.lang.Class<?> r2, java.lang.String r3) {
        /*
        r0 = r2.getDeclaredField(r3);	 Catch:{ SecurityException -> 0x0009, NoSuchFieldException -> 0x000f }
        r1 = 1;
        r0.setAccessible(r1);	 Catch:{ SecurityException -> 0x0009, NoSuchFieldException -> 0x000f }
    L_0x0008:
        return r0;
    L_0x0009:
        r0 = move-exception;
        r0.printStackTrace();
    L_0x000d:
        r0 = 0;
        goto L_0x0008;
    L_0x000f:
        r0 = move-exception;
        r0.printStackTrace();
        goto L_0x000d;
        */
        throw new UnsupportedOperationException("Method not decompiled: android.taobao.atlas.hack.Reflect.getField(java.lang.Class, java.lang.String):java.lang.reflect.Field");
    }
}


text:
package org.batfish.datamodel.flow;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;

import com.google.common.collect.ImmutableSortedSet;
import com.google.common.testing.EqualsTester;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.datamodel.FlowDiff;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.flow.TransformationStep.TransformationStepDetail;
import org.batfish.datamodel.flow.TransformationStep.TransformationType;
import org.batfish.datamodel.transformation.IpField;
import org.junit.Test;

/** Tests of {@link TransformationStep} */
public class TransformationStepTest {
  @Test
  public void testJsonSerialization() {
    TransformationStep step =
        new TransformationStep(
            new TransformationStepDetail(
                TransformationType.DEST_NAT,
                ImmutableSortedSet.of(
                    FlowDiff.flowDiff(IpField.DESTINATION, Ip.ZERO, Ip.FIRST_CLASS_A_PRIVATE_IP))),
            StepAction.TRANSFORMED);
    Step<?> genericClonedStep = BatfishObjectMapper.clone(step, Step.class);
    assertThat(genericClonedStep, instanceOf(TransformationStep.class));
    TransformationStep clonedStep = (TransformationStep) genericClonedStep;
    assertThat(clonedStep, equalTo(step));
  }

  @Test
  public void testEquals() {
    new EqualsTester()
        .addEqualityGroup(new Object())
        .addEqualityGroup(
            new TransformationStep(
                new TransformationStepDetail(
                    TransformationType.DEST_NAT,
                    ImmutableSortedSet.of(
                        FlowDiff.flowDiff(
                            IpField.DESTINATION, Ip.ZERO, Ip.FIRST_CLASS_A_PRIVATE_IP))),
                StepAction.TRANSFORMED),
            new TransformationStep(
                new TransformationStepDetail(
                    TransformationType.DEST_NAT,
                    ImmutableSortedSet.of(
                        FlowDiff.flowDiff(
                            IpField.DESTINATION, Ip.ZERO, Ip.FIRST_CLASS_A_PRIVATE_IP))),
                StepAction.TRANSFORMED))
        .addEqualityGroup(
            new TransformationStep(
                new TransformationStepDetail(
                    TransformationType.SOURCE_NAT,
                    ImmutableSortedSet.of(
                        FlowDiff.flowDiff(
                            IpField.DESTINATION, Ip.ZERO, Ip.FIRST_CLASS_A_PRIVATE_IP))),
                StepAction.TRANSFORMED))
        .addEqualityGroup(
            new TransformationStep(
                new TransformationStepDetail(
                    TransformationType.SOURCE_NAT,
                    ImmutableSortedSet.of(
                        FlowDiff.flowDiff(IpField.SOURCE, Ip.ZERO, Ip.FIRST_CLASS_A_PRIVATE_IP))),
                StepAction.TRANSFORMED))
        .addEqualityGroup(
            new TransformationStep(
                new TransformationStepDetail(
                    TransformationType.SOURCE_NAT, ImmutableSortedSet.of()),
                StepAction.PERMITTED))
        .testEquals();
  }
}


text:
package org.intracer.wmua.cmd

import db.scalikejdbc.Round

case class SetCurrentRound(contestId: Long, prevRound: Option[Round], round: Round) {

  def apply(): Unit = {
    println(s"Setting current round ${prevRound.fold("")(r => s"from ${r.getId}")} to ${round.getId}")

    prevRound.foreach(r => Round.setActive(r.getId, active = false))

    Round.setActive(round.getId, active = round.active)
  }

}


text:
package com.github.ben.zhihudaily.mvpbase;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.github.ben.zhihudaily.ui.base.BaseFragment;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.lang.reflect.ParameterizedType;

/**
 * Created on 17/5/3.
 *
 * @author Ben
 */

public abstract class MVPBaseFragment<V extends BaseView, T extends BasePresentImpl<V>> extends BaseFragment implements BaseView {
    protected T mPresenter;

    @SuppressWarnings("unchecked")
    @Nullable
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        mPresenter = getInstance(this, 1);
        mPresenter.attachView((V) this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroyView();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @SuppressWarnings("unchecked")
    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass().getGenericSuperclass())).getActualTypeArguments()[i]).newInstance();
        } catch (InstantiationException | IllegalAccessException | java.lang.InstantiationException | ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
<?php
/**
 * Author: Maxim
 * Date: 19/06/2014
 * Time: 14:17
 * Property of MCSuite
 */
namespace Maxim\CMSBundle\EventListener;

use Oneup\UploaderBundle\Event\PostPersistEvent;

class UploadListener
{
    public function __construct($doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function onUpload(PostPersistEvent $event)
    {
        $request = $event->getRequest();
        $gallery = $request->get('gallery');
    }
}


text:
package pl.srw.mfvp;

/**
 * Delegates view state events to associated presenter
 * @param <V> view type
 */
public class PresenterHandlingDelegate<V> {

    protected final V view;
    private final MvpPresenter<V>[] presenters;

    private boolean isViewBound;

    PresenterHandlingDelegate(V view) {
        this(view, new MvpPresenter[0]);
    }

    PresenterHandlingDelegate(V view, MvpPresenter<V>... presenter) {
        this.view = view;
        this.presenters = presenter;
    }

    void onReady() {
        for (int i = 0; i < presenters.length; i++) {
            presenters[i].bind(view);
        }
        isViewBound = true;
    }

    void onUnavailable() {
        for (int i = 0; i < presenters.length; i++) {
            presenters[i].unbind(view);
        }
        isViewBound = false;
    }

    void onFinish() {
        for (int i = 0; i < presenters.length; i++) {
            presenters[i].onFinish();
        }
    }

    boolean isViewBound() {
        return isViewBound;
    }
}


text:
#include "grove_example_gen.h"

void rpc_server_register_resources()
{
    uint8_t arg_types[MAX_INPUT_ARG_LEN];

    //Grove_Example1
    GroveExample *Grove_Example1 = new GroveExample(P0_27,P0_28);
    memset(arg_types, TYPE_NONE, MAX_INPUT_ARG_LEN);
    rpc_server_register_method("Grove_Example1", "temp", METHOD_READ, __grove_example_read_temp, Grove_Example1, arg_types);
    rpc_server_register_method("Grove_Example1", "humidity", METHOD_READ, __grove_example_read_humidity, Grove_Example1, arg_types);
    rpc_server_register_method("Grove_Example1", "acc", METHOD_READ, __grove_example_read_acc, Grove_Example1, arg_types);
    rpc_server_register_method("Grove_Example1", "uint8_value", METHOD_READ, __grove_example_read_uint8_value, Grove_Example1, arg_types);
    rpc_server_register_method("Grove_Example1", "compass", METHOD_READ, __grove_example_read_compass, Grove_Example1, arg_types);
    memset(arg_types, TYPE_NONE, MAX_INPUT_ARG_LEN);
    arg_types[0] = TYPE_INT;
    arg_types[1] = TYPE_FLOAT;
    arg_types[2] = TYPE_INT8;
    rpc_server_register_method("Grove_Example1", "multi_value", METHOD_WRITE, __grove_example_write_multi_value, Grove_Example1, arg_types);
    memset(arg_types, TYPE_NONE, MAX_INPUT_ARG_LEN);
    arg_types[0] = TYPE_UINT8;
    rpc_server_register_method("Grove_Example1", "acc_mode", METHOD_WRITE, __grove_example_write_acc_mode, Grove_Example1, arg_types);
    memset(arg_types, TYPE_NONE, MAX_INPUT_ARG_LEN);
    arg_types[0] = TYPE_FLOAT;
    rpc_server_register_method("Grove_Example1", "float_value", METHOD_WRITE, __grove_example_write_float_value, Grove_Example1, arg_types);

    Grove_Example1->attach_event_handler(rpc_server_event_report);
}


text:
/**
 * @private
 */
Ext.define('Ext.selection.DataViewModel', {
    extend: 'Ext.selection.Model',

    alias: 'selection.dataviewmodel',

    requires: ['Ext.util.KeyNav'],

    deselectOnContainerClick: true,

    /**
     * @cfg {Boolean} [enableKeyNav=true]
     *
     * @deprecated 5.1.0 Keyboard navigation is a function of the view's {@link Ext.view.NavigationModel navigation model},
     * and is enabled for accessibilty purposes.
     */

    /**
     * @event beforedeselect
     * Fired before a record is deselected. If any listener returns false, the
     * deselection is cancelled.
     * @param {Ext.selection.DataViewModel} this
     * @param {Ext.data.Model} record The deselected record.
     * @param {Number} The index within the store of the deselected record.
     */

    /**
     * @event beforeselect
     * Fired before a record is selected. If any listener returns false, the
     * selection is cancelled.
     * @param {Ext.selection.DataViewModel} this
     * @param {Ext.data.Model} record The selected record.
     * @param {Number} The index within the store of the selected record.
     */

    /**
     * @event deselect
     * Fired after a record is deselected
     * @param {Ext.selection.DataViewModel} this
     * @param  {Ext.data.Model} record The deselected record
     */

    /**
     * @event select
     * Fired after a record is selected
     * @param {Ext.selection.DataViewModel} this
     * @param  {Ext.data.Model} record The selected record.
     * @param {Number} The index within the store of the selected record.
     */

    bindComponent: function(view) {
        var me = this,
            viewListeners;

        if (me.view !== view) {
            if (me.view) {
                me.navigationModel = null;
                Ext.destroy(me.viewListeners, me.navigationListeners);
            }
            me.view = view;
            if (view) {
                viewListeners = me.getViewListeners();
                viewListeners.scope = me;
                viewListeners.destroyable = true;
                me.navigationModel = view.getNavigationModel();
                me.viewListeners = view.on(viewListeners);
                me.navigationListeners = me.navigationModel.on({
                    navigate: me.onNavigate,
                    scope: me,
                    destroyable: true
                });
            }
        }
    },

    getViewListeners: function() {
        var me = this,
            eventListeners = {};

        eventListeners[me.view.triggerCtEvent] = me.onContainerClick;
        return eventListeners;
    },

    onUpdate: function(record){
        var view = this.view;
        if (view && this.isSelected(record)) {
            view.onItemSelect(record);
        }
    },

    onContainerClick: function() {
        if (this.deselectOnContainerClick) {
            this.deselectAll();
        }
    },

    // Allow the DataView to update the ui
    onSelectChange: function(record, isSelected, suppressEvent, commitFn) {
        var me = this,
            view = me.view,
            eventName = isSelected ? 'select' : 'deselect',
            recordIndex = me.store.indexOf(record);

        if ((suppressEvent || me.fireEvent('before' + eventName, me, record, recordIndex)) !== false &&
                commitFn() !== false) {

            if (view) {
                if (isSelected) {
                    view.onItemSelect(record);
                } else {
                    view.onItemDeselect(record);
                }
            }

            if (!suppressEvent) {
                me.fireEvent(eventName, me, record, recordIndex);
            }
        }
    },

    destroy: function() {
        this.bindComponent();
        Ext.destroy(this.keyNav);
        this.callParent();
    }
});


text:
. ../settings.ini

mkdir -p /tmp/taxhub
sudo chown -R "$(id -u)" /tmp/taxhub

LOG_DIR="../log/"

mkdir -p $LOG_DIR

echo "Import des données de taxref v12"

echo "Import des données de taxref v12" > $LOG_DIR/update_taxref_v12.log
array=( TAXREF_INPN_v12.zip ESPECES_REGLEMENTEES_v11.zip )
for i in "${array[@]}"
do
    if [ ! -f '/tmp/taxhub/'$i ]
    then
        wget http://geonature.fr/data/inpn/taxonomie/$i -P /tmp/taxhub
    else
        echo $i exists
    fi
    unzip -o /tmp/taxhub/$i -d /tmp/taxhub &>> $LOG_DIR/update_taxref_v12.log
done

echo "Import taxref v12"
# sudo -n -u postgres -s psql -d $geonature_db_name -c "DROP TABLE taxonomie.import_taxref"
export PGPASSWORD=$geonature_user_pg_pass;psql -h $db_host -U $geonature_pg_user -d $geonature_db_name  -f create_structure.sql   &>> $LOG_DIR/update_taxref_v12.log
sudo -n -u postgres -s psql -d $geonature_db_name -f import_taxref_data.sql
export PGPASSWORD=$geonature_user_pg_pass;psql -h $db_host -U $geonature_pg_user -d $geonature_db_name  -f migrate_taxref_data.sql   &>> $LOG_DIR/update_taxref_v12.log


text:
import com.afk.calmera.network.Message;

public interface ProcessType {
	Message process(Message msg);
}


text:
<bill session="111" type="h" number="1093" updated="2009-03-07T11:57:14-05:00">
	<status><introduced date="1234501200" datetime="2009-02-13"/></status>

	<introduced date="1234501200" datetime="2009-02-13"/>
	<titles>
		<title type="official" as="introduced">To amend title II of the Social Security Act to provide for an increase in the maximum level of fees authorized to be charged by representatives with respect to claims of entitlement to past-due benefits and to require cost-of-living adjustments to such level of authorized fees.</title>
	</titles>
	<sponsor id="400240"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1234501200" datetime="2009-02-13"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>
		<committee name="House Ways and Means" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	2/13/2009--Introduced.<br/>Amends title II (Old Age, Survivors and Disability Insurance) (OASDI) of the Social Security Act with respect to fees of persons representating claimants prevailing before the Commissioner of Social Security in a claim of entitlement to past-due benefits. Increases the maximum level of fees authorized to be charged by such representatives with respect to such claims. Requires the Commissioner to make annual cost-of-living adjustments to such fee level.
	</summary>
</bill>


text:
extern crate gunship;

use gunship::engine::EngineBuilder;

fn main() {
    let mut builder = EngineBuilder::new();
    builder.max_workers(1);
    builder.build(|| {});
}


text:
package service

func Hello() string {
         return "Xiao Sicong"
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Framework.Infrastructure;
using Framework.Models;

namespace Framework.Web.Api
{
    using Framework.FileSystem;

    public class FileSystemStreamProvider : MultipartStreamProvider
    {
        private readonly IVirtualFileSystem fileSystem;

        private readonly IVirtualFolder folderItem;

        private readonly int bufferSize;

        private readonly Collection<FileDataModel> files = new Collection<FileDataModel>();

        public FileSystemStreamProvider(IVirtualFileSystem fileSystem, IVirtualFolder folderItem, int bufferSize = 4096)
        {
            this.fileSystem = fileSystem;
            this.folderItem = folderItem;
            this.bufferSize = bufferSize;
        }

        public virtual string GetFileName(HttpContentHeaders headers)
        {
            string fileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
            return !string.IsNullOrWhiteSpace(fileName)
                       ? Guid.NewGuid().ToStringValue() + Path.GetExtension(fileName)
                       : Guid.NewGuid().ToStringValue() + ".data";
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            string fileName = this.GetFileName(headers);

            var fileItem = fileSystem.CreateFile(this.FolderItem, fileName, Stream.Null);
            this.Files.Add(new FileDataModel(fileItem.Name, fileItem.RelativePath, fileItem.WebUrl));

            return fileSystem.WriteFileAsync(fileItem, this.BufferSize);
        }

        /// Gets the FolderItem where the content of MIME multipart body parts are written to.
        /// <returns>The FolderItem where the content of MIME multipart body parts are written to.</returns>
        protected IVirtualFolder FolderItem
        {
            get
            {
                return this.folderItem;
            }
        }

        /// Gets the fileS.
        /// <returns>The file data.</returns>
        public ICollection<FileDataModel> Files
        {
            get
            {
                return this.files;
            }
        }

        /// Gets or sets the number of bytes buffered for writes to the file.
        /// <returns>The number of bytes buffered for writes to the file.</returns>
        protected int BufferSize
        {
            get
            {
                return this.bufferSize;
            }
        }
    }
}