text:
ACCEPTED

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

#### Published in
Memoirs of the Cornell University Agricultural Experimental Station 6: 161 (1915)

#### Original name
Fusarium diversisporum Sherb., 1915

### Remarks
null


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/switchMap';
import { AlertService, AuthService, FormValidationService, LoaderService } from '../../shared/services';
import { PetsService, CitiesService, PetStatusesService, BreedsService, SpeciesService } from '../services';
import { Pet, Breed, Specie, PetStatus, City } from '../models';
import { MatchValidatorDirective, matchValidator } from '../../shared/validators';
import { GeneralConstants, BgConstants } from '../../shared/constants';

@Component({
  selector: 'app-pet-create',
  templateUrl: './pet-create.component.html',
  styleUrls: ['./pet-create.component.css']
})
export class PetCreateComponent implements OnInit, OnDestroy {
  public loading = false;
  private petFormSubscription: Subscription;
  private petForm: FormGroup;
  private validationMessages = BgConstants.petCreateValidationMessages;
  private pet: Pet;
  private petId: number;
  private currentUsername: string;
  public breeds: Breed[];
  public species: Specie[];
  public petStatuses: PetStatus[];
  public cities: City[];
  public petGenderOptions: any[] = BgConstants.petGenderOptions;

  private formErrors = {
    'name': '',
    'description': '',
    'address': '',
    'imageUrl': '',
    'specieId': '',
    'breedId': '',
    'petStatusId': '',
    'cityId': '',
    'petGender': ''
  };

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private authService: AuthService,
    private alertService: AlertService,
    private breedsService: BreedsService,
    private speciesService: SpeciesService,
    private petsService: PetsService,
    private petStatusesService: PetStatusesService,
    private citiesService: CitiesService,
    private formBuilder: FormBuilder,
    private formValidationService: FormValidationService,
    private loaderService: LoaderService,
  ) { }

  ngOnInit() {
    this.pet = new Pet();
    this.currentUsername = this.authService.getLoggedInUsername();
    this.loaderService.toggleLoader(true);
    this.loading = true;

    this.route.params
      .first()
      .subscribe((params: Params) => this.petId = (+params['id']));

    this.speciesService.getAll().first().subscribe(species => this.species = species);
    this.petStatusesService.getAll().first().subscribe(statuses => this.petStatuses = statuses);
    this.citiesService.getAll().first().subscribe(cities => this.cities = cities);

    if (this.petId) {
      // Edit mode
      this.petsService.getPet(this.petId)
        .first()
        .subscribe(
        pet => {
          // Unauthorized attempt to modify pet not owned by the logged in user
          if (pet.id && pet.ownerUserName !== this.currentUsername) {
            this.alertService.error(BgConstants.unathorizedMessage, true);
            this.router.navigate([`/pet`, this.petId]);
          }

          this.pet = pet;
          this.loaderService.toggleLoader(false);
          this.loading = false;

          if (this.pet && this.pet.specieId) {
            this.breedsService.getBySpecieId(this.pet.specieId).first().subscribe(breeds => this.breeds = breeds);
          }

          this.buildForm();
        },
        error => {
          this.loaderService.toggleLoader(false);
          this.loading = false;
          this.alertService.error(BgConstants.petDetilsErrorMessage, true);
        }
        );
    } else {
      // Create mode
      this.loaderService.toggleLoader(false);
      this.loading = false;
    }

    this.buildForm();
  }

  ngOnDestroy() {
    if (this.petFormSubscription) {
      this.petFormSubscription.unsubscribe();
    }
  }

  public selectedSpecieChanged(specieId: number) {
    this.breedsService.getBySpecieId(+specieId).first().subscribe(breeds => this.breeds = breeds);
  }

  private buildForm() {
    this.petForm = this.formBuilder.group({
      'name': [this.pet.name, [Validators.required,
      Validators.minLength(GeneralConstants.petNameMinLenght),
      Validators.maxLength(GeneralConstants.petNameMaxLenght)]],
      'description': [this.pet.description, [Validators.required,
      Validators.minLength(GeneralConstants.petDescriptionMinLenght),
      Validators.maxLength(GeneralConstants.petDescriptionMaxLenght)]],
      'address': [this.pet.address, [Validators.required,
      Validators.minLength(GeneralConstants.petAddressMinLenght),
      Validators.maxLength(GeneralConstants.petAddressMaxLenght)]],
      'imageUrl': [this.pet.imageUrl, [Validators.required,
      Validators.pattern(GeneralConstants.urlImageRegex)]],
      'specieId': [this.pet.specieId],
      'breedId': [this.pet.breedId],
      'petStatusId': [this.pet.petStatusId],
      'cityId': [this.pet.cityId],
      'petGender': [this.pet.petGender]
    });

    if (this.petFormSubscription) {
      this.petFormSubscription.unsubscribe();
    }

    this.petFormSubscription = this.petForm.valueChanges
      .debounceTime(300)
      .subscribe(data => this.formValidationService.onFormValueChanged(this.petForm, this.formErrors, this.validationMessages));

    this.formValidationService.onFormValueChanged(this.petForm, this.formErrors, this.validationMessages);
  }

  public createOrUpdatePet(pet: Pet) {
    if (this.pet.id) {
      pet.id = this.pet.id;
      return this.updatePet(pet);
    }

    return this.createPet(pet);
  }

  private createPet(newPet: Pet) {
    this.loaderService.toggleLoader(true);
    this.loading = true;
    this.petsService.create(newPet)
      .first()
      .subscribe(
      data => {
        this.alertService.success(BgConstants.petCreateSuccessMessage, true);
        this.loaderService.toggleLoader(false);
        this.loading = false;
        this.router.navigate([`pet`, data.id]);
      },
      error => {
        this.alertService.error(BgConstants.petCreateErrorMessage, true);
        this.loaderService.toggleLoader(false);
        this.loading = false;
        this.buildForm();
      });
  }

  private updatePet(updatedPet: Pet) {
    this.loaderService.toggleLoader(true);
    this.loading = true;
    this.petsService.update(updatedPet)
      .first()
      .subscribe(
      data => {
        this.alertService.success(BgConstants.petUpdateSuccessMessage, true);
        this.loaderService.toggleLoader(false);
        this.loading = false;
        this.router.navigate([`pet`, data.id]);
      },
      error => {
        this.alertService.error(BgConstants.petUpdateErrorMessage, true);
        this.loaderService.toggleLoader(false);
        this.loading = false;
        this.buildForm();
      });
  }
}

redpajama_set_name: RedPajamaGithub


text:
status: publish
tags:
- Pennsylvania
- pittsburgh
- sports
published: true
title: Too Bad, Pens!
type: post
meta:
  _edit_last: "2"
layout: post
---
Sadly, the Pittsburgh Penguins lost their game against the Detroit Red Wings last night. Watching the game downtown was fun nonetheless. Plus, while during the course of the game it became quite apparent that the Red Wings are the stronger team, at the very end the Pens put a tremendous effort into tying the game to get into overtime and they almost made it! In the last second of the game, the puck was literally *on* the Red Wings' goal line.

I also got myself a t-shirt with the Pens' captain's name on it (Sidney Crosby) -- I mean, when in Rome...

Here are three pictures I took with my crappy cellphone cam (click on them to see the larger version):


text:
package org.jasig.cas.web;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.AuthenticationException;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.HttpBasedServiceCredential;
import org.jasig.cas.authentication.principal.WebApplicationService;
import org.jasig.cas.services.UnauthorizedProxyingException;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.ticket.TicketValidationException;
import org.jasig.cas.ticket.proxy.ProxyHandler;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.Cas20ProtocolValidationSpecification;
import org.jasig.cas.validation.ValidationSpecification;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

/**
 * Process the /validate , /serviceValidate , and /proxyValidate URL requests.
 * <p>
 * Obtain the Service Ticket and Service information and present them to the CAS
 * validation services. Receive back an Assertion containing the user Principal
 * and (possibly) a chain of Proxy Principals. Store the Assertion in the Model
 * and chain to a View to generate the appropriate response (CAS 1, CAS 2 XML,
 * SAML, ...).
 *
 * @author Scott Battaglia
 * @author Misagh Moayyed
 * @since 3.0
 */
public class ServiceValidateController extends DelegateController {

    /** View if Service Ticket Validation Fails. */
    public static final String DEFAULT_SERVICE_FAILURE_VIEW_NAME = "cas2ServiceFailureView";

    /** View if Service Ticket Validation Succeeds. */
    public static final String DEFAULT_SERVICE_SUCCESS_VIEW_NAME = "cas2ServiceSuccessView";

    /** Constant representing the PGTIOU in the model. */
    private static final String MODEL_PROXY_GRANTING_TICKET_IOU = "pgtIou";

    /** Constant representing the Assertion in the model. */
    private static final String MODEL_ASSERTION = "assertion";

    /** Constant representing the proxy callback url parameter in the request. */
    private static final String PARAMETER_PROXY_CALLBACK_URL = "pgtUrl";

    /** The CORE which we will delegate all requests to. */
    @NotNull
    private CentralAuthenticationService centralAuthenticationService;

    /** The validation protocol we want to use. */
    @NotNull
    private Class<?> validationSpecificationClass = Cas20ProtocolValidationSpecification.class;

    /** The proxy handler we want to use with the controller. */
    @NotNull
    private ProxyHandler proxyHandler;

    /** The view to redirect to on a successful validation. */
    @NotNull
    private String successView = DEFAULT_SERVICE_SUCCESS_VIEW_NAME;

    /** The view to redirect to on a validation failure. */
    @NotNull
    private String failureView = DEFAULT_SERVICE_FAILURE_VIEW_NAME;

    /** Extracts parameters from Request object. */
    @NotNull
    private ArgumentExtractor argumentExtractor;

    /**
     * Overrideable method to determine which credentials to use to grant a
     * proxy granting ticket. Default is to use the pgtUrl.
     *
     * @param request the HttpServletRequest object.
     * @return the credentials or null if there was an error or no credentials
     * provided.
     */
    protected Credential getServiceCredentialsFromRequest(final HttpServletRequest request) {
        final String pgtUrl = request.getParameter(PARAMETER_PROXY_CALLBACK_URL);
        if (StringUtils.hasText(pgtUrl)) {
            try {
                return new HttpBasedServiceCredential(new URL(pgtUrl));
            } catch (final Exception e) {
                logger.error("Error constructing pgtUrl", e);
            }
        }

        return null;
    }

    protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) {
        binder.setRequiredFields("renew");
    }

    @Override
    protected final ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        final WebApplicationService service = this.argumentExtractor.extractService(request);
        final String serviceTicketId = service != null ? service.getArtifactId() : null;

        if (service == null || serviceTicketId == null) {
            logger.debug("Could not identify service and/or service ticket. Service: {}, Service ticket id: {}", service, serviceTicketId);
            return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", null);
        }

        try {
            final Credential serviceCredential = getServiceCredentialsFromRequest(request);
            String proxyGrantingTicketId = null;

            if (serviceCredential != null) {
                try {
                    proxyGrantingTicketId = this.centralAuthenticationService.delegateTicketGrantingTicket(serviceTicketId,
                                serviceCredential);
                } catch (final AuthenticationException e) {
                    logger.info("Failed to authenticate service credential {}", serviceCredential);
                } catch (final TicketException e) {
                    logger.error("Failed to create proxy granting ticket for {}", serviceCredential, e);
                }

                if (StringUtils.isEmpty(proxyGrantingTicketId)) {
                    return generateErrorView("INVALID_PROXY_CALLBACK", "INVALID_PROXY_CALLBACK",
                            new Object[] {serviceCredential.getId()});
                }
            }

            final Assertion assertion = this.centralAuthenticationService.validateServiceTicket(serviceTicketId, service);

            final ValidationSpecification validationSpecification = this.getCommandClass();
            final ServletRequestDataBinder binder = new ServletRequestDataBinder(validationSpecification, "validationSpecification");
            initBinder(request, binder);
            binder.bind(request);

            if (!validationSpecification.isSatisfiedBy(assertion)) {
                logger.debug("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
                return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", null);
            }

            String proxyIou = null;
            if (serviceCredential != null && proxyGrantingTicketId != null && this.proxyHandler.canHandle(serviceCredential)) {
                proxyIou = this.proxyHandler.handle(serviceCredential, proxyGrantingTicketId);
                if (StringUtils.isEmpty(proxyIou)) {
                    return generateErrorView("INVALID_PROXY_CALLBACK", "INVALID_PROXY_CALLBACK",
                            new Object[] {serviceCredential.getId()});
                }
            }

            onSuccessfulValidation(serviceTicketId, assertion);
            logger.debug("Successfully validated service ticket {} for service [{}]", serviceTicketId, service.getId());
            return generateSuccessView(assertion, proxyIou);
        } catch (final TicketValidationException e) {
            return generateErrorView(e.getCode(), e.getCode(),
                    new Object[] {serviceTicketId, e.getOriginalService().getId(), service.getId()});
        } catch (final TicketException te) {
            return generateErrorView(te.getCode(), te.getCode(),
                new Object[] {serviceTicketId});
        } catch (final UnauthorizedProxyingException e) {
            return generateErrorView(e.getMessage(), e.getMessage(), new Object[] {service.getId()});
        } catch (final UnauthorizedServiceException e) {
            return generateErrorView(e.getMessage(), e.getMessage(), null);
        }
    }

    protected void onSuccessfulValidation(final String serviceTicketId, final Assertion assertion) {
        // template method with nothing to do.
    }

    private ModelAndView generateErrorView(final String code, final String description, final Object[] args) {
        final ModelAndView modelAndView = new ModelAndView(this.failureView);
        final String convertedDescription = getMessageSourceAccessor().getMessage(description, args, description);
        modelAndView.addObject("code", code);
        modelAndView.addObject("description", convertedDescription);

        return modelAndView;
    }

    private ModelAndView generateSuccessView(final Assertion assertion, final String proxyIou) {
        final ModelAndView success = new ModelAndView(this.successView);
        success.addObject(MODEL_ASSERTION, assertion);
        success.addObject(MODEL_PROXY_GRANTING_TICKET_IOU, proxyIou);
        return success;
    }

    private ValidationSpecification getCommandClass() {
        try {
            return (ValidationSpecification) this.validationSpecificationClass.newInstance();
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) {
        return true;
    }

    /**
     * @param centralAuthenticationService The centralAuthenticationService to
     * set.
     */
    public final void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {
        this.centralAuthenticationService = centralAuthenticationService;
    }

    public final void setArgumentExtractor(final ArgumentExtractor argumentExtractor) {
        this.argumentExtractor = argumentExtractor;
    }

    /**
     * @param validationSpecificationClass The authenticationSpecificationClass
     * to set.
     */
    public final void setValidationSpecificationClass(final Class<?> validationSpecificationClass) {
        this.validationSpecificationClass = validationSpecificationClass;
    }

    /**
     * @param failureView The failureView to set.
     */
    public final void setFailureView(final String failureView) {
        this.failureView = failureView;
    }

    /**
     * @param successView The successView to set.
     */
    public final void setSuccessView(final String successView) {
        this.successView = successView;
    }

    /**
     * @param proxyHandler The proxyHandler to set.
     */
    public final void setProxyHandler(final ProxyHandler proxyHandler) {
        this.proxyHandler = proxyHandler;
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>admin-linux: _cookbook.file Namespace Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />

admin-linux
    0.0.0

Admin Linux

Main Page

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Packages

Package Functions

 All Classes Namespaces Files Functions Variables

_cookbook

file

Functions

_cookbook.file Namespace Reference

Functions

def 	test_bin_io

def 	test_mmap

Function Documentation

          def _cookbook.file.test_bin_io
          (

          filename	)

Binary I/O

Definition at line 65 of file file.py.

          def _cookbook.file.test_mmap
          (

          filename	)

Memory-mapped I/O.

It should be emphasized that memory mapping a file does not cause the
entire file to be read into memory. That is, it's not copied into some kind
of memory buffer or array. Instead, the operating system merely reserves a
section of virtual memory for the file contents. As you access different
regions, those portions of the file will be read and mapped into the memory
region as needed. However, parts of the file that are never accessed simply
stay on disk. This all happens transparently, behind the scenes.

If more than one Python interpreter memory maps the same file, the
resulting mmap object can be used to exchange data between interpreters.
That is, all interpreters can read/write data simultaneously, and changes
made to the data in one interpreter will automatically appear in the
others. Obviously, some extra care is required to synchronize things, but
this kind of approach is sometimes used as an alternative to transmitting
data in messages over pipes or sockets.

Definition at line 97 of file file.py.

<address class="footer">
Generated on Wed Sep 17 2014 14:49:33 for admin-linux by

 1.8.6
</address>


text:
namespace Google.Cloud.Dataplex.V1.Snippets
{
    // [START dataplex_v1_generated_MetadataService_GetPartition_sync_flattened]
    using Google.Cloud.Dataplex.V1;

    public sealed partial class GeneratedMetadataServiceClientSnippets
    {
        /// <summary>Snippet for GetPartition</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void GetPartition()
        {
            // Create client
            MetadataServiceClient metadataServiceClient = MetadataServiceClient.Create();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]/zones/[ZONE]/entities/[ENTITY]/partitions/[PARTITION]";
            // Make the request
            Partition response = metadataServiceClient.GetPartition(name);
        }
    }
    // [END dataplex_v1_generated_MetadataService_GetPartition_sync_flattened]
}


text:
namespace LiveSplit.UI.Components
{
    public interface IDeactivatableComponent : IComponent
    {
        bool Activated { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2021 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources>
  <public name="materialDividerStyle" type="attr"/>
  <public name="materialDividerHeavyStyle" type="attr"/>
  <public name="dividerColor" type="attr"/>
  <public name="dividerThickness" type="attr"/>
  <public name="dividerInsetStart" type="attr"/>
  <public name="dividerInsetEnd" type="attr"/>
  <public name="lastItemDecorated" type="attr"/>
  <public name="Widget.MaterialComponents.MaterialDivider" type="style"/>
  <public name="Widget.Material3.MaterialDivider" type="style"/>
  <public name="Widget.Material3.MaterialDivider.Heavy" type="style"/>
</resources>


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=iso-8859-1">
<TITLE>
Uses of Class org.apache.commons.io.LineIterator (Commons IO 2.3 API)
</TITLE>

<META NAME="date" CONTENT="2012-04-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.commons.io.LineIterator

Packages that use LineIterator

org.apache.commons.io

This package defines utility classes for working with streams, readers,
writers and files.

Uses of LineIterator in org.apache.commons.io

Methods in org.apache.commons.io that return LineIterator

static LineIterator
FileUtils.lineIterator(File file)

          Returns an Iterator for the lines in a File using the default encoding for the VM.

static LineIterator
FileUtils.lineIterator(File file,
             String encoding)

          Returns an Iterator for the lines in a File.

static LineIterator
IOUtils.lineIterator(InputStream input,
             Charset encoding)

          Return an Iterator for the lines in an InputStream, using
 the character encoding specified (or default encoding if null).

static LineIterator
IOUtils.lineIterator(InputStream input,
             String encoding)

          Return an Iterator for the lines in an InputStream, using
 the character encoding specified (or default encoding if null).

static LineIterator
IOUtils.lineIterator(Reader reader)

          Return an Iterator for the lines in a Reader.

Methods in org.apache.commons.io with parameters of type LineIterator

static void
LineIterator.closeQuietly(LineIterator iterator)

          Closes the iterator, handling null and ignoring exceptions.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2012 The Apache Software Foundation. All Rights Reserved.


text:
<?php

// Pre-Spec setup


text:
using Aggregates.Contracts;
using Aggregates.Exceptions;
using Aggregates.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using NewtonSerializer = Newtonsoft.Json.JsonSerializer;

namespace Aggregates.Internal
{
    // https://github.com/Particular/NServiceBus.Newtonsoft.Json/blob/develop/src/NServiceBus.Newtonsoft.Json/JsonMessageSerializer.cs
    [ExcludeFromCodeCoverage]
    class JsonMessageSerializer : IMessageSerializer
    {
        public static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

        IEventMapper messageMapper;
        IEventFactory messageFactory;
        Func<Stream, JsonReader> readerCreator;
        Func<Stream, JsonWriter> writerCreator;
        NewtonSerializer jsonSerializer;

        public JsonMessageSerializer(
            IEventMapper messageMapper,
            IEventFactory messageFactory,
            JsonConverter[] extraConverters)
        {
            this.messageMapper = messageMapper;
            this.messageFactory = messageFactory;

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Converters = new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new IdJsonConverter() }.Concat(extraConverters).ToArray(),
                //Error = new EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>(HandleError),
                ContractResolver = new EventContractResolver(messageMapper, messageFactory),
                SerializationBinder = new EventSerializationBinder(messageMapper),
                //TraceWriter = new TraceWriter(),
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Include
            };

            this.writerCreator = (stream =>
            {
                var streamWriter = new StreamWriter(stream, Utf8NoBom);
                return new JsonTextWriter(streamWriter)
                {
                    // better for displaying
                    Formatting = Formatting.Indented
                };
            });

            this.readerCreator = (stream =>
            {
                var streamReader = new StreamReader(stream, Utf8NoBom);
                return new JsonTextReader(streamReader);
            });

            ContentType = "Json";
            jsonSerializer = NewtonSerializer.Create(settings);
        }

        //private static void HandleError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
        //{
        //    args.ErrorContext.Handled = true;
        //    throw new SerializerException(args.ErrorContext.Error, args.ErrorContext.Path);
        //}

        public void Serialize(object message, Stream stream)
        {
            using (var writer = writerCreator(stream))
            {
                writer.CloseOutput = false;
                jsonSerializer.Serialize(writer, message);
                writer.Flush();
            }
        }

        public object[] Deserialize(Stream stream, IList<Type> messageTypes)
        {
            var isArrayStream = IsArrayStream(stream);

            if (messageTypes.Any())
            {
                return DeserializeMultipleMessageTypes(stream, messageTypes, isArrayStream);
            }

            return new[]
            {
                ReadObject(stream, isArrayStream, typeof(object))
            };
        }

        object ReadObject(Stream stream, bool isArrayStream, Type type)
        {
            using (var reader = readerCreator(stream))
            {
                reader.CloseInput = false;
                if (isArrayStream)
                {
                    var objects = (object[])jsonSerializer.Deserialize(reader, type.MakeArrayType());
                    if (objects.Length > 1)
                    {
                        throw new Exception("Multiple messages in the same stream are not supported.");
                    }
                    return objects[0];
                }

                return jsonSerializer.Deserialize(reader, type);
            }
        }

        public string ContentType { get; }

        object[] DeserializeMultipleMessageTypes(Stream stream, IList<Type> messageTypes, bool isArrayStream)
        {
            var rootTypes = FindRootTypes(messageTypes).ToList();
            var messages = new object[rootTypes.Count];
            for (var index = 0; index < rootTypes.Count; index++)
            {
                var messageType = rootTypes[index];
                stream.Seek(0, SeekOrigin.Begin);

                messageType = GetMappedType(messageType);
                messages[index] = ReadObject(stream, isArrayStream, messageType);
            }
            return messages;
        }

        Type GetMappedType(Type messageType)
        {
            if (messageType.IsInterface)
            {
                var mappedTypeFor = messageMapper.GetMappedTypeFor(messageType);
                if (mappedTypeFor != null)
                {
                    return mappedTypeFor;
                }
            }
            return messageType;
        }

        bool IsArrayStream(Stream stream)
        {
            using (var reader = readerCreator(stream))
            {
                reader.CloseInput = false;
                reader.Read();
                stream.Seek(0, SeekOrigin.Begin);
                return reader.TokenType == JsonToken.StartArray;
            }
        }

        static IEnumerable<Type> FindRootTypes(IEnumerable<Type> messageTypesToDeserialize)
        {
            Type currentRoot = null;
            foreach (var type in messageTypesToDeserialize)
            {
                if (currentRoot == null)
                {
                    currentRoot = type;
                    yield return currentRoot;
                    continue;
                }
                if (!type.IsAssignableFrom(currentRoot))
                {
                    currentRoot = type;
                    yield return currentRoot;
                }
            }
        }
    }
}


text:
/*!
 * CLDR JavaScript Library v@VERSION @DATE MIT license © Rafael Xavier
 * http://git.io/h4lmVg
 */
(function( factory ) {

	if ( typeof define === "function" && define.amd ) {
		// AMD.

		// Node. CommonJS.
		module.exports = factory( require( "cldrjs" ) );
	} else {
		// Global
		factory( Cldr );
	}

}(function( Cldr ) {

	// Build optimization hack to avoid duplicating functions across modules.
	var coreLoad = Cldr._coreLoad;
	var jsonMerge = Cldr._jsonMerge;
	var pathNormalize = Cldr._pathNormalize;
	var resourceGet = Cldr._resourceGet;
	var validatePresence = Cldr._validatePresence;
	var validateTypePath = Cldr._validateTypePath;


text:
#pragma once
#include <aws/secretsmanager/SecretsManager_EXPORTS.h>
#include <aws/secretsmanager/SecretsManagerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SecretsManager
{
namespace Model
{

  /**
   */
  class AWS_SECRETSMANAGER_API ValidateResourcePolicyRequest : public SecretsManagerRequest
  {
  public:
    ValidateResourcePolicyRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ValidateResourcePolicy"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
This field is reserved for internal use.

     */
    inline const Aws::String& GetSecretId() const{ return m_secretId; }

    /**
     *
This field is reserved for internal use.

     */
    inline bool SecretIdHasBeenSet() const { return m_secretIdHasBeenSet; }

    /**
     *
This field is reserved for internal use.

     */
    inline void SetSecretId(const Aws::String& value) { m_secretIdHasBeenSet = true; m_secretId = value; }

    /**
     *
This field is reserved for internal use.

     */
    inline void SetSecretId(Aws::String&& value) { m_secretIdHasBeenSet = true; m_secretId = std::move(value); }

    /**
     *
This field is reserved for internal use.

     */
    inline void SetSecretId(const char* value) { m_secretIdHasBeenSet = true; m_secretId.assign(value); }

    /**
     *
This field is reserved for internal use.

     */
    inline ValidateResourcePolicyRequest& WithSecretId(const Aws::String& value) { SetSecretId(value); return *this;}

    /**
     *
This field is reserved for internal use.

     */
    inline ValidateResourcePolicyRequest& WithSecretId(Aws::String&& value) { SetSecretId(std::move(value)); return *this;}

    /**
     *
This field is reserved for internal use.

     */
    inline ValidateResourcePolicyRequest& WithSecretId(const char* value) { SetSecretId(value); return *this;}

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline const Aws::String& GetResourcePolicy() const{ return m_resourcePolicy; }

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline bool ResourcePolicyHasBeenSet() const { return m_resourcePolicyHasBeenSet; }

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline void SetResourcePolicy(const Aws::String& value) { m_resourcePolicyHasBeenSet = true; m_resourcePolicy = value; }

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline void SetResourcePolicy(Aws::String&& value) { m_resourcePolicyHasBeenSet = true; m_resourcePolicy = std::move(value); }

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline void SetResourcePolicy(const char* value) { m_resourcePolicyHasBeenSet = true; m_resourcePolicy.assign(value); }

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline ValidateResourcePolicyRequest& WithResourcePolicy(const Aws::String& value) { SetResourcePolicy(value); return *this;}

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline ValidateResourcePolicyRequest& WithResourcePolicy(Aws::String&& value) { SetResourcePolicy(std::move(value)); return *this;}

    /**
     *
A JSON-formatted string that contains an Amazon Web Services resource-based
     * policy. The policy in the string identifies who can access or manage this secret
     * and its versions. For example policies, see Permissions
     * policy examples.

     */
    inline ValidateResourcePolicyRequest& WithResourcePolicy(const char* value) { SetResourcePolicy(value); return *this;}

  private:

    Aws::String m_secretId;
    bool m_secretIdHasBeenSet;

    Aws::String m_resourcePolicy;
    bool m_resourcePolicyHasBeenSet;
  };

} // namespace Model
} // namespace SecretsManager
} // namespace Aws


text:
GRR Rapid Response is an incident response framework focused on remote live forensics.

The goal of GRR is to support forensics and investigations in a fast, scalable manner to allow analysts to quickly triage attacks and perform analysis remotely.

GRR consists of 2 parts: client and server.

**GRR client** is deployed on systems that one might want to investigate. On every such system, once deployed, GRR client periodically polls GRR frontend servers for work. "Work" means running a specific action: downloading file, listing a directory, etc.

**GRR server** infrastructure consists of several components (frontends, workers, UI servers, fleetspeak) and provides web-based graphical user interface and an API endpoint that allows analysts to schedule actions on clients and view and process collected data.

## Remote forensics at scale

GRR was built to run at scale so that analysts are capable of effectively collecting and processing data from large numbers of machines. GRR was built with following scenarios in mind:

* Joe saw something weird, check his machine *(p.s. Joe is on holiday in Cambodia and on 3G)*
* Forensically acquire 25 machines for analysis *(p.s. they're in 5 continents and none are Windows)*
* Tell me if this machine is compromised *(while you're at it, check 100,000 of them - i.e. "hunt" across the fleet)*

## GRR client features

* Cross-platform support for Linux, OS X and Windows clients.
* Live remote memory analysis using YARA library.
* Powerful search and download capabilities for files and the Windows registry.
* OS-level and raw file system access, using the SleuthKit (TSK).
* Secure communication infrastructure designed for Internet deployment.
* Detailed monitoring of client CPU, memory, IO usage and self-imposed limits.

## GRR server features

* Fully fledged response capabilities handling most incident response and
   forensics tasks.
* Enterprise hunting (searching across a fleet of machines) support.
* Fast and simple collection of hundreds of digital forensic artifacts.
* AngularJS Web UI and RESTful JSON API with client libraries in Python, PowerShell and Go.
* Powerful data export features supporting variety of formats and output plugins.
* Fully scalable back-end capable of handling large deployments.
* Automated scheduling for recurring tasks.
* Asynchronous design allowing future task scheduling for clients, designed to work with a large fleet of laptops.


text:
namespace YoungNet
{
	class Thread
	{
	public:
		typedef std::function<void()> BGJobs;

		explicit Thread(const BGJobs&);
		explicit Thread(BGJobs&&);
		~Thread() noexcept;

		void Start();
		static pid_t GetTid();

		Thread(const Thread&) = delete;
		Thread& operator=(const Thread&) = delete;
		Thread(Thread&&) = delete;
		Thread& operator=(Thread&&) = delete;

	private:
		bool started_;
		pthread_t pid_;
		BGJobs job_;
	};
} // namespace YoungNet

#endif // __YOUNG_NET_NET_THREAD+H__


text:
module UkAccountValidator
  class Validator

    attr_writer   :sort_code
    attr_accessor :account_number

    def initialize(account_number = nil, sort_code = nil)
      @account_number = account_number
      @sort_code      = sort_code
    end

    def sort_code
      @sort_code.gsub('-', '')
    end

    def modulus_weights
      @modulus_weights ||= UkAccountValidator.modulus_weights_table.find(sort_code)
    end

    def modulus_validator(modulus)
      case modulus
      when 'MOD10'
        Validators::Modulus10
      when 'MOD11'
        Validators::Modulus11
      when 'DBLAL'
        Validators::DoubleAlternate
      else
        fail NotImplementedError
      end
    end

    def valid?
      return false unless valid_format?

      exceptions = modulus_weights.map(&:exception)
      exception_class = self.exception_class(exceptions)

      results = modulus_weights.each_with_index.map do |modulus_weight, i|
        exception = exception_class.new(modulus_weight, account_number, sort_code, i + 1)

        @account_number = exception.apply_account_number_substitutions

        modulus_validator(modulus_weight.modulus).new(
          account_number, sort_code, modulus_weight, exception
        ).valid?
      end

      return results.any? if exception_class.allow_any?

      results.all?
    end

    def valid_format?
      return false if account_number =~ /\D/
      return false if account_number.length < 6
      return false if account_number.length > 10
      return false if sort_code.length != 6

      return true
    end

    def exception_class(exception_strings)
      case
      when exception_strings.include?('1')
        Exception1
      when exception_strings.include?('2') && exception_strings.include?('9')
        Exception29
      when exception_strings.include?('3')
        Exception3
      when exception_strings.include?('4')
        Exception4
      when exception_strings.include?('5')
        Exception5
      when exception_strings.include?('6')
        Exception6
      when exception_strings.include?('7')
        Exception7
      when exception_strings.include?('8')
        Exception8
      when exception_strings.include?('10') && exception_strings.include?('11')
        Exception10
      when exception_strings.include?('12') && exception_strings.include?('13')
        Exception12
      when exception_strings.include?('14')
        Exception14
      else
        BaseException
      end
    end
  end
end


text:
//
//  NSObject+XXParseModel.m
//  PodsTest
//
//  Created by Rdxer on 2016/12/4.
//  Copyright © 2016年 LXF. All rights reserved.
//

#import "NSObject+XXParseModel.h"
#import "JRSwizzle.h"
#import "NSObject+XXProperty.h"

@implementation NSObject (XXParseModel_ExchangeMethod)
+ (void)load
{
    if (self == [NSObject class]) {
        NSError *error = NULL;
        [self jr_swizzleMethod:@selector(setValue:forUndefinedKey:) withMethod:@selector(xx_setValue:forUndefinedKey:) error:&error];
        if (error) {
            NSLog(@"jr_swizzleMethod <setValue:forUndefinedKey:> error===>%@",error);
        }

        error = NULL;

        [self jr_swizzleMethod:@selector(setNilValueForKey:) withMethod:@selector(xx_setNilValueForKey:) error:&error];
        if (error) {
            NSLog(@"jr_swizzleMethod <setNilValueForKey:> error===>%@",error);
        }
    }
}

/// 交换掉NSObject自带的
-(void)xx_setValue:(id)value forUndefinedKey:(NSString *)key{
    if ([self conformsToProtocol:@protocol(XXParseModel)]) {
        if ([[self class] xx_propertyMapDictionary][key]) {
            [self setValue:value forKey:[[self class] xx_propertyMapDictionary][key]];
        }else{
            NSLog(@"forUndefinedKey k(%@)=v(%@) => Class(%@)",key,value,self.class);
        }
    }else{
        [self xx_setValue:value forUndefinedKey:key];
    }
}

-(void)xx_setNilValueForKey:(NSString *)key{
    if ([self conformsToProtocol:@protocol(XXParseModel)]) {
        //        [self setValue:@(0) forKey:[[self class] xx_convertKeys][key]];
        NSLog(@"setNilValueForKey k(%@) => Class(%@)",key,self.class);
    }else{
        [self xx_setNilValueForKey:key];
    }
}

@end

@implementation NSObject (XXParseModel_Dictionary2Model)

+(id)xx_modelWithDictionary:(NSDictionary *)dict{

    if ([dict isKindOfClass:[NSDictionary class]] == false) {
        return nil;
    }

    id clazz = self;
    id instence = [[clazz alloc] init];

    if (dict.count < 1) {
        return instence;
    }

    if ([self respondsToSelector:@selector(xx_ModelPropertyDictionary)]) {
        NSDictionary *modelKeys = [(id)self xx_ModelPropertyDictionary];
        if (modelKeys.count) {
            NSMutableDictionary *dictM = [dict mutableCopy];
            [modelKeys enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                id v = [dictM valueForKey:key];
                [dictM removeObjectForKey:key];
                if (v && [v isKindOfClass:[NSDictionary class]]) {
                    Class clazz;

                    if ([obj isKindOfClass:[NSString class]]) {
                        clazz = NSClassFromString(obj);
                    }else{
                        clazz = obj;
                    }

                    id newobj = [clazz xx_modelWithDictionary:v];

                    [instence setValue:newobj forKey:key];
                }else{
                    if (v) {
                        NSLog(@"XXParseModel <xx_modelWithDict:> error===>字典转模型 自动转化到对应模型时失败 -> value = (%@)",v);
                    }
                }
            }];
            dict = dictM.copy;
        }
    }

    if ([self respondsToSelector:@selector(xx_ArrayModelPropertyDictionary)]) {
        NSDictionary *modelKeys = [(id)self xx_ArrayModelPropertyDictionary];
        if (modelKeys.count) {
            NSMutableDictionary *dictM = [dict mutableCopy];
            [modelKeys enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, Class  _Nonnull obj, BOOL * _Nonnull stop) {
                id v = [dictM valueForKey:key];
                [dictM removeObjectForKey:key];
                if (v && [v isKindOfClass:[NSArray class]]) {
                    id newobjList = [obj xx_modelArrayWithDictionaryArray:v];
                    [instence setValue:newobjList forKey:key];
                }else{
                    if (v) {
                        NSLog(@"XXParseModel <xx_modelWithDict:> error===>字典转模型 自动转化到对应模型列表时失败 -> value = (%@)",v);
                    }
                }
            }];
            dict = dictM.copy;
        }
    }

    [instence setValuesForKeysWithDictionary:dict];

    return instence;
}

+(NSArray *)xx_modelArrayWithDictionaryArray:(NSArray *)dicts{
    NSMutableArray * arrayM = [NSMutableArray array];
    if ([dicts isKindOfClass:[NSArray class]] == false) {
        return arrayM;
    }
    for (NSDictionary *dict in dicts) {
        id obj = [self xx_modelWithDictionary:dict];
        if (obj == nil) {
            NSLog(@"NSArray<NSDictionary>中混进了奇怪的东西...");
            return nil;
        }
        [arrayM addObject:obj];
    }
    return arrayM;
}

@end

@implementation NSObject (XXParseModel_Json2Model)

//// -------- json --------

+(instancetype)xx_modelWithJSONString:(NSString *)jsonStr{
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    if (result == nil || [result isKindOfClass:[NSDictionary class]] == NO) {
        NSLog(@"此 JSONString 不是 字典的 JSON 字符串 %@, error: %@", jsonStr, error);
        return nil;
    }
    return [self xx_modelWithDictionary:result];
}

+(NSArray *)xx_modelArrayWithJSONString:(NSString *)jsonStr{
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    if (result == nil || [result isKindOfClass:[NSArray class]] == NO) {
        NSLog(@"此 JSONString 不是 数组的 JSON 字符串 %@, error: %@", jsonStr, error);
        return nil;
    }
    return [self xx_modelArrayWithDictionaryArray:result];
}

@end

static NSDictionary *_xx_setDefaultConvertKeys = nil;

@implementation NSObject (XXParseModel_ConvertKeys)

/// key <=> key
+(void)xx_setDefaultPropertyMapDictionary:(NSDictionary<NSString *,NSString *> *)keys;{
    _xx_setDefaultConvertKeys = keys;
}

+(NSDictionary *)xx_propertyMapDictionary{
    return _xx_setDefaultConvertKeys ?: @{};
}

@end

@implementation NSObject (XXParseModel_Model2Dictionary)
//-----------------------  model -> json  ----------------
/**
 模型转成字典

 @return JSON字符串
 */
-(nonnull NSMutableDictionary<NSString *,id> *)xx_toDictionary_Dont_Map{
    NSArray *pNameArray = [[self class]xx_allClassPropertyNameArray_filtered];
    NSMutableDictionary<NSString *,id> *dict = [self dictionaryWithValuesForKeys:pNameArray].mutableCopy;
    NSDictionary *temp = dict.copy;
    [temp enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj conformsToProtocol:@protocol(XXParseModel)]) {
            [dict setObject:[obj xx_toDictionary_Dont_Map] forKey:key];
        }else if([obj isKindOfClass:[NSArray class]]){
            NSArray *array = obj;
            if ([array.firstObject conformsToProtocol:@protocol(XXParseModel)]) {
                NSMutableArray *arrayM = [array xx_toDictionaryArray_Dont_Map];
                [dict setObject:arrayM forKey:key];
            }
        }
    }];
    return dict;
}

-(NSMutableDictionary<NSString *,id> *)xx_toDictionary{
    NSArray *pNameArray = [[self class]xx_allClassPropertyNameArray_filtered];
    NSMutableDictionary<NSString *,id> *dict = [self dictionaryWithValuesForKeys:pNameArray].mutableCopy;
    NSDictionary *temp = dict.copy;
    [temp enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj conformsToProtocol:@protocol(XXParseModel)]) {
            [dict setObject:[obj xx_toDictionary] forKey:key];
        }else if([obj isKindOfClass:[NSArray class]]){
            NSArray *array = obj;
            if ([array.firstObject conformsToProtocol:@protocol(XXParseModel)]) {
                NSMutableArray *arrayM = [array xx_toDictionaryArray];
                [dict setObject:arrayM forKey:key];
            }
        }
    }];

    if ([self conformsToProtocol:@protocol(XXParseModel)]) {
        [dict xx_keyConvertFromKeys:[[self class] xx_propertyMapDictionary].xx_dictionaryKeyValueConvert];
    }

    return dict;
}

@end

@implementation NSObject (XXParseModel_Model2Json)

//-----------------------  model -> json  ----------------
/**
 模型转成json字符串

 @return JSON字符串
 */
-(nullable NSString *)xx_toJsonString_Dont_Map{
    NSDictionary<NSString *,id> *dict = [self xx_toDictionary_Dont_Map];

    if ([NSJSONSerialization isValidJSONObject:dict] == false) {
        NSLog(@"不是有效的json对象");
        return nil;
    }

    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
    if (error) {
        NSLog(@"转化为json失败 error->%@",error);
        return nil;
    }

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//-----------------------  model -> json  ----------------
/**
 模型转成json字符串

 @return JSON字符串
 */
-(nullable NSString *)xx_toJsonString{
    NSDictionary<NSString *,id> *dict = [self xx_toDictionary];

    if ([NSJSONSerialization isValidJSONObject:dict] == false) {
        NSLog(@"不是有效的json对象");
        return nil;
    }

    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
    if (error) {
        NSLog(@"转化为json失败 error->%@",error);
        return nil;
    }

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

@end

@implementation NSArray (XXParseModel)

//-----------------------  modelArray -> json  ----------------
/**
 模型转成json字符串

 @return JSON字符串
 */
-(nullable NSString *)xx_toJsonString_Dont_Map{
    NSArray *dictArray = [self xx_toDictionaryArray_Dont_Map];

    if ([NSJSONSerialization isValidJSONObject:dictArray] == false) {
        NSLog(@"不是有效的json对象");
        return nil;
    }

    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictArray options:kNilOptions error:&error];
    if (error) {
        NSLog(@"转化为json失败 error->%@",error);
        return nil;
    }

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//-----------------------  modelArray -> dictArray  ----------------
/**
 模型转成字典

 @return dict
 */
-(nonnull NSMutableArray<NSDictionary<NSString *,id> *>*)xx_toDictionaryArray_Dont_Map{
    NSMutableArray *arrayM = [NSMutableArray array];
    for (id item in self) {
        NSDictionary *dict = [item xx_toDictionary_Dont_Map];
        [arrayM addObject:dict];
    }
    return arrayM;
}

/////////////////////////////////////////////////////////////////
//////////////////////////   进行键值映射转化   /////////////////
//-----------------------  modelArray -> json  ----------------
/**
 模型转成json字符串

 @return JSON字符串
 */
-(nullable NSString *)xx_toJsonString{
    NSArray *dictArray = [self xx_toDictionaryArray];

    if ([NSJSONSerialization isValidJSONObject:dictArray] == false) {
        NSLog(@"不是有效的json对象");
        return nil;
    }

    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictArray options:kNilOptions error:&error];
    if (error) {
        NSLog(@"转化为json失败 error->%@",error);
        return nil;
    }

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//-----------------------  modelArray -> dictArray  ----------------
/**
 模型转成字典

 @return dict
 */
-(nonnull NSMutableArray<NSDictionary<NSString *,id> *>*)xx_toDictionaryArray{
    NSMutableArray *arrayM = [NSMutableArray array];
    for (id item in self) {
        NSDictionary *dict = [item xx_toDictionary];
        [arrayM addObject:dict];
    }
    return arrayM;
}

@end

/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////

@implementation NSMutableDictionary (XXParseModel)

-(void)xx_keyConvertFromKeys:(NSDictionary<NSString *,NSString *> *)keys{
    [keys enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
        id dictV = [self objectForKey:key];
        if (dictV) {
            [self removeObjectForKey:key];
            [self setObject:dictV forKey:obj];
        }
    }];
}

@end

@implementation NSDictionary (XXParseModel)

/**
 字典,键值转换
 */
-(nullable NSDictionary *)xx_dictionaryKeyValueConvert{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:self.count];
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj conformsToProtocol:@protocol(NSCopying)]) {
            [dict setObject:key forKey:obj];
        }else{
            NSLog(@"想要进行转化,值得必须准守NSCopying协议");
            *stop = YES;
        }
    }];
    if (dict.count == self.count) {
        return dict;
    }
    return nil;
}

@end


text:
'''
The MIT License (MIT)

Copyright (c) 2014 NTHUOJ team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''

from datetime import datetime
from django.db import models
from team.models import Team
from users.models import User

# Create your models here.

class Tag(models.Model):

    tag_name = models.CharField(max_length=20, default='')

    def __unicode__(self):
        return self.tag_name

class Problem(models.Model):
    LOCAL = 'LOCAL'
    OTHER = 'OTHER'
    JUDGE_SOURCE_CHOICE = (
        (LOCAL, 'Local Judge'),
        (OTHER, 'Use Other Judge'),
    )

    NORMAL = 'LOCAL_NORMAL'
    SPECIAL = 'LOCAL_SPECIAL'
    ERROR_TOLERANT = 'LOCAL_ERR_TOLERANT'
    PARTIAL = 'LOCAL_PARTIAL'
    UVA_JUDGE = 'OTHER_UVA'
    ICPC_JUDGE = 'OTHER_UVALive'
    POJ_JUDGE = 'OTHER_POJ'
    JUDGE_TYPE_CHOICE = (
        # Local Judge
        (NORMAL, 'Normal Judge'),
        (SPECIAL, 'Special Judge'),
        # (ERROR_TOLERANT, 'Error TOLERANT'),
        (PARTIAL, 'Partial Judge'),
        # Other Judge
        (UVA_JUDGE, 'Uva'),
        (ICPC_JUDGE, 'ACM ICPC Live Archive'),
        (POJ_JUDGE, 'POJ'),
    )

    C = 'C'
    CPP = 'CPP'
    CPP11 = 'CPP11'
    LANGUAGE_CHOICE = (
        (C, 'C'),
        (CPP, 'C++'),
        (CPP11, 'C++11'),
    )

    pname = models.CharField(max_length=50, default='')
    owner = models.ForeignKey(User)
    description = models.TextField(blank=True)
    input = models.TextField(blank=True)
    output = models.TextField(blank=True)
    sample_in = models.TextField(blank=True)
    sample_out = models.TextField(blank=True)
    visible = models.BooleanField(default=False)
    error_tolerance = models.DecimalField(decimal_places=15, max_digits=17, default=0)
    other_judge_id = models.IntegerField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True, null=True)
    judge_source = models.CharField(max_length=11, choices=JUDGE_SOURCE_CHOICE, default=LOCAL)
    judge_type = models.CharField(max_length=20, choices=JUDGE_TYPE_CHOICE, default=NORMAL)
    judge_language = models.CharField(max_length=11, choices=LANGUAGE_CHOICE, default=CPP)
    ac_count = models.IntegerField(default=0)
    total_submission = models.IntegerField(default=0)

    def __unicode__(self):
        return '%d - %s' % (self.id, self.pname)

class Testcase(models.Model):
    problem = models.ForeignKey(Problem)
    description = models.TextField(blank=True)
    time_limit = models.IntegerField(default=1)
    memory_limit = models.IntegerField(default=32)

    def __unicode__(self):
        return '%s: %s' % (self.problem.pname, self.description)

class Submission(models.Model):
    WAIT = 'WAIT'
    JUDGING = 'JUDGING'
    ACCEPTED = 'AC'
    NOT_ACCEPTED = 'NA'
    COMPILE_ERROR = 'CE'
    RESTRICTED_FUNCTION = 'RF'
    JUDGE_ERROR = 'JE'
    STATUS_CHOICE = (
        (WAIT, 'Being Judged'),
        (JUDGING, 'Judging'),
        (ACCEPTED, 'All Accepted'),
        (NOT_ACCEPTED, 'Not Accepted'),
        (COMPILE_ERROR, 'Compile Error'),
        (RESTRICTED_FUNCTION, 'Restricted Function'),
        (JUDGE_ERROR, 'Judge Error'),
    )

    C = 'C'
    CPP = 'CPP'
    CPP11 = 'CPP11'
    LANGUAGE_CHOICE = (
        (C, 'C'),
        (CPP, 'C++'),
        (CPP11, 'C++11'),
    )

    problem = models.ForeignKey(Problem)
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team, blank=True, null=True)
    submit_time = models.DateTimeField(default=datetime.now)
    error_msg = models.TextField(blank=True)
    status = models.CharField(max_length=25, choices=STATUS_CHOICE, default=WAIT)
    language = models.CharField(max_length=5, choices=LANGUAGE_CHOICE, default=C)
    other_judge_sid = models.IntegerField(blank=True, null=True)
    def __unicode__(self):
        return str(self.id)

class SubmissionDetail(models.Model):
    AC = 'AC'
    WA = 'WA'
    TLE = 'TLE'
    MLE = 'MLE'
    RE = 'RE'
    PE = 'PE'
    VERDICT_CHOICE = (
        (AC, 'Accepted'),
        (WA, 'Wrong Answer'),
        (TLE, 'Time Limit Exceeded'),
        (MLE, 'Memory Limit Exceeded'),
        (RE, 'Runtime Error'),
        (PE, 'Presentation Error'),
    )

    tid = models.ForeignKey(Testcase)
    sid = models.ForeignKey(Submission)
    cpu = models.FloatField(default=0)
    memory = models.IntegerField(default=0)
    verdict = models.CharField(max_length=3, choices=VERDICT_CHOICE, default='')

    class Meta:
        unique_together = (('tid', 'sid'),)

    def __unicode__(self):
        return 'sid %d, tid %d' % (self.sid.id, self.tid.id)


text:
SUBDIRS		=	src

DOCFILE  = CharEncConvert

include	./Makefile.common


text:
// Copyright Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity;
using UnityEngine;

public class ButtonSlateConnection : MonoBehaviour
{
    public AboutSlate Slate;

    private Tagalong tagalong;
    private float distance = 2.0f;

    private void Start()
    {
        if (Slate)
        {
            tagalong = Slate.gameObject.GetComponent<Tagalong>();

            if (tagalong)
            {
                distance = tagalong.TagalongDistance;
            }
        }
    }

    public void Show()
    {
        Slate.gameObject.SetActive(true);

        Vector3 headForward = Camera.main.transform.forward;
        headForward.y = 0;
        headForward.Normalize();

        Slate.gameObject.transform.position = Camera.main.transform.position + (headForward * distance);

        Slate.Show();
    }

    public void Hide()
    {
        Slate.Hide();
    }
}


text:
Sequel.migration do
  change do
    create_table :reg_d601 do
      column :id, Integer, primary_key: true
      column :id_pai, Integer, index: true, null: false
      column :cod_class, String, size: 4
      column :vl_item, BigDecimal, size: [18, 2]
      column :vl_desc, BigDecimal, size: [18, 2]
      column :cst_pis, String, size: 2
      column :vl_bc_pis, BigDecimal, size: [18, 2]
      column :aliq_pis, BigDecimal, size: [18, 4]
      column :vl_pis, BigDecimal, size: [18, 2]
      column :cod_cta, String, size: 60
      column :cnpj_pai, String, size: 14, index: true
    end
  end
end


text:
package com.b12kab.tmdblibrary.entities;

import com.google.gson.annotations.SerializedName;

import java.util.Date;
import java.util.List;

public class TvSeason {
    @SerializedName("_id")
    String _id;

    public Integer id;
    public Date air_date;
    public List<TvEpisode> episodes;
    public Integer episode_count;
    public String name;
    public String overview;
    public String poster_path;
    public Integer season_number;
    public CreditResults credits;
    public Images images;
    public ExternalIds external_ids;

}


text:
import numpy as np
from keras.layers import Dense, Activation
from keras.models import Sequential

# OR logic gate inputs and output.
# x_train is sample data (input features)
# y_train the expected outcome for example
x_train = np.array([[0, 0],
                    [0, 1],
                    [1, 0],
                    [1, 1]])
y_train = np.array([[0],
                    [1],
                    [1],
                    [1]])
model = Sequential()
model.add(Dense(1, input_dim=2))
model.add(Activation('sigmoid'))
model.compile('SGD', 'mse')
model.fit(x_train, y_train)
# Get stochastic gradient descent, though there are others
model = Sequential()
model.add(Dense(1, input_dim=2))
model.add(Activation('sigmoid'))
model.compile('sgd', 'mse')
model.fit(x=np.array(x_train), y=np.array(y_train), epochs=5000, batch_size=4)


text:
package org.drools.ide.common.server.testscenarios;

import java.util.HashSet;
import java.util.List;

public class ScenarioSettings {

    private HashSet<String> ruleList = new HashSet<String>();
    private boolean inclusive;
    private int maxRuleFirings;

    public void setRuleList(List<String> ruleList) {
        this.ruleList.addAll(ruleList);
    }

    public HashSet<String> getRuleList() {
        return ruleList;
    }

    public void setInclusive(boolean inclusive) {
        this.inclusive = inclusive;
    }

    public boolean isInclusive() {
        return inclusive;
    }

    public int getMaxRuleFirings() {
        return maxRuleFirings;
    }

    public void setMaxRuleFirings(int maxRuleFirings) {
        this.maxRuleFirings = maxRuleFirings;
    }
}


text:
/* First created by JCasGen Sat Mar 07 22:05:57 CET 2015 */
package de.julielab.jules.types;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;

/**
 * Updated by JCasGen Sat Mar 07 22:05:57 CET 2015
 * @generated */
public class EEE_Type extends Coordination_Type {
  /** @generated
   * @return the generator for this type
   */
  @Override
  protected FSGenerator getFSGenerator() {return fsGenerator;}
  /** @generated */
  private final FSGenerator fsGenerator =
    new FSGenerator() {
      public FeatureStructure createFS(int addr, CASImpl cas) {
  			 if (EEE_Type.this.useExistingInstance) {
  			   // Return eq fs instance if already created
  		     FeatureStructure fs = EEE_Type.this.jcas.getJfsFromCaddr(addr);
  		     if (null == fs) {
  		       fs = new EEE(addr, EEE_Type.this);
  			   EEE_Type.this.jcas.putJfsFromCaddr(addr, fs);
  			   return fs;
  		     }
  		     return fs;
        } else return new EEE(addr, EEE_Type.this);
  	  }
    };
  /** @generated */
  @SuppressWarnings ("hiding")
  public final static int typeIndexID = EEE.typeIndexID;
  /** @generated
     @modifiable */
  @SuppressWarnings ("hiding")
  public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.julielab.jules.types.EEE");

  /** initialize variables to correspond with Cas Type and Features
	 * @generated
	 * @param jcas JCas
	 * @param casType Type
	 */
  public EEE_Type(JCas jcas, Type casType) {
    super(jcas, casType);
    casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator());

  }
}


text:
import 'core-js/es';
import 'core-js/proposals/reflect-metadata';
import 'zone.js/dist/zone';

if (process.env.ENV === 'production') {
  // Production
} else {
  // Development and test
  Error.stackTraceLimit = Infinity;
  require('zone.js/dist/long-stack-trace-zone');
}


text:
<?php
namespace Zend\Db\Sql;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2012-03-01 at 23:40:12.
 */
class DeleteTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Delete
     */
    protected $delete;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->delete = new Delete;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Zend\Db\Sql\Delete::from
     * @todo   Implement testFrom().
     */
    public function testFrom()
    {
        $this->delete->from('foo', 'bar');
        $this->assertEquals('foo', $this->readAttribute($this->delete, 'table'));
        $this->assertEquals('bar', $this->readAttribute($this->delete, 'databaseOrSchema'));
    }

    /**
     * @covers Zend\Db\Sql\Delete::where
     * @todo   Implement testWhere().
     */
    public function testWhere()
    {
        $this->delete->where('x = y');
        $this->delete->where(array('foo > ?' => 5));
        $this->delete->where(array('id' => 2));
        $this->delete->where(array('a = b'), Where::OP_OR);
        $where = $this->delete->where;

        $predicates = $this->readAttribute($where, 'predicates');
        $this->assertEquals('AND', $predicates[0][0]);
        $this->assertInstanceOf('Zend\Db\Sql\Predicate\Literal', $predicates[0][1]);

        $this->assertEquals('AND', $predicates[1][0]);
        $this->assertInstanceOf('Zend\Db\Sql\Predicate\Literal', $predicates[1][1]);

        $this->assertEquals('AND', $predicates[2][0]);
        $this->assertInstanceOf('Zend\Db\Sql\Predicate\Operator', $predicates[2][1]);

        $this->assertEquals('OR', $predicates[3][0]);
        $this->assertInstanceOf('Zend\Db\Sql\Predicate\Literal', $predicates[3][1]);

        $where = new Where;
        $this->delete->where($where);
        $this->assertSame($where, $this->delete->where);

        $test = $this;
        $this->delete->where(function ($what) use ($test, $where) {
            $test->assertSame($where, $what);
        });
    }

    /**
     * @covers Zend\Db\Sql\Delete::prepareStatement
     */
    public function testPrepareStatement()
    {
        $mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
        $mockAdapter = $this->getMock('Zend\Db\Adapter\Adapter', null, array($mockDriver));

        $mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
        $mockStatement->expects($this->at(0))
            ->method('setSql')
            ->with($this->equalTo('DELETE FROM "foo"'));
        $mockStatement->expects($this->at(3))
            ->method('setSql')
            ->with($this->equalTo(' WHERE x = y'));

        $this->delete->from('foo')
            ->where('x = y');

        $this->delete->prepareStatement($mockAdapter, $mockStatement);
    }

    /**
     * @covers Zend\Db\Sql\Delete::getSqlString
     */
    public function testGetSqlString()
    {
        $this->delete->from('foo')
            ->where('x = y');
        $this->assertEquals('DELETE FROM "foo" WHERE x = y', $this->delete->getSqlString());

    }
}


text:
@implementation RMPPageViewController {
    UILabel* _messageLabel;
}

- (void)loadView
{
    [super loadView];

    CGRect f = self.view.bounds;
    f.size.height = 32;
    UILabel* label = [[UILabel alloc] initWithFrame:f];
    _messageLabel = label;
    _messageLabel.numberOfLines = 0;
    _messageLabel.textColor = [UIColor whiteColor];
    _messageLabel.textAlignment = NSTextAlignmentCenter;
    _messageLabel.center = CGPointMake(self.view.bounds.size.width*0.5, self.view.bounds.size.height*0.5);
    [self.view addSubview:_messageLabel];

    if(_message){
        _messageLabel.text = _message;
    }

}

- (void)setMessage:(NSString *)message
{
    _message = message;
    _messageLabel.text = _message;
}

- (void)viewDidLayoutSubviews
{
    _messageLabel.center = CGPointMake(self.view.bounds.size.width*0.5, self.view.bounds.size.height*0.5);
}

@end


text:
package org.apache.kylin.engine.spark;

import org.apache.kylin.engine.spark.job.NSparkOptimizingJob;
import org.apache.kylin.engine.spark.job.NSparkCubingJob;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.cube.model.CubeDesc;
import org.apache.kylin.engine.IBatchCubingEngine;
import org.apache.kylin.engine.spark.job.NSparkMergingJob;
import org.apache.kylin.engine.spark.job.NTableSamplingJob;
import org.apache.kylin.job.execution.DefaultChainedExecutable;
import org.apache.kylin.metadata.model.IJoinedFlatTableDesc;
import org.apache.kylin.shaded.com.google.common.collect.Sets;
import org.apache.kylin.metadata.model.TableDesc;

public class SparkBatchCubingEngineParquet implements IBatchCubingEngine {
    @Override
    public IJoinedFlatTableDesc getJoinedFlatTableDesc(CubeDesc cubeDesc) {
        return null;
    }

    @Override
    public IJoinedFlatTableDesc getJoinedFlatTableDesc(CubeSegment newSegment) {
        return null;
    }

    @Override
    public DefaultChainedExecutable createBatchCubingJob(CubeSegment newSegment, String submitter, Integer priorityOffset) {
        return NSparkCubingJob.create(Sets.newHashSet(newSegment), submitter);
    }

    @Override
    public DefaultChainedExecutable createBatchMergeJob(CubeSegment mergeSegment, String submitter) {
        return NSparkMergingJob.merge(mergeSegment, submitter);
    }

    @Override
    public DefaultChainedExecutable createBatchOptimizeJob(CubeSegment optimizeSegment, String submitter) {
        return NSparkOptimizingJob.optimize(optimizeSegment, submitter);
    }

    @Override
    public DefaultChainedExecutable createSampleTableJob(String project, String submitter, long maxSampleCount,
            TableDesc tableDesc) {
        return NTableSamplingJob.create(tableDesc, project, submitter, maxSampleCount);
    }

    @Override
    public Class<?> getSourceInterface() {
        return null;
    }

    @Override
    public Class<?> getStorageInterface() {
        return null;
    }
}


text:
package com.google.common.collect.testing.testers;

import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;

/**
 * A generic JUnit test which tests {@code size()} operations on a map.
 * Can't be invoked directly; please see
 * {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
 *
 * <p>This class is GWT compatible.
 *
 * @author George van den Driessche
 */
@GwtCompatible
public class MapSizeTester<K, V> extends AbstractMapTester<K, V> {
  public void testSize() {
    assertEquals("size():", getNumElements(), getMap().size());
  }
}


text:
#ifndef QQUICKSTYLEATTACHED_P_H
#define QQUICKSTYLEATTACHED_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtQml/qqml.h>
#include <QtCore/qlist.h>
#include <QtCore/qobject.h>
#include <QtCore/qpointer.h>
#include <QtCore/qsharedpointer.h>
#include <QtQuick/private/qquickitemchangelistener_p.h>
#include <QtQuickControls2/private/qtquickcontrols2global_p.h>

QT_BEGIN_NAMESPACE

class QSettings;
class QQuickWindow;

class Q_QUICKCONTROLS2_PRIVATE_EXPORT QQuickStyleAttached : public QObject, public QQuickItemChangeListener
{
    Q_OBJECT

public:
    explicit QQuickStyleAttached(QObject *parent = nullptr);
    ~QQuickStyleAttached();

    static QSharedPointer<QSettings> settings(const QString &group = QString());

protected:
    void init();

    QList<QQuickStyleAttached *> childStyles() const;

    QQuickStyleAttached *parentStyle() const;
    void setParentStyle(QQuickStyleAttached *style);

    virtual void parentStyleChange(QQuickStyleAttached *newParent, QQuickStyleAttached *oldParent);

    void itemWindowChanged(QQuickWindow *window);
    void itemParentChanged(QQuickItem *item, QQuickItem *parent) override;

private:
    QList<QQuickStyleAttached *> m_childStyles;
    QPointer<QQuickStyleAttached> m_parentStyle;
};

QT_END_NAMESPACE

#endif // QQUICKSTYLEATTACHED_P_H


text:
import logging
import csv
import yaml
from dipper.sources.Source import Source
from dipper.models.assoc.Association import Assoc
from dipper.models.Pathway import Pathway

LOG = logging.getLogger(__name__)

class Reactome(Source):
    """
    Reactome is a free, open-source, curated and peer reviewed pathway database.
    (http://reactome.org/)
    """
    REACTOME_BASE = "http://www.reactome.org/download/current/"
    files = {
        'ensembl2pathway': {
            'file': 'Ensembl2Reactome.txt',
            'url': REACTOME_BASE + 'Ensembl2Reactome.txt',
            'columns': [          # e.g.
                'component',      # 1:C34F11.9e
                'pathway_id',     # 2:R-CEL-201688
                'pathway_iri',    # 3:https://reactome.org/PathwayBrowser/#/R-CEL-123
                'pathway_label',  # 4:WNT mediated activation of DVL
                'go_ecode',       # 5:IEA
                'species_nam',    # 6:Caenorhabditis elegans
            ]
        },
        'chebi2pathway': {
            'file': 'ChEBI2Reactome.txt',
            'url': REACTOME_BASE + 'ChEBI2Reactome.txt',
            'columns': [          # e.g.
                'component',      # 1:10033
                'pathway_id',     # 2:R-BTA-6806664
                'pathway_iri',    # 3:https://reactome.org/PathwayBrowser/#/R-BTA-123
                'pathway_label',  # 4:Metabolism of vitamin K
                'go_ecode',       # 5:IEA
                'species_nam',    # 6:Bos taurus
            ]
        },
        'gaf-eco-mapping': {
            'file': 'gaf-eco-mapping.yaml',
            'url': '/'.join((Source.DIPPERCACHE, 'reactome', 'gaf-eco-mapping.yaml')),
        }
    }

    def __init__(
            self,
            graph_type,
            are_bnodes_skolemized,
            data_release_version=None
    ):
        super().__init__(
            graph_type=graph_type,
            are_bnodes_skized=are_bnodes_skolemized,
            data_release_version=data_release_version,
            name='reactome',
            ingest_title='Reactome',
            ingest_url='http://reactome.org/',
            ingest_logo='source-reactome.png',
            license_url=None,
            data_rights='https://reactome.org/license/'
            # file_handle=None
        )
        # gaf evidence code mapping is built in parse(), after the file is fetched.
        self.gaf_eco = {}

    def fetch(self, is_dl_forced=False):
        """
        Override Source.fetch()
        Fetches resources from reactome using the Reactome.files dictionary
        Args:
            :param is_dl_forced (bool): Force download
        Returns:
            :return None
        """
        self.get_files(is_dl_forced)

    def parse(self, limit=None):
        """
        Override Source.parse()
        Args:
            :param limit (int, optional) limit the number of rows processed
        Returns:
            :return None
        """
        src_key = 'gaf-eco-mapping'
        yamlfile = '/'.join((self.rawdir, self.files[src_key]['file']))
        with open(yamlfile, 'r') as yfh:
            self.gaf_eco = yaml.safe_load(yfh)

        if limit is not None:
            LOG.info("Only parsing first %d rows", limit)

        self._parse_reactome_association_file(
            'ensembl2pathway', limit, subject_prefix='ENSEMBL', object_prefix='REACT'
        )

        self._parse_reactome_association_file(
            'chebi2pathway', limit, subject_prefix='CHEBI', object_prefix='REACT'
        )

    def _parse_reactome_association_file(
            self,
            src_key,
            limit=None,
            subject_prefix=None,
            object_prefix=None
    ):
        """
        Parse ensembl gene to reactome pathway file
        :param file: file path (not handle)
        :param limit: limit (int, optional) limit the number of rows processed
        :return: None
        """
        src_file = '/'.join((self.rawdir, self.files[src_key]['file']))
        col = self.files[src_key]['columns']

        with open(src_file, 'r') as tsvfile:
            reader = csv.reader(tsvfile, delimiter="\t")
            for row in reader:
                component = row[col.index('component')].strip()
                pathway_id = row[col.index('pathway_id')].strip()
                # pathway_iri = row[col.index('pathway_iri')]
                pathway_label = row[col.index('pathway_label')].strip()
                go_ecode = row[col.index('go_ecode')].strip()
                # species_name = row[col.index('species_name')]

                gene_curie = ':'.join((subject_prefix, component))
                pathway_curie = ':'.join((object_prefix, pathway_id))

                eco_curie = None
                if go_ecode in self.gaf_eco:
                    eco_curie = self.gaf_eco[go_ecode]
                else:
                    LOG.error(
                        'Evidence code %s not found in %s', go_ecode, str(self.gaf_eco))

                self._add_component_pathway_association(
                   gene_curie, pathway_curie, pathway_label, eco_curie)

                if limit is not None and reader.line_num >= limit:
                    break

    def _add_component_pathway_association(
            self, gene_curie, pathway_curie, pathway_label, eco_curie
    ):

        pathway = Pathway(self.graph)
        pathway.addPathway(pathway_curie, pathway_label)
        pathway.addComponentToPathway(gene_curie, pathway_curie)

        association = Assoc(self.graph, self.name)
        association.sub = gene_curie
        association.rel = self.globaltt['involved in']
        association.obj = pathway_curie
        association.set_association_id()
        association.add_evidence(eco_curie)
        association.add_association_to_graph()


text:
#import <Message/MFMessageSortingValue.h>

@interface _MFMessageSortingValueDateSent : MFMessageSortingValue
{
    double _dateSentAsTimeIntervalSince1970;
}

- (double)dateSentAsTimeIntervalSince1970;
- (void)setDateSentAsTimeIntervalSince1970:(double)arg1;
- (id)description;

@end


text:
package org.zalando.stups.fullstop.plugin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.stups.clients.kio.KioOperations;
import org.zalando.stups.fullstop.aws.ClientProvider;
import org.zalando.stups.fullstop.plugin.EC2InstanceContextProvider;
import org.zalando.stups.fullstop.plugin.impl.EC2InstanceContextProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.AmiIdProvider;
import org.zalando.stups.fullstop.plugin.provider.AmiProvider;
import org.zalando.stups.fullstop.plugin.provider.KioApplicationProvider;
import org.zalando.stups.fullstop.plugin.provider.PieroneTagProvider;
import org.zalando.stups.fullstop.plugin.provider.ScmSourceProvider;
import org.zalando.stups.fullstop.plugin.provider.TaupageYamlProvider;
import org.zalando.stups.fullstop.plugin.provider.impl.AmiIdProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.impl.AmiProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.impl.KioApplicationProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.impl.PieroneTagProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.impl.ScmSourceProviderImpl;
import org.zalando.stups.fullstop.plugin.provider.impl.TaupageYamlProviderImpl;
import org.zalando.stups.pierone.client.PieroneOperations;

import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

@Configuration
public class EC2InstanceContextConfig {

    @Autowired
    private KioOperations kioOperations;

    @Autowired
    private Function<String, PieroneOperations> pieroneOperationsProvider;

    @ConditionalOnMissingBean
    @Bean
    EC2InstanceContextProvider contextProvider(final ClientProvider clientProvider,
                                               @Value("${fullstop.plugins.ami.taupageNamePrefix}") final String taupageNamePrefix,
                                               @Value("${fullstop.plugins.ami.taupageOwners}") final String taupageOwners) {
        return new EC2InstanceContextProviderImpl(
                clientProvider,
                amiIdProvider(),
                amiProvider(),
                taupageYamlProvider(),
                taupageNamePrefix,
                Stream.of(taupageOwners.split(",")).filter(s -> !s.isEmpty()).collect(toList()),
                kioApplicationProvider(),
                pieroneTagProvider(),
                scmSourceProvider());
    }

    @Bean
    AmiIdProvider amiIdProvider() {
        return new AmiIdProviderImpl();
    }

    @Bean
    AmiProvider amiProvider() {
        return new AmiProviderImpl();
    }

    @Bean
    TaupageYamlProvider taupageYamlProvider() {
        return new TaupageYamlProviderImpl();
    }

    @Bean
    KioApplicationProvider kioApplicationProvider() {
        return new KioApplicationProviderImpl(kioOperations);
    }

    @Bean
    PieroneTagProvider pieroneTagProvider() {
        return new PieroneTagProviderImpl(pieroneOperationsProvider);
    }

    @Bean
    ScmSourceProvider scmSourceProvider() {
        return new ScmSourceProviderImpl(pieroneOperationsProvider);
    }
}


text:
#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_
#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_

#include "utils/macro.h"
#include "utils/timer_task.h"

namespace timer {

/**
 * @brief The TaskImpl is proxy-template class for calling callback from Timer
 */
template <typename Trackable>
class TimerTaskImpl : public TimerTask {
 public:
  typedef void (Trackable::*CallbackFunction)();

  TimerTaskImpl(Trackable* trackable, CallbackFunction callback);
  ~TimerTaskImpl();
  /**
   * @brief run method which call callback function from callee
   */
  void run() const OVERRIDE;

 private:
  Trackable* callee_;
  CallbackFunction callback_;
};

// Implementation
template <typename Trackable>
TimerTaskImpl<Trackable>::TimerTaskImpl(Trackable* trackable,
                                        CallbackFunction callback)
    : callee_(trackable), callback_(callback) {}

template <typename Trackable>
TimerTaskImpl<Trackable>::~TimerTaskImpl() {
  callee_ = NULL;
}

template <typename Trackable>
void TimerTaskImpl<Trackable>::run() const {
  DCHECK_OR_RETURN_VOID(callee_ && callback_)
  (callee_->*callback_)();
}
}  // namespace timer

#endif  // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_


text:
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl

import pytest

from .. import Strict

class TestDescriptor:

    from ..base import Descriptor

    class Dummy:
        pass

    def test_ctor(self):
        d = self.Descriptor('key', size=1)
        assert d.name == 'key'
        assert d.size == 1

    def test_setter(self):
        d = self.Descriptor('key')
        client = self.Dummy()
        d.__set__(client, 42)
        assert client.key == 42

@pytest.fixture
def boolean():

    from ..base import Bool

    class Dummy(Strict):

        value = Bool()

    return Dummy()

class TestBool:

    def test_valid(self, boolean):
        boolean.value = True
        assert boolean.value

    @pytest.mark.parametrize("value, expected",
                             [
                                 (1, True,),
                                 (0, False),
                                 ('true', True),
                                 ('false', False),
                                 ('0', False),
                                 ('f', False),
                                 ('', False),
                                 ([], False)
                             ]
                              )
    def test_cast(self, boolean, value, expected):
        boolean.value = value
        assert boolean.value == expected

def test_nested():
    from ..base import Bool

    class DummyNested(Strict):

        value = Bool(nested=True)

    dummy = DummyNested()
    dummy.value = True
    assert dummy.__class__.value.nested == True

@pytest.fixture
def integer():

    from ..base import Integer

    class Dummy(Strict):

        value = Integer()

    return Dummy()

class TestInt:

    def test_valid(self, integer):
        integer.value = 4
        assert integer.value == 4

    @pytest.mark.parametrize("value", ['a', '4.5', None])
    def test_invalid(self, integer, value):
        with pytest.raises(TypeError):
            integer.value = value

    @pytest.mark.parametrize("value, expected",
                             [
                                 ('4', 4),
                                 (4.5, 4),
                             ])
    def test_cast(self, integer, value, expected):
        integer.value = value
        assert integer.value == expected

@pytest.fixture
def float():

    from ..base import Float

    class Dummy(Strict):

        value = Float()

    return Dummy()

class TestFloat:

    def test_valid(self, float):
        float.value = 4
        assert float.value == 4

    @pytest.mark.parametrize("value", ['a', None])
    def test_invalid(self, float, value):
        with pytest.raises(TypeError):
            float.value = value

    @pytest.mark.parametrize("value, expected",
                             [
                                 ('4.5', 4.5),
                                 (4.5, 4.5),
                                 (4, 4.0),
                             ])
    def test_cast(self, float, value, expected):
        float.value = value
        assert float.value == expected

@pytest.fixture
def allow_none():

    from ..base import Float

    class Dummy(Strict):

        value = Float(allow_none=True)

    return Dummy()

class TestAllowNone:

    def test_valid(self, allow_none):
        allow_none.value = None
        assert allow_none.value is None

@pytest.fixture
def maximum():
    from ..base import Max

    class Dummy(Strict):

        value = Max(max=5)

    return Dummy()

class TestMax:

    def test_ctor(self):
        from ..base import Max

        with pytest.raises(TypeError):
            class Dummy(Strict):
                value = Max()

    def test_valid(self, maximum):
        maximum.value = 4
        assert maximum.value == 4

    def test_invalid(self, maximum):
        with pytest.raises(ValueError):
            maximum.value = 6

@pytest.fixture
def minimum():
    from ..base import Min

    class Dummy(Strict):

        value = Min(min=0)

    return Dummy()

class TestMin:

    def test_ctor(self):
        from ..base import Min

        with pytest.raises(TypeError):
            class Dummy(Strict):
                value = Min()

    def test_valid(self, minimum):
        minimum.value = 2
        assert minimum.value == 2

    def test_invalid(self, minimum):
        with pytest.raises(ValueError):
            minimum.value = -1

@pytest.fixture
def min_max():
    from ..base import MinMax

    class Dummy(Strict):

        value = MinMax(min=-1, max=1)

    return Dummy()

class TestMinMax:

    def test_ctor(self):
        from ..base import MinMax

        with pytest.raises(TypeError):

            class Dummy(Strict):
                value = MinMax(min=-10)

        with pytest.raises(TypeError):

            class Dummy(Strict):
                value = MinMax(max=10)

    def test_valid(self, min_max):
        min_max.value = 1
        assert min_max.value == 1

    def test_invalid(self, min_max):
        with pytest.raises(ValueError):
            min_max.value = 2

@pytest.fixture
def set():
    from ..base import Set

    class Dummy(Strict):

        value = Set(values=[1, 'a', None])

    return Dummy()

class TestValues:

    def test_ctor(self):
        from ..base import Set

        with pytest.raises(TypeError):
            class Dummy(Strict):

                value = Set()

    def test_valid(self, set):
        set.value = 1
        assert set.value == 1

    def test_invalid(self, set):
        with pytest.raises(ValueError):
            set.value = 2

def test_noneset():
    from ..base import NoneSet
    class Dummy(Strict):

        value = NoneSet(values=[1, 2, 3])

    obj = Dummy()
    obj.value = 'none'
    assert obj.value is None
    with pytest.raises(ValueError):
        obj.value = 5

@pytest.fixture
def ascii():

    from ..base import ASCII

    class Dummy(Strict):

        value = ASCII()

    return Dummy()

class TestASCII:

    def test_valid(self, ascii):
        ascii.value = b'some text'
        assert ascii.value == b'some text'

    value = b'\xc3\xbc'.decode("utf-8")
    @pytest.mark.parametrize("value",
                             [
                                 value,
                                 10,
                                 []
                             ]
                             )
    def test_invalid(self, ascii, value):
        with pytest.raises(TypeError):
            ascii.value = value

@pytest.fixture
def string():

    from ..base import String

    class Dummy(Strict):

        value = String()

    return Dummy()

class TestString:

    def test_valid(self, string):
        value = b'\xc3\xbc'.decode("utf-8")
        string.value = value
        assert string.value == value

    def test_invalid(self, string):
        with pytest.raises(TypeError):
            string.value = 5

@pytest.fixture
def Tuple():
    from ..base import Tuple

    class Dummy(Strict):

        value = Tuple()

    return Dummy()

class TestTuple:

    def test_valid(self, Tuple):
        Tuple.value = (1, 2)
        assert Tuple.value == (1, 2)

    def test_invalid(self, Tuple):
        with pytest.raises(TypeError):
            Tuple.value = [1, 2, 3]

@pytest.fixture
def Length():
    from ..base import Length

    class Dummy(Strict):

        value = Length(length=4)

    return Dummy()

class TestLength:

    def test_valid(self, Length):
        Length.value = "this"

    def test_invalid(self, Length):
        with pytest.raises(ValueError):
            Length.value = "2"


text:
#ifndef OVR_CAPI_HMDRenderState_h
#define OVR_CAPI_HMDRenderState_h

#include "../OVR_CAPI.h"
#include "../Kernel/OVR_Math.h"
#include "../Util/Util_Render_Stereo.h"

namespace OVR { namespace CAPI {

using namespace OVR::Util::Render;

//-------------------------------------------------------------------------------------
// ***** HMDRenderState

// Combines all of the rendering setup information about one HMD.

class HMDRenderState : public NewOverrideBase
{
    // Quiet assignment compiler warning.
    void operator = (const HMDRenderState&) { }
public:

    HMDRenderState(ovrHmd hmd, Profile* userProfile, const OVR::HMDInfo& hmdInfo);
    virtual ~HMDRenderState();

    // *** Rendering Setup

    // Delegated access APIs
    ovrHmdDesc GetDesc();
    ovrSizei   GetFOVTextureSize(int eye, ovrFovPort fov, float pixelsPerDisplayPixel);

    ovrEyeRenderDesc calcRenderDesc(ovrEyeType eyeType, const ovrFovPort& fov);

    void       setupRenderDesc(ovrEyeRenderDesc eyeRenderDescOut[2],
                               const ovrFovPort eyeFovIn[2]);
public:

    // HMDInfo shouldn't change, as its string pointers are passed out.
    ovrHmd                  HMD;
    const OVR::HMDInfo&     HMDInfo;

    //const char*             pLastError;

    HmdRenderInfo            RenderInfo;
    DistortionRenderDesc     Distortion[2];
    ovrEyeRenderDesc         EyeRenderDesc[2];

    // Clear color used for distortion
    float                    ClearColor[4];

    // Pose at which last time the eye was rendered, as submitted by EndEyeRender.
    ovrPosef                 EyeRenderPoses[2];

    // Capabilities passed to Configure.
    unsigned                 EnabledHmdCaps;
    unsigned                 DistortionCaps;
};

}} // namespace OVR::CAPI

#endif // OVR_CAPI_HMDState_h