text:
<?php

namespace IonAuth\IonAuth\Entities;

class LoginAttempt
{

    private $id;

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

    /**
     * Function: increaseLoginAttempts()
     *
     * increase_login_attempts
     * Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)
     *
     * @access public
     * @param  string $identity
     * @return bool
     **/
    public function increaseLoginAttempts($identity)
    {
      if ($this->config->get('trackLoginAttempts')) {
        $ipAddress = $this->_prepareIp($_SERVER['REMOTE_ADDR']);

        return $this->db->insert(
          $this->tables['loginAttempts'],
          ['ip_address' => $ipAddress, 'login' => $identity, 'time' => time()]
        );
      }
      return false;
    }

    /**
     * clear_login_attempts
     *
     * Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)
     *
     * @access public
     * @param  string $identity
     * @param  $expire_period
     *
     * @return bool
     **/
    public function clearLoginAttempts($identity, $expire_period = 86400)
    {
        if ($this->config->get('trackLoginAttempts')) {
            $ipAddress = $this->_prepareIp($_SERVER['REMOTE_ADDR']);

            $this->db->where(['ip_address' => $ipAddress, 'login' => $identity]);
            // Purge obsolete login attempts
            $this->db->or_where('time <', time() - $expire_period, false);

            return $this->db->delete($this->tables['loginAttempts']);
        }
        return false;
    }

    /**
     * Function: getNumberOfAttempts()
     *
     * Get number of attempts to login occured from given IP-address or identity
     * Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)
     *
     * @param    string, $user
     * @return   int
     */
    function getNumberOfAttempts(User $user)
    {
        if ($this->config->get('trackLoginAttempts')) {
            $ipAddress = $this->_prepareIp($_SERVER['REMOTE_ADDR']);

            $this->db->select('1', false);
            $this->db->where('ip_address', $ipAddress);
            if (strlen($identity) > 0) {
                $this->db->or_where('login', $identity);
            }

            $qres = $this->db->get($this->tables['loginAttempts']);
            return count($qres);
        }
        return 0;
    }

    /**
     * getLastAttemptTime
     *
     * Get the last login attempt from a user.
     *
     * @access   public
     * @param    string $user
     */
    public function getLastAttemptTime(User $user)
    {
        if ($this->config->get('trackLoginAttempts'))
        {
            $ipAddress = $this->_prepareIp($_SERVER['REMOTE_ADDR']);

            $this->db->select_max('time');
            $this->db->where('ip_address', $ipAddress);
            if (strlen($identity) > 0)
            {
                $this->db->or_where('login', $identity);
            }
            $qres = $this->db->get($this->tables['loginAttempts'], 1);

            if (count($qres) > 0)
            {
                return $qres->first()->time;
            }
        }
        return 0;
    }

    /**
     * is_max_login_attempts_exceeded
     * Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)
     *
     * @access public
     * @param  string $identity
     * @return boolean
     **/
    public function isMaxLoginAttemptsExceeded()
    {
        if ($this->config->get('trackLoginAttempts'))
        {
            $maxAttempts = $this->config->get('maximumLoginAttempts');
            if ($maxAttempts > 0)
            {
                $attempts = $this->getAttemptsNum();
                return $attempts >= $maxAttempts;
            }
        }
        return false;
    }

    /**
     *
     */
    /**
     * getIpAddress
     *
     * get the ip address of the user.
     *
     * @access public
     * @todo   write the logic
     */
    public function getIpAddress()
    {

    }
}

redpajama_set_name: RedPajamaGithub


text:
from connection_manager import ConnectionManager
from query import Query
from assertion import Assertion

__version__ = '0.6'

class DatabaseLibrary(ConnectionManager, Query, Assertion):
    """
    Database Library contains utilities meant for Robot Framework's usage.

    This can allow you to query your database after an action has been made to verify the results.

    This is `compatible*` with any Database API Specification 2.0 module.

    References:

     + Database API Specification 2.0 - http://www.python.org/dev/peps/pep-0249/

     + Lists of DB API 2.0 - http://wiki.python.org/moin/DatabaseInterfaces

     + Python Database Programming - http://wiki.python.org/moin/DatabaseProgramming/

    Notes:

    `compatible* - or at least theoretically it should be compatible. Currently tested only with postgresql
    (using psycopg2).`

    Example Usage:
    | # Setup |
    | Connect to Database |
    | # Guard assertion (verify that test started in expected state). |
    | Check if not exists in database | select id from person where first_name = 'Franz Allan' and last_name = 'See' |
    | # Drive UI to do some action |
    | Go To | http://localhost/person/form.html | | # From selenium library |
    | Input Text |  name=first_name | Franz Allan | # From selenium library |
    | Input Text |  name=last_name | See | # From selenium library |
    | Click Button | Save | | # From selenium library |
    | # Log results |
    | @{queryResults} | Query | select * from person |
    | Log Many | @{queryResults} |
    | # Verify if persisted in the database |
    | Check if exists in database | select id from person where first_name = 'Franz Allan' and last_name = 'See' |
    | # Teardown |
    | Disconnect from Database |
    """

    ROBOT_LIBRARY_SCOPE = 'GLOBAL'


text:
      <input checked ng-change="showSelectArea()"  ng-model="showSelect" value="student" type="radio" name="optViewScore">Theo học sinh
      <input ng-change="showSelectArea()" ng-model="showSelect" value="subject" type="radio" name="optViewScore">Theo môn học

      <input checked ng-model="semesterID" value="1" type="radio" name="sesmter">Học kì I
      <input ng-model="semesterID" value="2" type="radio" name="sesmter">Học kì II

      <select ng-change="getScoreList()" ng-model="selectedSubject" class="form-control input-sm">
          <option ng-selected="1" value="">Chọn môn học</option>
          <option ng-repeat="subject in subjectList" value="{{subject.subjectID}}">{{subject.subjectName}}</option>
      </select>

      <select ng-change="getScoreList()" ng-model="selectedStudent" class="form-control input-sm">
          <option ng-selected="1" value="">Chọn học sinh</option>
          <option ng-repeat="student in studentList" value="{{student.studentID}}">{{student.name}}</option>
      </select>

Chưa có dữ liệu

Chưa có dữ liệu


text:
clear;
close all;
disp('####### START of the Program ######')
path('COSFIRE/',path);
a = dir('narrative_pics/*jpg');
path('narrative_pics/',path);
path('../COSFIRE_Matlabcode',path);
path('./Gabor',path);
%for i = 3:length(a);
NCOSFIRES=3;
max_response = zeros(5,3);
operator_num = 0;

%%%%%%%%%training%%%%%%%%%%%%%%
% % Once you have selected the operator as good / you save it
% and you apply it over the image from which it was configured
% in order to see the maximum response it can achieve.
max_response=zeros(5,15);

for training_image = 1:5  % get the image lap1 etc

    training_image_prototype = imread(a(training_image).name); % prototype is the image in this case example lap1.jpg
    training_image_prototype = imresize(training_image_prototype,0.3);
    training_image_prototype = preprocessImage(training_image_prototype);

    for variable= 1:15

        % get the operator
        load (['./OUTPUT_FOLDER/operator_' num2str(variable) '.mat'])

        % apply cosfire
        new_matrix = applyCOSFIRE(training_image_prototype, operator );

        % save maximum from the matrix
        max_response(training_image,variable) = max(max(new_matrix))

    end

end
save('max_response.mat', 'max_response') ;
load('config_max_response.mat');


text:
Lists the character's personal, corporation, and alliance contacts.

* __Path:__ ``/char/ContactList.xml.aspx``
* __Cache timer:__ 15 minutes
* __Access mask:__ 16
* __Parameters:__

                Argument
                Type
                Description

                characterID
                long
                ID of character

### Sample Response

```xml
<result>
    <rowset name="contactList" key="contactID" columns="contactID,contactName,standing,contactTypeID,labelMask,inWatchlist">
        <row contactID="3013827" contactName="Nouta Dahiva" standing="0" contactTypeID="1373" labelMask="0" inWatchlist="False" />
        <row contactID="3008933" contactName="Saame Marver" standing="0" contactTypeID="1374" labelMask="0" inWatchlist="False" />
        <row contactID="3013522" contactName="Iya Kattora" standing="0" contactTypeID="1375" labelMask="0" inWatchlist="False" />
        <row contactID="3011405" contactName="Okila Kavas" standing="0" contactTypeID="1376" labelMask="0" inWatchlist="False" />
        <row contactID="3009566" contactName="Rias Luisauir" standing="0" contactTypeID="1377" labelMask="0" inWatchlist="False" />
        <row contactID="147874353" contactName="BIG Games" standing="0" contactTypeID="1378" labelMask="0" inWatchlist="True" />
        <row contactID="196379789" contactName="Chribba" standing="5" contactTypeID="1379" labelMask="0" inWatchlist="False" />
        <row contactID="3017057" contactName="Kaer Aginia" standing="0" contactTypeID="1380" labelMask="0" inWatchlist="False" />
        <row contactID="3018696" contactName="Rantoh Funkaki" standing="0" contactTypeID="1383" labelMask="0" inWatchlist="False" />
        <row contactID="3018931" contactName="Antogase Pandon" standing="0" contactTypeID="1384" labelMask="0" inWatchlist="False" />
        <row contactID="3019364" contactName="Doctor Canius" standing="0" contactTypeID="1385" labelMask="0" inWatchlist="False" />
        <row contactID="3019361" contactName="Keita Eslin" standing="0" contactTypeID="1386" labelMask="0" inWatchlist="False" />
        <row contactID="1488155548" contactName="MD Financial Services" standing="0" contactTypeID="2" labelMask="0" inWatchlist="False" />
        <row contactID="903693898" contactName="Biotronics Inc." standing="10" contactTypeID="2" labelMask="0" inWatchlist="False" />
    </rowset>
    <rowset name="contactLabels" key="labelID" columns="labelID,name" />
    <rowset name="corporateContactList" key="contactID" columns="contactID,contactName,standing,contactTypeID,labelMask">
        <row contactID="111751354" contactName="Mark Hamill" standing="5" contactTypeID="1374" labelMask="0" />
        <row contactID="903693898" contactName="Biotronics Inc." standing="10" contactTypeID="2" labelMask="0" />
        <row contactID="1900696668" contactName="The Initiative." standing="5" contactTypeID="16159" labelMask="0" />
    </rowset>
    <rowset name="corporateContactLabels" key="labelID" columns="labelID,name" />
    <rowset name="allianceContactList" key="contactID" columns="contactID,contactName,standing,contactTypeID,labelMask" />
    <rowset name="allianceContactLabels" key="labelID" columns="labelID,name" />
</result>
```

### Result Data

            Name
            Data type
            Description

            Rowset contactList

            contactID
            long
            The characterID/corporationID of the character/agent/corporation in your contact list.

            contactName
            char
            The name of the contact. For deleted entities this field is empty.

            standing
            int
            The standings you set for this contact (see notes).

            contactTypeID
            long

                Determines the contact type:

                2 = Corporation

                1373-1386 = Character

                16159 = Alliance

            labelMask
            long
            Label(s) from contactLabels associated with this entry.

            inWatchlist
            bool
            Has this entry been added to the character's watchlist? Valid for contactTypeID 1373 to 1386 only.

            Rowset contactLabels

            labelID
            long
            Unique label ID. Multiple labelIDs bitwise combined result in labelMask.

            name
            char
            The label's text.

            Rowset corporateContactList

                Same as contactList with the exception of inWatchlist missing.

            Rowset corporateContactLabels

                Same as contactLabels.

            Rowset allianceContactList

                Same as contactList with the exception of inWatchlist missing.

            Rowset allianceContactLabels

                Same as contactLabels.

### Notes

* Returns the character's contact and watch lists, __incl. agents__ and respective standings set by
    the character. Also includes the character's corporation and/or alliance contacts. See the
    [Standings API](char_standings.md) for standings towards the character from agents and
    NPC entities.


text:
namespace EngineLayer
{
    public enum InitiatorMethionineBehavior
    {
        Undefined,
        Retain,
        Cleave,
        Variable
    }
}


text:
title: Drive DDoS String patcher tool
author: g3nuin3
layout: post
description: Decrypting a string obfuscation in the Drive DDoS malware
---
Some time ago a friend and I wrote a little tool to do some automatic patching of a DDos related malware called Drive. I've been meaning to write this post for a while to release this tool with accompanying source but time was never on my side. But, late is better than never right? 🙂

This tool is aimed to patch any variant of the Drive payload to connect to the desired C2 server for internal testing.

It currently does not patch the authentication yet. That will come soon enough.

The source code is cross platform and should work on Linux/MacOSX/Windows.

Basic compilation syntax is:

> **g++ -std=c++11 -v -m32 -o driveedit ini.c scandecryptor.cpp**

gcc can also be used.

There are two methods to get the string information inside of Drive binaries. The strings are structured in a high level language format like so:

> _struct strings{

> int val = 0xFFFFFFFF;

> size_t len;

> char[] str;

> };_

Where 0xFFFFF is always found before the string information. In Olly this looks like this:

    Drive string structure as seen in debugger

I think my initial research revealed that this was the way that Delphi stores its internal strings, since the malware is written in Delphi. Someone can correct me if Im wrong here.

Notice the 0xFFFFFFFF, then the length, then the string itself. the tool uses this to find the pertinent strings inside the binary. Alternatively, you can use strings to dump all strings inside the binary and pick which string you want to decrypt and replace.

[](http://bangreverse.me/blog/wp-content/uploads/2014/05/Strings.png)

To use the tool, you do two things. First, you find the string you'd like to replace. Afterwords you need to get its decrypted form. For instance, if we want to decrypt the string: "kkm,|ampqcwo{p". We can use the command:

** _./driveedit d "kkm,|ampqcwo{p"_**

(the quotes is typically required for strings with special characters such as pipes or quotes, else it breaks the parser)

This will give us the decrypted string.

> **Decrypted string: systemskey.ini**

Now that we have the decrypted string, we want to replace it with our own string, we put this information inside of the patterns.ini file, like this:

> **find=systemskey.ini

> replace=myconf.ini**

Once thats done we're ready to make the patch. YOU CAN HAVE SEVERAL find/replace patterns in the ini file.

> **./driveedit patterns.ini drive1.exe**

The format of the command to run the patch is ./drivetool \[inifile\] \[drive_binary\]

The tool will make the given patches, then output the patched binary appended with .out suffix.

> **account$ ./driveedit patterns.ini drive1.exe

> Replacing string at 42060 with ‘systemskey.ini’ with ‘myconf.ini’

> 1 replacements were written to drive1.exe.out**

Heres what the two will look like after the patching, look at line 353. Replaced will have our new encrypted string "myconf.ini" :

    comparing original and patched file

The tool is also capable of dumping all the strings that match the structure described above. Use the 'l' argument to dump these strings on any drive malware variant.

> **./driveedit l drive1.exe**

This command will list all possible strings in the binary that conform to the string structure mentioned in the beginning of this post. It is a naive approach because there are alot of useless strings that get dumped, but it will also give the decrypted forms of any possibly encrypted strings inside of the binary as well. So it can speed the process of generating the ini file to patch the strings of interest.

Alright well without any more waste of characters, I have publicly hosted the source code on bitbucket and you can find it and play with it to your hearts content.

 https://bitbucket.org/genuine_/driveddos-string-tool

The repo includes a sample patterns.ini file.

Here are some md5 hashes of Drive malware you can test the tool against:

322a9bf00689e7e978be32cdade032ed

63a3fbba0070f9ff56ea83dc76ef9e9e

3bbefd483564bfd2172f7963970fa784

Have fun and happy reversing,

gen


text:
void CP_ICACHE_FLASH_ATTR util_bin2hex (char *cd, char* label, unsigned char * x, int len );
void CP_ICACHE_FLASH_ATTR util_debug_bin2hex(char* label, unsigned char * x, int len,  char* file, const char* func, int line );
#define util_print_bin2hex( a, b ) ((void)0)

extern int _GLOBAL_DEBUG;
//extern macaddr_t macAddr;

#ifdef ESP8266
#include "ets_sys.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"
void* calloc_wrapper(size_t len, size_t size);

#define socklen_t int
#define malloc os_malloc
#define calloc(len,size) calloc_wrapper(len,size);
#define free os_free
#define arc4random_uniform(x) os_random() % x
#define printf(...) os_printf( __VA_ARGS__ )
#define sprintf(...) os_sprintf( __VA_ARGS__ )
#define sbuf_printf(...) os_sprintf( __VA_ARGS__ )

extern int os_printf_plus(const char * format, ...);

#define CHATFABRIC_PRINT(msg) os_printf("%s\n", msg );
#define CHATFABRIC_DEBUG(d, msg) if (d) os_printf("[DEBUG][%s:%s:%d] %s\n", __FILE__, __FUNCTION__, __LINE__, msg );
#define CHATFABRIC_DEBUG_FMT(d, fmt, ...) if (d) os_printf("[DEBUG][%s:%s:%d] " fmt "\n", __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__ );
#define CHATFABRIC_DEBUG_FMT2(d, func, line, fmt, ...) if (d) os_printf("[DEBUG][%s:%s:%d] " fmt "\n", __FILE__, func, line, __VA_ARGS__ );
#define CHATFABRIC_DEBUG_B2H(d, label, x, len) if (d) util_debug_bin2hex(label, x,len, __FILE__, __FUNCTION__, __LINE__ );

#else

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>

#define CHATFABRIC_PRINT(msg) printf("%s\n", msg );
#define CHATFABRIC_DEBUG(d, msg) if (d) printf("[DEBUG][%s:%s:%d] %s\n", __FILE__, __FUNCTION__, __LINE__, msg );
#define CHATFABRIC_DEBUG_FMT(d, fmt, ...) if (d) printf("[DEBUG][%s:%s:%d] " fmt "\n", __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__ );
#define CHATFABRIC_DEBUG_FMT2(d, func, line, fmt, ...) if (d) printf("[DEBUG][%s:%s:%d] " fmt "\n", __FILE__, func, line, __VA_ARGS__ );
#define CHATFABRIC_DEBUG_B2H(d, label, x, len) if (d) util_debug_bin2hex(label, x,len, __FILE__, __FUNCTION__, __LINE__ );

#endif

#endif


text:
import java.util.*;
public class DicionarioSindarin
{
    public static void main(String[] args){
        try{
            int resultado = 13/0;
        }catch (ArithmeticException ae){
            System.out.println("Tipo ArithmeticException");
            throw ae;
        }catch (Exception e){
            System.out.println("Tipo Exception");
        }
        /*Scanner scanner = new Scanner(System.in);
        System.out.println("\n\n\n\nEscolha a linguagem: ");
        System.out.println("[P]ortuguês [I]nglês");
        String idioma = scanner.nextLine();
        TradutorSindarin tradutor = criarTradutor(idioma);
        String palavra = scanner.nextLine();
        System.out.println(palavra + " significa " + tradutor.traduzir(palavra));*/
        // rodarExemplosHashMap();
    }

    private static TradutorSindarin criarTradutor(String idioma){
        TradutorSindarin tradutor = null;
        switch (idioma.toLowerCase()){
            case "i":
                tradutor = new SindarinParaIngles();
            break;
            default:
                tradutor = new SindarinParaPortugues();
            break;
        }
        return tradutor;
    }

    private static void rodarExemplosHashMap(){
        //cria um hashmap de strings
        HashMap<String, String> dicionarioSindarin = new HashMap<>();
        //adiciona valores e chaves no hashmap
        dicionarioSindarin.put("terra","amar");
        dicionarioSindarin.put("fogo","naur");
        dicionarioSindarin.put("fire","naur");
        dicionarioSindarin.put("vento","gwaew");
        dicionarioSindarin.put("água","nen");
        dicionarioSindarin.put("coração","gûr");

        String terraEmSindarin = dicionarioSindarin.get("terra");
        //sobrepoe um valor de mesma chave
        dicionarioSindarin.put("água","nîn");
        //removea chave e o valor
        dicionarioSindarin.remove("água");
        //está vazio?
        boolean estaVazio = dicionarioSindarin.isEmpty();
        //tamanho
        int tamanhoDePares = dicionarioSindarin.size();
        //contém chave?
        boolean contemAgua = dicionarioSindarin.containsKey("água");
        //contém valor?
        boolean contemNaur = dicionarioSindarin.containsValue("naur");
        //Mesmo HashCode
        dicionarioSindarin.put("FB","facebook");
        dicionarioSindarin.put("Ea","badoo");

        for(Map.Entry<String,String> chaveValor : dicionarioSindarin.entrySet()){
            System.out.println("K: " + chaveValor.getKey() + "_ V: " + chaveValor.getValue());
        }
    }
}


text:
[![Build Status](https://travis-ci.org/xrexonx/gulp-copy.svg?branch=master)](https://travis-ci.org/xrexonx/gulp-copy)
[![npm version](https://badge.fury.io/js/gulp-copy-rex.svg)](https://badge.fury.io/js/gulp-copy-rex)
[![Downloads](http://img.shields.io/npm/dm/gulp-copy-rex.svg)](https://www.npmjs.com/package/gulp-copy-rex)

Enables you to copy or transfer files on your gulp task (gulpfile.js).
## Install

```
$ npm install --save-dev gulp-copy-rex
```
[![NPM](https://nodei.co/npm/gulp-copy-rex.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/gulp-copy-rex/)

## Usage

Can use this inside of your any gulp tasks or you can create a specific tasks for it.

```js
var copy = require('gulp-copy-rex');

gulp.task('copy', function () {

	//array of files ~ array / object
    var files = [
  			'./node_modules/someVendors/vendors.js',
  			'./bower_components/someVendors2/vendors2.js',
  			'./bower_components/someVendors3/vendors3.js',
  			];

  	or

  	//single file ~ string
  	var files = './bower_components/angular/angular.min.js';

    copy(files,'yourDestination/folder');
});

```

Using options as 3rd param ~ Minify and Concat files using [gulp-uglify](https://github.com/terinjokes/gulp-uglify) and [gulp-concat](https://github.com/contra/gulp-concat) (not applicable to CSS files)
```js
    var opts = {
    	min:true, //minify ~ default false
    	concat:true, //concat ~ default false
    	filename:'app' //set filename
    }

    copy(files, dist, opts);
});

```

## Run Task

```
$ gulp copy
```

## License

MIT © [Rexon A. De los Reyes](http://xrexonx.github.io)

#### Thanks and Enjoy. Goodspeed. ~ xrexonx


text:
namespace DAVA
{
String VisibleValueDescription(const Any& value)
{
    return value.Cast<bool>() == true ? "Visible" : "Invisible";
}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package recyclapp;

import gui.RecyclApp;
import javax.swing.SwingUtilities;

/**
 * Début du programme RecyclApp
 *
 * @author Vincent
 */
public class Main
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        RecyclApp app = new RecyclApp();

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                app.setVisible(true);
            }
        });
    }

}


text:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("mbbsd", ["mbbsd.pyx"])]

setup(
  name = 'ptt BBS server',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)


text:
<!doctype html>
<meta charset=utf-8>
<title>RTCPeerConnection.prototype.setRemoteDescription - offer</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="RTCPeerConnection-helper.js"></script>
<script>
  'use strict';

  // The following helper functions are called from RTCPeerConnection-helper.js:
  //   assert_session_desc_similar()
  //   generateAudioReceiveOnlyOffer

  /*
    4.3.2.  Interface Definition
      [Constructor(optional RTCConfiguration configuration)]
      interface RTCPeerConnection : EventTarget {
        Promise<void>                      setRemoteDescription(
            RTCSessionDescriptionInit description);

        readonly attribute RTCSessionDescription? remoteDescription;
        readonly attribute RTCSessionDescription? currentRemoteDescription;
        readonly attribute RTCSessionDescription? pendingRemoteDescription;
        ...
      };

    4.6.2.  RTCSessionDescription Class
      dictionary RTCSessionDescriptionInit {
        required RTCSdpType type;
                 DOMString  sdp = "";
      };

    4.6.1.  RTCSdpType
      enum RTCSdpType {
        "offer",
        "pranswer",
        "answer",
        "rollback"
      };
   */

  /*
    4.3.1.6.  Set the RTCSessionSessionDescription
      2.2.3.  Otherwise, if description is set as a remote description, then run one of
              the following steps:
        - If description is of type "offer", set connection.pendingRemoteDescription
          attribute to description and signaling state to have-remote-offer.
   */

  promise_test(t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    pc1.createDataChannel('datachannel');

    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());

    const states = [];
    pc2.addEventListener('signalingstatechange', () => states.push(pc2.signalingState));

    return pc1.createOffer()
     .then(offer => {
      return pc2.setRemoteDescription(offer)
      .then(() => {
        assert_equals(pc2.signalingState, 'have-remote-offer');
        assert_session_desc_similar(pc2.remoteDescription, offer);
        assert_session_desc_similar(pc2.pendingRemoteDescription, offer);
        assert_equals(pc2.currentRemoteDescription, null);

        assert_array_equals(states, ['have-remote-offer']);
      });
    });
  }, 'setRemoteDescription with valid offer should succeed');

  promise_test(t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    pc1.createDataChannel('datachannel');

    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());

    const states = [];
    pc2.addEventListener('signalingstatechange', () => states.push(pc2.signalingState));

    return pc1.createOffer()
    .then(offer => {
      return pc2.setRemoteDescription(offer)
      .then(() => pc2.setRemoteDescription(offer))
      .then(() => {
        assert_equals(pc2.signalingState, 'have-remote-offer');
        assert_session_desc_similar(pc2.remoteDescription, offer);
        assert_session_desc_similar(pc2.pendingRemoteDescription, offer);
        assert_equals(pc2.currentRemoteDescription, null);

        assert_array_equals(states, ['have-remote-offer']);
      });
    });
  }, 'setRemoteDescription multiple times should succeed');

  promise_test(t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    pc1.createDataChannel('datachannel');

    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());

    const states = [];
    pc2.addEventListener('signalingstatechange', () => states.push(pc2.signalingState));

    return pc1.createOffer()
    .then(offer1 => {
      return pc1.setLocalDescription(offer1)
       .then(()=> {
        return generateAudioReceiveOnlyOffer(pc1)
        .then(offer2 => {
          assert_session_desc_not_similar(offer1, offer2);

          return pc2.setRemoteDescription(offer1)
          .then(() => pc2.setRemoteDescription(offer2))
          .then(() => {
            assert_equals(pc2.signalingState, 'have-remote-offer');
            assert_session_desc_similar(pc2.remoteDescription, offer2);
            assert_session_desc_similar(pc2.pendingRemoteDescription, offer2);
            assert_equals(pc2.currentRemoteDescription, null);

            assert_array_equals(states, ['have-remote-offer']);
          });
        });
      });
    });
  }, 'setRemoteDescription multiple times with different offer should succeed');

  /*
    4.3.1.6.  Set the RTCSessionSessionDescription
      2.1.4.  If the content of description is not valid SDP syntax, then reject p with
              an RTCError (with errorDetail set to "sdp-syntax-error" and the
              sdpLineNumber attribute set to the line number in the SDP where the syntax
              error was detected) and abort these steps.
   */
  promise_test(t => {
    const pc = new RTCPeerConnection();

    t.add_cleanup(() => pc.close());

    return pc.setRemoteDescription({
      type: 'offer',
      sdp: 'Invalid SDP'
    })
    .then(() => {
      assert_unreached('Expect promise to be rejected');
    }, err => {
      assert_equals(err.errorDetail, 'sdp-syntax-error',
        'Expect error detail field to set to sdp-syntax-error');

      assert_true(err instanceof RTCError,
        'Expect err to be instance of RTCError');
    });
  }, 'setRemoteDescription(offer) with invalid SDP should reject with RTCError');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    t.add_cleanup(() => pc2.close());
    await pc1.setLocalDescription(await pc1.createOffer());
    await pc1.setRemoteDescription(await pc2.createOffer());
    assert_equals(pc1.signalingState, 'have-remote-offer');
  }, 'setRemoteDescription(offer) from have-local-offer should roll back and succeed');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    t.add_cleanup(() => pc2.close());
    await pc1.setLocalDescription(await pc1.createOffer());
    const p = pc1.setRemoteDescription(await pc2.createOffer());
    await new Promise(r => pc1.onsignalingstatechange = r);
    assert_equals(pc1.signalingState, 'stable');
    assert_equals(pc1.pendingLocalDescription, null);
    assert_equals(pc1.pendingRemoteDescription, null);
    await new Promise(r => pc1.onsignalingstatechange = r);
    assert_equals(pc1.signalingState, 'have-remote-offer');
    assert_equals(pc1.pendingLocalDescription, null);
    assert_equals(pc1.pendingRemoteDescription.type, 'offer');
    await p;
  }, 'setRemoteDescription(offer) from have-local-offer fires signalingstatechange twice');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());

    pc1.addTransceiver('audio', { direction: 'recvonly' });
    const srdPromise = pc2.setRemoteDescription(await pc1.createOffer());

    assert_equals(pc2.signalingState, "stable", "signalingState should not be set synchronously after a call to sRD");

    assert_equals(pc2.pendingRemoteDescription, null, "pendingRemoteDescription should not be set synchronously after a call to sRD");
    assert_equals(pc2.currentRemoteDescription, null, "currentRemoteDescription should not be set synchronously after a call to sRD");

    const statePromise = new Promise(resolve => {
      pc2.onsignalingstatechange = () => {
        resolve(pc2.signalingState);
      }
    });

    const raceValue = await Promise.race([statePromise, srdPromise]);
    assert_equals(raceValue, "have-remote-offer", "signalingstatechange event should fire before sRD resolves");
    assert_not_equals(pc2.pendingRemoteDescription, null, "pendingRemoteDescription should be updated before the signalingstatechange event");
    assert_equals(pc2.pendingRemoteDescription.type, "offer");
    assert_equals(pc2.pendingRemoteDescription.sdp, pc2.remoteDescription.sdp);
    assert_equals(pc2.currentRemoteDescription, null, "currentRemoteDescription should not be set after a call to sRD(offer)");

    await srdPromise;
  }, "setRemoteDescription(offer) in stable should update internal state with a queued task, in the right order");

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());

    pc2.addTransceiver('audio', { direction: 'recvonly' });
    await pc2.setLocalDescription(await pc2.createOffer());

    // Implicit rollback!
    pc1.addTransceiver('audio', { direction: 'recvonly' });
    const srdPromise = pc2.setRemoteDescription(await pc1.createOffer());

    assert_equals(pc2.signalingState, "have-local-offer", "signalingState should not be set synchronously after a call to sRD");

    assert_equals(pc2.pendingRemoteDescription, null, "pendingRemoteDescription should not be set synchronously after a call to sRD");
    assert_not_equals(pc2.pendingLocalDescription, null, "pendingLocalDescription should not be set synchronously after a call to sRD");
    assert_equals(pc2.pendingLocalDescription.type, "offer");
    assert_equals(pc2.pendingLocalDescription.sdp, pc2.localDescription.sdp);

    // First, we should go through stable (the implicit rollback part)
    const stablePromise = new Promise(resolve => {
      pc2.onsignalingstatechange = () => {
        resolve(pc2.signalingState);
      }
    });

    let raceValue = await Promise.race([stablePromise, srdPromise]);
    assert_equals(raceValue, "stable", "signalingstatechange event should fire before sRD resolves");
    assert_equals(pc2.pendingLocalDescription, null, "pendingLocalDescription should be updated before the signalingstatechange event");
    assert_equals(pc2.pendingRemoteDescription, null, "pendingRemoteDescription should be updated before the signalingstatechange event");

    const haveRemoteOfferPromise = new Promise(resolve => {
      pc2.onsignalingstatechange = () => {
        resolve(pc2.signalingState);
      }
    });

    raceValue = await Promise.race([haveRemoteOfferPromise, srdPromise]);
    assert_equals(raceValue, "have-remote-offer", "signalingstatechange event should fire before sRD resolves");
    assert_not_equals(pc2.pendingRemoteDescription, null, "pendingRemoteDescription should be updated before the signalingstatechange event");
    assert_equals(pc2.pendingRemoteDescription.type, "offer");
    assert_equals(pc2.pendingRemoteDescription.sdp, pc2.remoteDescription.sdp);
    assert_equals(pc2.pendingLocalDescription, null, "pendingLocalDescription should be updated before the signalingstatechange event");

    await srdPromise;
  }, "setRemoteDescription(offer) in have-local-offer should update internal state with a queued task, in the right order");

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    t.add_cleanup(() => pc2.close());
    await pc1.setLocalDescription(await pc1.createOffer());
    const offer = await pc2.createOffer();
    const p1 = pc1.setLocalDescription({type: 'rollback'});
    await new Promise(r => pc1.onsignalingstatechange = r);
    assert_equals(pc1.signalingState, 'stable');
    const p2 = pc1.addIceCandidate();
    const p3 = pc1.setRemoteDescription(offer);
    await promise_rejects_dom(t, 'InvalidStateError', p2);
    await p1;
    await p3;
    assert_equals(pc1.signalingState, 'have-remote-offer');
  }, 'Naive rollback approach is not glare-proof (control)');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    t.add_cleanup(() => pc2.close());
    await pc1.setLocalDescription(await pc1.createOffer());
    const p = pc1.setRemoteDescription(await pc2.createOffer());
    await new Promise(r => pc1.onsignalingstatechange = r);
    assert_equals(pc1.signalingState, 'stable');
    await pc1.addIceCandidate();
    await p;
    assert_equals(pc1.signalingState, 'have-remote-offer');
  }, 'setRemoteDescription(offer) from have-local-offer is glare-proof');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    t.add_cleanup(() => pc2.close());
    await pc1.setLocalDescription(await pc1.createOffer());
    const p = pc1.setRemoteDescription({type: 'offer', sdp: 'Invalid SDP'});
    await new Promise(r => pc1.onsignalingstatechange = r);
    assert_equals(pc1.signalingState, 'stable');
    assert_equals(pc1.pendingLocalDescription, null);
    assert_equals(pc1.pendingRemoteDescription, null);
    await promise_rejects_dom(t, 'RTCError', p);
  }, 'setRemoteDescription(invalidOffer) from have-local-offer does not undo rollback');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());
    pc1.addTransceiver('video');
    const offer = await pc1.createOffer();
    await pc2.setRemoteDescription(offer);
    assert_equals(pc2.getTransceivers().length, 1);
    await pc2.setRemoteDescription(offer);
    assert_equals(pc2.getTransceivers().length, 1);
    await pc1.setLocalDescription(offer);
    const answer = await pc2.createAnswer();
    await pc2.setLocalDescription(answer);
    await pc1.setRemoteDescription(answer);
  }, 'repeated sRD(offer) works');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());
    pc1.addTransceiver('video');
    await exchangeOfferAnswer(pc1, pc2);
    await waitForIceGatheringState(pc1, ['complete']);
    await exchangeOfferAnswer(pc1, pc2);
    await waitForIceStateChange(pc2, ['connected', 'completed']);
  }, 'sRD(reoffer) with candidates and without trickle works');

  promise_test(async t => {
    const pc1 = new RTCPeerConnection();
    t.add_cleanup(() => pc1.close());
    const pc2 = new RTCPeerConnection();
    t.add_cleanup(() => pc2.close());
    pc1.addTransceiver('video');
    const offer = await pc1.createOffer();
    const srdPromise = pc2.setRemoteDescription(offer);
    assert_equals(pc2.getTransceivers().length, 0);
    await srdPromise;
    assert_equals(pc2.getTransceivers().length, 1);
  }, 'Transceivers added by sRD(offer) should not show up until sRD resolves');

</script>


text:
using API.Models;
using System.Collections.Generic;
using System.Linq;
using System;

namespace API.Services
{
    public interface IAuctionRepository : IRepository<Auction>
    {
        IQueryable GetWithBiddings(int auctionId);
    }
}


text:
package com.sessionm.smp_loyalty_card;

import android.app.Application;

import com.sessionm.core.api.SessionM;
import com.sessionm.core.api.SessionMError;
import com.sessionm.core.api.StartupListener;
import com.sessionm.core.api.ext.SessionMExtension;
import com.sessionm.loyaltycard.api.LoyaltyCardsManager;

public class SEApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //Callback is optional but highly recommended
        SessionM.start(this, new StartupListener() {
            @Override
            public void onStarted(SessionMError sessionMError) {
                //If sessionMError is not null, something is wrong(Networking, config, etc.)
            }
        });

        //!!!!!!!Attention: this flag is for test only!!!!!!!!!!
        SessionMExtension.getInstance().setTestFlag(LoyaltyCardsManager.getInstance(), "_server_debug", true);
    }
}


text:
/**
 * The utility APIs.
 */
package org.onosproject.teyang.api;


text:
This module contains the WebGL adapter for the "abstract" luma.gl API (`@luma.gl/api`).

Simply importing `@luma.gl/webgl` installs the adapter and enables WebGL devices to
be created using `luma.createDevice(...)`:

```typescript
import {luma} from '@luma.gl/api';
import '@luma.gl/webgl'; // Installs the WebGLDevice adapter

const device = await luma.createDevice({type: 'webgl', canvas: ...});

// Resources can now be created
const buffer = device.createBuffer(...);
```

To use a luma.gl WebGL `Device` with raw WebGL calls, the application needs to access
the `WebGLRenderingContext`. The context is available on the `WebGLDevice` subclass:

```typescript
// @ts-expect-error
const gl = device.gl;
```

With a bit more work, typescript users can retrieve the `WebGLRenderingContext`
without ignoring type errors:

```typescript
import {cast} from '@luma.gl/api';
import {WebGLDevice} from '@luma.gl/webgl'; // Installs the WebGLDevice adapter

const webglDevice = cast<WebGPUDevice>(device);
const gl = webglDevice.gl;
```

## Legacy WebGL classes

This module also exports a set of JavaScript classes for the WebGL2 API,
inherited from the legacy luma.gl v8 API. Note that these classes are considered
deprecated and should be avoided in new code.


text:
define([
    'flight/lib/component',
    'util/popovers/withPopover',
    'util/component/attacher',
    'util/range'
], function(
    defineComponent,
    withPopover,
    Attacher,
    rangeUtils) {

    return defineComponent(TextPopover, withPopover);

    function TextPopover() {

        this.before('teardown', function() {
            if (this.attacher) {
                this.attacher.teardown();
                this.attacher = null;
            }
        })

        this.before('initialize', function(node, config) {
            config.hideDialog = true;
            config.template = '/detail/text/popover/popover.hbs';
            this.after('setupWithTemplate', () => {
                const {
                    selection,
                    terms,
                    sourceVertexId,
                    targetVertexId,
                    artifactId,
                    propertyName,
                    propertyKey
                } = this.attr;

                this.attacher = Attacher()
                    .node(this.popover.find('.popover-content'))
                    .path('detail/text/popover/TermContainer')
                    .params({ selection, terms, artifactId, propertyName, propertyKey, sourceVertexId, targetVertexId })
                    .behavior({
                        onHoverTerm: (attacher, id) => {
                            this.trigger('hoverTerm', { id });
                        },
                        comment: (attacher, sourceInfo) => {
                            this.trigger('commentOnSelection', sourceInfo);
                        },
                        openFullscreen: (attacher, elementIds) => {
                            this.trigger(document, 'openFullscreen', elementIds);
                        },
                        reloadText: () => {
                            this.trigger(document, 'textUpdated', { vertexId: artifactId });
                        },
                        closeDialog: () => {
                            rangeUtils.clearSelection();
                            this.teardown();
                        }
                    });

                this.attacher.attach().then(() => {
                    this.dialog.show();
                    this.positionDialog();
                })
            })
        })
    }
});


text:
layout: post
title: Classroom walls
date: 2017-11-09 22:37:19 -0500
categories: education
location: Somerville, Mass.
---

This is my third year volunteering with an awesome local organization as a mentor for immigrant high school students. We meet once a week, in the evening, in a classroom at the high school. My student was late today — he had some "drama" to deal with — so I sat for a while looking around. I think I'd forgotten what a high school classroom looks like. They're so personal and idiosyncratic. A poster from A Clockwork Orange. A quote from Dalí: "Intelligence without ambition is a bird without
wings." That one, as you might suspect, is [apocryphal](https://quoteinvestigator.com/2015/10/14/wings/). Ironically (or not?): A poster with Lincoln's photograph next to "Don't believe everything you read on the internet just because there's a picture with a quote next to it."

What would you put on the walls of your classroom?


text:
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"

using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using PdfSharp.Drawing;

namespace TheArtOfDev.HtmlRenderer.PdfSharp.Adapters
{
    /// <summary>
    /// Adapter for WinForms pens objects for core.
    /// </summary>
    internal sealed class PenAdapter : RPen
    {
        /// <summary>
        /// The actual WinForms brush instance.
        /// </summary>
        private readonly XPen _pen;

        /// <summary>
        /// Init.
        /// </summary>
        public PenAdapter(XPen pen)
        {
            _pen = pen;
        }

        /// <summary>
        /// The actual WinForms brush instance.
        /// </summary>
        public XPen Pen
        {
            get { return _pen; }
        }

        public override double Width
        {
            get { return _pen.Width; }
            set { _pen.Width = value; }
        }

        public override RDashStyle DashStyle
        {
            set
            {
                switch (value)
                {
                    case RDashStyle.Solid:
                        _pen.DashStyle = XDashStyle.Solid;
                        break;
                    case RDashStyle.Dash:
                        _pen.DashStyle = XDashStyle.Dash;
                        if (Width < 2)
                            _pen.DashPattern = new[] { 4, 4d }; // better looking
                        break;
                    case RDashStyle.Dot:
                        _pen.DashStyle = XDashStyle.Dot;
                        break;
                    case RDashStyle.DashDot:
                        _pen.DashStyle = XDashStyle.DashDot;
                        break;
                    case RDashStyle.DashDotDot:
                        _pen.DashStyle = XDashStyle.DashDotDot;
                        break;
                    case RDashStyle.Custom:
                        _pen.DashStyle = XDashStyle.Custom;
                        break;
                    default:
                        _pen.DashStyle = XDashStyle.Solid;
                        break;
                }
            }
        }
    }
}


text:
import unittest.mock as mock
from typing import Optional

import numpy as np
import pytest
import sympy

import cirq
import cirq.circuits.circuit_operation as circuit_operation
from cirq import _compat
from cirq.circuits.circuit_operation import _full_join_string_lists

ALL_SIMULATORS = (cirq.Simulator(), cirq.DensityMatrixSimulator(), cirq.CliffordSimulator())

def test_properties():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    op = cirq.CircuitOperation(circuit)
    assert op.circuit is circuit
    assert op.qubits == (a, b, c)
    assert op.qubit_map == {}
    assert op.measurement_key_map == {}
    assert op.param_resolver == cirq.ParamResolver()
    assert op.repetitions == 1
    assert op.repetition_ids is None
    # Despite having the same decomposition, these objects are not equal.
    assert op != circuit
    assert op == circuit.to_op()

def test_circuit_type():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.Circuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    with pytest.raises(TypeError, match='Expected circuit of type FrozenCircuit'):
        _ = cirq.CircuitOperation(circuit)

def test_non_invertible_circuit():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    with pytest.raises(ValueError, match='circuit is not invertible'):
        _ = cirq.CircuitOperation(circuit, repetitions=-2)

def test_repetitions_and_ids_length_mismatch():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    with pytest.raises(ValueError, match='Expected repetition_ids to be a list of length 2'):
        _ = cirq.CircuitOperation(circuit, repetitions=2, repetition_ids=['a', 'b', 'c'])

def test_is_measurement_memoization():
    a = cirq.LineQubit(0)
    circuit = cirq.FrozenCircuit(cirq.measure(a, key='m'))
    c_op = cirq.CircuitOperation(circuit)
    cache_name = _compat._method_cache_name(circuit._is_measurement_)
    assert not hasattr(circuit, cache_name)
    # Memoize `_is_measurement_` in the circuit.
    assert cirq.is_measurement(c_op)
    assert hasattr(circuit, cache_name)

def test_invalid_measurement_keys():
    a = cirq.LineQubit(0)
    circuit = cirq.FrozenCircuit(cirq.measure(a, key='m'))
    c_op = cirq.CircuitOperation(circuit)
    # Invalid key remapping
    with pytest.raises(ValueError, match='Mapping to invalid key: m:a'):
        _ = c_op.with_measurement_key_mapping({'m': 'm:a'})

    # Invalid key remapping nested CircuitOperation
    with pytest.raises(ValueError, match='Mapping to invalid key: m:a'):
        _ = cirq.CircuitOperation(cirq.FrozenCircuit(c_op), measurement_key_map={'m': 'm:a'})

    # Originally invalid key
    with pytest.raises(ValueError, match='Invalid key name: m:a'):
        _ = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(a, key='m:a')))

    # Remapped to valid key
    _ = cirq.CircuitOperation(circuit, measurement_key_map={'m:a': 'ma'})

def test_invalid_qubit_mapping():
    q = cirq.LineQubit(0)
    q3 = cirq.LineQid(1, dimension=3)

    # Invalid qid remapping dict in constructor
    with pytest.raises(ValueError, match='Qid dimension conflict'):
        _ = cirq.CircuitOperation(cirq.FrozenCircuit(), qubit_map={q: q3})

    # Invalid qid remapping dict in with_qubit_mapping call
    c_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q)))
    with pytest.raises(ValueError, match='Qid dimension conflict'):
        _ = c_op.with_qubit_mapping({q: q3})

    # Invalid qid remapping function in with_qubit_mapping call
    with pytest.raises(ValueError, match='Qid dimension conflict'):
        _ = c_op.with_qubit_mapping(lambda q: q3)

def test_circuit_sharing():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    op1 = cirq.CircuitOperation(circuit)
    op2 = cirq.CircuitOperation(op1.circuit)
    op3 = circuit.to_op()
    assert op1.circuit is circuit
    assert op2.circuit is circuit
    assert op3.circuit is circuit

    assert hash(op1) == hash(op2)
    assert hash(op1) == hash(op3)

def test_with_qubits():
    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.FrozenCircuit(cirq.H(a), cirq.CX(a, b))
    op_base = cirq.CircuitOperation(circuit)

    op_with_qubits = op_base.with_qubits(d, c)
    assert op_with_qubits.base_operation() == op_base
    assert op_with_qubits.qubits == (d, c)
    assert op_with_qubits.qubit_map == {a: d, b: c}

    assert op_base.with_qubit_mapping({a: d, b: c, d: a}) == op_with_qubits

    def map_fn(qubit: 'cirq.Qid') -> 'cirq.Qid':
        if qubit == a:
            return d
        if qubit == b:
            return c
        return qubit

    fn_op = op_base.with_qubit_mapping(map_fn)
    assert fn_op == op_with_qubits
    # map_fn does not affect qubits c and d.
    assert fn_op.with_qubit_mapping(map_fn) == op_with_qubits

    # with_qubits must receive the same number of qubits as the circuit contains.
    with pytest.raises(ValueError, match='Expected 2 qubits, got 3'):
        _ = op_base.with_qubits(c, d, b)

    # Two qubits cannot be mapped onto the same target qubit.
    with pytest.raises(ValueError, match='Collision in qubit map'):
        _ = op_base.with_qubit_mapping({a: b})

    # Two qubits cannot be transformed into the same target qubit.
    with pytest.raises(ValueError, match='Collision in qubit map'):
        _ = op_base.with_qubit_mapping(lambda q: b)
    # with_qubit_mapping requires exactly one argument.
    with pytest.raises(TypeError, match='must be a function or dict'):
        _ = op_base.with_qubit_mapping('bad arg')

def test_with_measurement_keys():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.FrozenCircuit(cirq.X(a), cirq.measure(b, key='mb'), cirq.measure(a, key='ma'))
    op_base = cirq.CircuitOperation(circuit)

    op_with_keys = op_base.with_measurement_key_mapping({'ma': 'pa', 'x': 'z'})
    assert op_with_keys.base_operation() == op_base
    assert op_with_keys.measurement_key_map == {'ma': 'pa'}
    assert cirq.measurement_key_names(op_with_keys) == {'pa', 'mb'}

    assert cirq.with_measurement_key_mapping(op_base, {'ma': 'pa'}) == op_with_keys

    # Two measurement keys cannot be mapped onto the same target string.
    with pytest.raises(ValueError):
        _ = op_base.with_measurement_key_mapping({'ma': 'mb'})

def test_with_params():
    a = cirq.LineQubit(0)
    z_exp = sympy.Symbol('z_exp')
    x_exp = sympy.Symbol('x_exp')
    delta = sympy.Symbol('delta')
    theta = sympy.Symbol('theta')
    circuit = cirq.FrozenCircuit(cirq.Z(a) ** z_exp, cirq.X(a) ** x_exp, cirq.Z(a) ** delta)
    op_base = cirq.CircuitOperation(circuit)

    param_dict = {z_exp: 2, x_exp: theta, sympy.Symbol('k'): sympy.Symbol('phi')}
    op_with_params = op_base.with_params(param_dict)
    assert op_with_params.base_operation() == op_base
    assert op_with_params.param_resolver == cirq.ParamResolver(
        {
            z_exp: 2,
            x_exp: theta,
            # As 'k' is irrelevant to the circuit, it does not appear here.
        }
    )
    assert cirq.parameter_names(op_with_params) == {'theta', 'delta'}

    assert (
        cirq.resolve_parameters(op_base, cirq.ParamResolver(param_dict), recursive=False)
        == op_with_params
    )

def test_recursive_params():
    q = cirq.LineQubit(0)
    a, a2, b, b2 = sympy.symbols('a a2 b b2')
    circuitop = cirq.CircuitOperation(
        cirq.FrozenCircuit(cirq.X(q) ** a, cirq.Z(q) ** b),
        # Not recursive, a and b are swapped.
        param_resolver=cirq.ParamResolver({a: b, b: a}),
    )
    # Recursive, so a->a2->0 and b->b2->1.
    outer_params = {a: a2, a2: 0, b: b2, b2: 1}
    resolved = cirq.resolve_parameters(circuitop, outer_params)
    # Combined, a->b->b2->1, and b->a->a2->0.
    assert resolved.param_resolver.param_dict == {a: 1, b: 0}

    # Non-recursive, so a->a2 and b->b2.
    resolved = cirq.resolve_parameters(circuitop, outer_params, recursive=False)
    # Combined, a->b->b2, and b->a->a2.
    assert resolved.param_resolver.param_dict == {a: b2, b: a2}

    with pytest.raises(RecursionError):
        cirq.resolve_parameters(circuitop, {a: a2, a2: a})

    # Non-recursive, so a->b and b->a.
    resolved = cirq.resolve_parameters(circuitop, {a: b, b: a}, recursive=False)
    # Combined, a->b->a, and b->a->b.
    assert resolved.param_resolver.param_dict == {}

    # First example should behave like an X when simulated
    result = cirq.Simulator().simulate(cirq.Circuit(circuitop), param_resolver=outer_params)
    assert np.allclose(result.state_vector(), [0, 1])

@pytest.mark.parametrize('add_measurements', [True, False])
@pytest.mark.parametrize('use_default_ids_for_initial_rep', [True, False])
def test_repeat(add_measurements, use_default_ids_for_initial_rep):
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(cirq.H(a), cirq.CX(a, b))
    if add_measurements:
        circuit.append([cirq.measure(b, key='mb'), cirq.measure(a, key='ma')])
    op_base = cirq.CircuitOperation(circuit.freeze())
    assert op_base.repeat(1) is op_base
    assert op_base.repeat(1, ['0']) != op_base
    assert op_base.repeat(1, ['0']) == op_base.repeat(repetition_ids=['0'])
    assert op_base.repeat(1, ['0']) == op_base.with_repetition_ids(['0'])

    initial_repetitions = -3
    if add_measurements:
        with pytest.raises(ValueError, match='circuit is not invertible'):
            _ = op_base.repeat(initial_repetitions)
        initial_repetitions = abs(initial_repetitions)

    op_with_reps: Optional[cirq.CircuitOperation] = None
    rep_ids = []
    if use_default_ids_for_initial_rep:
        op_with_reps = op_base.repeat(initial_repetitions)
        rep_ids = ['0', '1', '2']
        assert op_base**initial_repetitions == op_with_reps
    else:
        rep_ids = ['a', 'b', 'c']
        op_with_reps = op_base.repeat(initial_repetitions, rep_ids)
        assert op_base**initial_repetitions != op_with_reps
        assert (op_base**initial_repetitions).replace(repetition_ids=rep_ids) == op_with_reps
    assert op_with_reps.repetitions == initial_repetitions
    assert op_with_reps.repetition_ids == rep_ids
    assert op_with_reps.repeat(1) is op_with_reps

    final_repetitions = 2 * initial_repetitions

    op_with_consecutive_reps = op_with_reps.repeat(2)
    assert op_with_consecutive_reps.repetitions == final_repetitions
    assert op_with_consecutive_reps.repetition_ids == _full_join_string_lists(['0', '1'], rep_ids)
    assert op_base**final_repetitions != op_with_consecutive_reps

    op_with_consecutive_reps = op_with_reps.repeat(2, ['a', 'b'])
    assert op_with_reps.repeat(repetition_ids=['a', 'b']) == op_with_consecutive_reps
    assert op_with_consecutive_reps.repetitions == final_repetitions
    assert op_with_consecutive_reps.repetition_ids == _full_join_string_lists(['a', 'b'], rep_ids)

    with pytest.raises(ValueError, match='length to be 2'):
        _ = op_with_reps.repeat(2, ['a', 'b', 'c'])

    with pytest.raises(
        ValueError, match='At least one of repetitions and repetition_ids must be set'
    ):
        _ = op_base.repeat()

    with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
        _ = op_base.repeat(1.3)
    assert op_base.repeat(3.00000000001).repetitions == 3
    assert op_base.repeat(2.99999999999).repetitions == 3

@pytest.mark.parametrize('add_measurements', [True, False])
@pytest.mark.parametrize('use_repetition_ids', [True, False])
@pytest.mark.parametrize('initial_reps', [0, 1, 2, 3])
def test_repeat_zero_times(add_measurements, use_repetition_ids, initial_reps):
    q = cirq.LineQubit(0)
    subcircuit = cirq.Circuit(cirq.X(q))
    if add_measurements:
        subcircuit.append(cirq.measure(q))

    op = cirq.CircuitOperation(
        subcircuit.freeze(), repetitions=initial_reps, use_repetition_ids=use_repetition_ids
    )
    result = cirq.Simulator().simulate(cirq.Circuit(op))
    assert np.allclose(result.state_vector(), [0, 1] if initial_reps % 2 else [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op**0))
    assert np.allclose(result.state_vector(), [1, 0])

def test_no_repetition_ids():
    def default_repetition_ids(self):
        assert False, "Should not call default_repetition_ids"

    with mock.patch.object(circuit_operation, 'default_repetition_ids', new=default_repetition_ids):
        q = cirq.LineQubit(0)
        op = cirq.CircuitOperation(
            cirq.Circuit(cirq.X(q), cirq.measure(q)).freeze(),
            repetitions=1_000_000,
            use_repetition_ids=False,
        )
        assert op.repetitions == 1_000_000
        assert op.repetition_ids is None
        _ = repr(op)
        _ = str(op)

        op2 = op.repeat(10)
        assert op2.repetitions == 10_000_000
        assert op2.repetition_ids is None

def test_parameterized_repeat():
    q = cirq.LineQubit(0)
    op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q))) ** sympy.Symbol('a')
    assert cirq.parameter_names(op) == {'a'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 0})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 2})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': -1})
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5})
    with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op**-1
    assert cirq.parameter_names(op) == {'a'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 0})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 2})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': -1})
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5})
    with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op ** sympy.Symbol('b')
    assert cirq.parameter_names(op) == {'a', 'b'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1, 'b': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 2, 'b': 1})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1, 'b': 2})
    assert np.allclose(result.state_vector(), [1, 0])
    with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5, 'b': 1})
    with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))
    op = op**2.0
    assert cirq.parameter_names(op) == {'a', 'b'}
    assert not cirq.has_unitary(op)
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1, 'b': 1})
    assert np.allclose(result.state_vector(), [1, 0])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5, 'b': 1})
    assert np.allclose(result.state_vector(), [0, 1])
    result = cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1, 'b': 1.5})
    assert np.allclose(result.state_vector(), [0, 1])
    with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
        cirq.Simulator().simulate(cirq.Circuit(op), param_resolver={'a': 1.5, 'b': 1.5})
    with pytest.raises(ValueError, match='Circuit contains ops whose symbols were not specified'):
        cirq.Simulator().simulate(cirq.Circuit(op))

def test_parameterized_repeat_side_effects():
    q = cirq.LineQubit(0)
    op = cirq.CircuitOperation(
        cirq.FrozenCircuit(cirq.X(q).with_classical_controls('c'), cirq.measure(q, key='m')),
        repetitions=sympy.Symbol('a'),
    )

    # Control keys can be calculated because they only "lift" if there's a matching
    # measurement, in which case they're not returned here.
    assert cirq.control_keys(op) == {cirq.MeasurementKey('c')}

    # "local" params do not bind to the repetition param.
    assert cirq.parameter_names(op.with_params({'a': 1})) == {'a'}

    # Check errors that require unrolling the circuit.
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        cirq.measurement_key_objs(op)
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        cirq.measurement_key_names(op)
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        op.mapped_circuit()
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        cirq.decompose(op)

    # Not compatible with repetition ids
    with pytest.raises(ValueError, match='repetition ids with parameterized repetitions'):
        op.with_repetition_ids(['x', 'y'])
    with pytest.raises(ValueError, match='repetition ids with parameterized repetitions'):
        op.repeat(repetition_ids=['x', 'y'])

    # TODO(daxfohl): This should work, but likely requires a new protocol that returns *just* the
    # name of the measurement keys. (measurement_key_names returns the full serialized string).
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        cirq.with_measurement_key_mapping(op, {'m': 'm2'})

    # Everything should work once resolved
    op = cirq.resolve_parameters(op, {'a': 2})
    assert set(map(str, cirq.measurement_key_objs(op))) == {'0:m', '1:m'}
    assert op.mapped_circuit() == cirq.Circuit(
        cirq.X(q).with_classical_controls('c'),
        cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('0:m')),
        cirq.X(q).with_classical_controls('c'),
        cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('1:m')),
    )
    assert cirq.decompose(op) == cirq.decompose(
        cirq.Circuit(
            cirq.X(q).with_classical_controls('c'),
            cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('0:m')),
            cirq.X(q).with_classical_controls('c'),
            cirq.measure(q, key=cirq.MeasurementKey.parse_serialized('1:m')),
        )
    )

def test_parameterized_repeat_side_effects_when_not_using_rep_ids():
    q = cirq.LineQubit(0)
    op = cirq.CircuitOperation(
        cirq.FrozenCircuit(cirq.X(q).with_classical_controls('c'), cirq.measure(q, key='m')),
        repetitions=sympy.Symbol('a'),
        use_repetition_ids=False,
    )
    assert cirq.control_keys(op) == {cirq.MeasurementKey('c')}
    assert cirq.parameter_names(op.with_params({'a': 1})) == {'a'}
    assert set(map(str, cirq.measurement_key_objs(op))) == {'m'}
    assert cirq.measurement_key_names(op) == {'m'}
    assert cirq.measurement_key_names(cirq.with_measurement_key_mapping(op, {'m': 'm2'})) == {'m2'}
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        op.mapped_circuit()
    with pytest.raises(
        ValueError, match='Cannot unroll circuit due to nondeterministic repetitions'
    ):
        cirq.decompose(op)
    with pytest.raises(ValueError, match='repetition ids with parameterized repetitions'):
        op.with_repetition_ids(['x', 'y'])
    with pytest.raises(ValueError, match='repetition ids with parameterized repetitions'):
        op.repeat(repetition_ids=['x', 'y'])

def test_qid_shape():
    circuit = cirq.FrozenCircuit(
        cirq.IdentityGate(qid_shape=(q.dimension,)).on(q)
        for q in cirq.LineQid.for_qid_shape((1, 2, 3, 4))
    )
    op = cirq.CircuitOperation(circuit)
    assert cirq.qid_shape(op) == (1, 2, 3, 4)
    assert cirq.num_qubits(op) == 4

    id_circuit = cirq.FrozenCircuit(cirq.I(q) for q in cirq.LineQubit.range(3))
    id_op = cirq.CircuitOperation(id_circuit)
    assert cirq.qid_shape(id_op) == (2, 2, 2)
    assert cirq.num_qubits(id_op) == 3

def test_string_format():
    x, y, z = cirq.LineQubit.range(3)

    fc0 = cirq.FrozenCircuit()
    op0 = cirq.CircuitOperation(fc0)
    assert str(op0) == "[  ]"

    fc0_global_phase_inner = cirq.FrozenCircuit(
        cirq.global_phase_operation(1j), cirq.global_phase_operation(1j)
    )
    op0_global_phase_inner = cirq.CircuitOperation(fc0_global_phase_inner)
    fc0_global_phase_outer = cirq.FrozenCircuit(
        op0_global_phase_inner, cirq.global_phase_operation(1j)
    )
    op0_global_phase_outer = cirq.CircuitOperation(fc0_global_phase_outer)
    assert (
        str(op0_global_phase_outer)
        == """\
[                       ]
[                       ]
[ global phase:   -0.5π ]"""
    )

    fc1 = cirq.FrozenCircuit(cirq.X(x), cirq.H(y), cirq.CX(y, z), cirq.measure(x, y, z, key='m'))
    op1 = cirq.CircuitOperation(fc1)
    assert (
        str(op1)
        == """\
[ 0: ───X───────M('m')─── ]
[               │         ]
[ 1: ───H───@───M──────── ]
[           │   │         ]
[ 2: ───────X───M──────── ]"""
    )
    assert (
        repr(op1)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.H(cirq.LineQubit(1)),
        ),
        cirq.Moment(
            cirq.CNOT(cirq.LineQubit(1), cirq.LineQubit(2)),
        ),
        cirq.Moment(
            cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1), cirq.LineQubit(2), key=cirq.MeasurementKey(name='m')),
        ),
    ]),
)"""
    )

    fc2 = cirq.FrozenCircuit(cirq.X(x), cirq.H(y), cirq.CX(y, x))
    op2 = cirq.CircuitOperation(
        circuit=fc2,
        qubit_map=({y: z}),
        repetitions=3,
        parent_path=('outer', 'inner'),
        repetition_ids=['a', 'b', 'c'],
    )
    assert (
        str(op2)
        == """\
[ 0: ───X───X─── ]
[           │    ]
[ 1: ───H───@─── ](qubit_map={q(1): q(2)}, parent_path=('outer', 'inner'),\
 repetition_ids=['a', 'b', 'c'])"""
    )
    assert (
        repr(op2)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.H(cirq.LineQubit(1)),
        ),
        cirq.Moment(
            cirq.CNOT(cirq.LineQubit(1), cirq.LineQubit(0)),
        ),
    ]),
    repetitions=3,
    qubit_map={cirq.LineQubit(1): cirq.LineQubit(2)},
    parent_path=('outer', 'inner'),
    repetition_ids=['a', 'b', 'c'],
)"""
    )

    fc3 = cirq.FrozenCircuit(cirq.X(x) ** sympy.Symbol('b'), cirq.measure(x, key='m'))
    op3 = cirq.CircuitOperation(
        circuit=fc3,
        qubit_map={x: y},
        measurement_key_map={'m': 'p'},
        param_resolver={sympy.Symbol('b'): 2},
    )
    indented_fc3_repr = repr(fc3).replace('\n', '\n    ')
    assert (
        str(op3)
        == """\
[ 0: ───X^b───M('m')─── ](qubit_map={q(0): q(1)}, \
key_map={m: p}, params={b: 2})"""
    )
    assert (
        repr(op3)
        == f"""\
cirq.CircuitOperation(
    circuit={indented_fc3_repr},
    qubit_map={{cirq.LineQubit(0): cirq.LineQubit(1)}},
    measurement_key_map={{'m': 'p'}},
    param_resolver=cirq.ParamResolver({{sympy.Symbol('b'): 2}}),
)"""
    )

    fc4 = cirq.FrozenCircuit(cirq.X(y))
    op4 = cirq.CircuitOperation(fc4)
    fc5 = cirq.FrozenCircuit(cirq.X(x), op4)
    op5 = cirq.CircuitOperation(fc5)
    assert (
        repr(op5)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.CircuitOperation(
                circuit=cirq.FrozenCircuit([
                    cirq.Moment(
                        cirq.X(cirq.LineQubit(1)),
                    ),
                ]),
            ),
        ),
    ]),
)"""
    )
    op6 = cirq.CircuitOperation(fc5, use_repetition_ids=False)
    assert (
        repr(op6)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.X(cirq.LineQubit(0)),
            cirq.CircuitOperation(
                circuit=cirq.FrozenCircuit([
                    cirq.Moment(
                        cirq.X(cirq.LineQubit(1)),
                    ),
                ]),
            ),
        ),
    ]),
    use_repetition_ids=False,
)"""
    )
    op7 = cirq.CircuitOperation(
        cirq.FrozenCircuit(cirq.measure(x, key='a')),
        use_repetition_ids=False,
        repeat_until=cirq.KeyCondition(cirq.MeasurementKey('a')),
    )
    assert (
        repr(op7)
        == """\
cirq.CircuitOperation(
    circuit=cirq.FrozenCircuit([
        cirq.Moment(
            cirq.measure(cirq.LineQubit(0), key=cirq.MeasurementKey(name='a')),
        ),
    ]),
    use_repetition_ids=False,
    repeat_until=cirq.KeyCondition(cirq.MeasurementKey(name='a')),
)"""
    )

def test_json_dict():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(
        cirq.X(a),
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** sympy.Symbol('exp'),
        cirq.measure(a, b, c, key='m'),
    )
    op = cirq.CircuitOperation(
        circuit=circuit,
        qubit_map={c: b, b: c},
        measurement_key_map={'m': 'p'},
        param_resolver={'exp': 'theta'},
        parent_path=('nested', 'path'),
    )

    assert op._json_dict_() == {
        'circuit': circuit,
        'repetitions': 1,
        'qubit_map': sorted([(k, v) for k, v in op.qubit_map.items()]),
        'measurement_key_map': op.measurement_key_map,
        'param_resolver': op.param_resolver,
        'parent_path': op.parent_path,
        'repetition_ids': None,
    }

def test_terminal_matches():
    a, b = cirq.LineQubit.range(2)
    fc = cirq.FrozenCircuit(cirq.H(a), cirq.measure(b, key='m1'))
    op = cirq.CircuitOperation(fc)

    c = cirq.Circuit(cirq.X(a), op)
    assert c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(cirq.X(b), op)
    assert c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(cirq.measure(a), op)
    assert not c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(cirq.measure(b), op)
    assert not c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(op, cirq.X(a))
    assert c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(op, cirq.X(b))
    assert not c.are_all_measurements_terminal()
    assert not c.are_any_measurements_terminal()

    c = cirq.Circuit(op, cirq.measure(a))
    assert c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

    c = cirq.Circuit(op, cirq.measure(b))
    assert not c.are_all_measurements_terminal()
    assert c.are_any_measurements_terminal()

def test_nonterminal_in_subcircuit():
    a, b = cirq.LineQubit.range(2)
    fc = cirq.FrozenCircuit(cirq.H(a), cirq.measure(b, key='m1'), cirq.X(b))
    op = cirq.CircuitOperation(fc)
    c = cirq.Circuit(cirq.X(a), op)
    assert isinstance(op, cirq.CircuitOperation)
    assert not c.are_all_measurements_terminal()
    assert not c.are_any_measurements_terminal()

    op = op.with_tags('test')
    c = cirq.Circuit(cirq.X(a), op)
    assert not isinstance(op, cirq.CircuitOperation)
    assert not c.are_all_measurements_terminal()
    assert not c.are_any_measurements_terminal()

def test_decompose_applies_maps():
    a, b, c = cirq.LineQubit.range(3)
    exp = sympy.Symbol('exp')
    theta = sympy.Symbol('theta')
    circuit = cirq.FrozenCircuit(
        cirq.X(a) ** theta,
        cirq.Y(b),
        cirq.H(c),
        cirq.CX(a, b) ** exp,
        cirq.measure(a, b, c, key='m'),
    )
    op = cirq.CircuitOperation(
        circuit=circuit,
        qubit_map={c: b, b: c},
        measurement_key_map={'m': 'p'},
        param_resolver={exp: theta, theta: exp},
    )

    expected_circuit = cirq.Circuit(
        cirq.X(a) ** exp,
        cirq.Y(c),
        cirq.H(b),
        cirq.CX(a, c) ** theta,
        cirq.measure(a, c, b, key='p'),
    )
    assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit

def test_decompose_loops():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.FrozenCircuit(cirq.H(a), cirq.CX(a, b))
    base_op = cirq.CircuitOperation(circuit)

    op = base_op.with_qubits(b, a).repeat(3)
    expected_circuit = cirq.Circuit(
        cirq.H(b), cirq.CX(b, a), cirq.H(b), cirq.CX(b, a), cirq.H(b), cirq.CX(b, a)
    )
    assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit

    op = base_op.repeat(-2)
    expected_circuit = cirq.Circuit(cirq.CX(a, b), cirq.H(a), cirq.CX(a, b), cirq.H(a))
    assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit

def test_decompose_loops_with_measurements():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.FrozenCircuit(cirq.H(a), cirq.CX(a, b), cirq.measure(a, b, key='m'))
    base_op = cirq.CircuitOperation(circuit)

    op = base_op.with_qubits(b, a).repeat(3)
    expected_circuit = cirq.Circuit(
        cirq.H(b),
        cirq.CX(b, a),
        cirq.measure(b, a, key=cirq.MeasurementKey.parse_serialized('0:m')),
        cirq.H(b),
        cirq.CX(b, a),
        cirq.measure(b, a, key=cirq.MeasurementKey.parse_serialized('1:m')),
        cirq.H(b),
        cirq.CX(b, a),
        cirq.measure(b, a, key=cirq.MeasurementKey.parse_serialized('2:m')),
    )
    assert cirq.Circuit(cirq.decompose_once(op)) == expected_circuit

def test_decompose_nested():
    a, b, c, d = cirq.LineQubit.range(4)
    exp1 = sympy.Symbol('exp1')
    exp_half = sympy.Symbol('exp_half')
    exp_one = sympy.Symbol('exp_one')
    exp_two = sympy.Symbol('exp_two')
    circuit1 = cirq.FrozenCircuit(cirq.X(a) ** exp1, cirq.measure(a, key='m1'))
    op1 = cirq.CircuitOperation(circuit1)
    circuit2 = cirq.FrozenCircuit(
        op1.with_qubits(a).with_measurement_key_mapping({'m1': 'ma'}),
        op1.with_qubits(b).with_measurement_key_mapping({'m1': 'mb'}),
        op1.with_qubits(c).with_measurement_key_mapping({'m1': 'mc'}),
        op1.with_qubits(d).with_measurement_key_mapping({'m1': 'md'}),
    )
    op2 = cirq.CircuitOperation(circuit2)
    circuit3 = cirq.FrozenCircuit(
        op2.with_params({exp1: exp_half}),
        op2.with_params({exp1: exp_one})
        .with_measurement_key_mapping({'ma': 'ma1'})
        .with_measurement_key_mapping({'mb': 'mb1'})
        .with_measurement_key_mapping({'mc': 'mc1'})
        .with_measurement_key_mapping({'md': 'md1'}),
        op2.with_params({exp1: exp_two})
        .with_measurement_key_mapping({'ma': 'ma2'})
        .with_measurement_key_mapping({'mb': 'mb2'})
        .with_measurement_key_mapping({'mc': 'mc2'})
        .with_measurement_key_mapping({'md': 'md2'}),
    )
    op3 = cirq.CircuitOperation(circuit3)

    final_op = op3.with_params({exp_half: 0.5, exp_one: 1.0, exp_two: 2.0})

    expected_circuit1 = cirq.Circuit(
        op2.with_params({exp1: 0.5, exp_half: 0.5, exp_one: 1.0, exp_two: 2.0}),
        op2.with_params({exp1: 1.0, exp_half: 0.5, exp_one: 1.0, exp_two: 2.0})
        .with_measurement_key_mapping({'ma': 'ma1'})
        .with_measurement_key_mapping({'mb': 'mb1'})
        .with_measurement_key_mapping({'mc': 'mc1'})
        .with_measurement_key_mapping({'md': 'md1'}),
        op2.with_params({exp1: 2.0, exp_half: 0.5, exp_one: 1.0, exp_two: 2.0})
        .with_measurement_key_mapping({'ma': 'ma2'})
        .with_measurement_key_mapping({'mb': 'mb2'})
        .with_measurement_key_mapping({'mc': 'mc2'})
        .with_measurement_key_mapping({'md': 'md2'}),
    )

    result_ops1 = cirq.decompose_once(final_op)
    assert cirq.Circuit(result_ops1) == expected_circuit1

    expected_circuit = cirq.Circuit(
        cirq.X(a) ** 0.5,
        cirq.measure(a, key='ma'),
        cirq.X(b) ** 0.5,
        cirq.measure(b, key='mb'),
        cirq.X(c) ** 0.5,
        cirq.measure(c, key='mc'),
        cirq.X(d) ** 0.5,
        cirq.measure(d, key='md'),
        cirq.X(a) ** 1.0,
        cirq.measure(a, key='ma1'),
        cirq.X(b) ** 1.0,
        cirq.measure(b, key='mb1'),
        cirq.X(c) ** 1.0,
        cirq.measure(c, key='mc1'),
        cirq.X(d) ** 1.0,
        cirq.measure(d, key='md1'),
        cirq.X(a) ** 2.0,
        cirq.measure(a, key='ma2'),
        cirq.X(b) ** 2.0,
        cirq.measure(b, key='mb2'),
        cirq.X(c) ** 2.0,
        cirq.measure(c, key='mc2'),
        cirq.X(d) ** 2.0,
        cirq.measure(d, key='md2'),
    )
    assert cirq.Circuit(cirq.decompose(final_op)) == expected_circuit
    # Verify that mapped_circuit gives the same operations.
    assert final_op.mapped_circuit(deep=True) == expected_circuit

def test_decompose_repeated_nested_measurements():
    # Details of this test described at
    # https://tinyurl.com/measurement-repeated-circuitop#heading=h.sbgxcsyin9wt.
    a = cirq.LineQubit(0)

    op1 = (
        cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(a, key='A')))
        .with_measurement_key_mapping({'A': 'B'})
        .repeat(2, ['zero', 'one'])
    )

    op2 = (
        cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(a, key='P'), op1))
        .with_measurement_key_mapping({'B': 'C', 'P': 'Q'})
        .repeat(2, ['zero', 'one'])
    )

    op3 = (
        cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(a, key='X'), op2))
        .with_measurement_key_mapping({'C': 'D', 'X': 'Y'})
        .repeat(2, ['zero', 'one'])
    )

    expected_measurement_keys_in_order = [
        'zero:Y',
        'zero:zero:Q',
        'zero:zero:zero:D',
        'zero:zero:one:D',
        'zero:one:Q',
        'zero:one:zero:D',
        'zero:one:one:D',
        'one:Y',
        'one:zero:Q',
        'one:zero:zero:D',
        'one:zero:one:D',
        'one:one:Q',
        'one:one:zero:D',
        'one:one:one:D',
    ]
    assert cirq.measurement_key_names(op3) == set(expected_measurement_keys_in_order)

    expected_circuit = cirq.Circuit()
    for key in expected_measurement_keys_in_order:
        expected_circuit.append(cirq.measure(a, key=cirq.MeasurementKey.parse_serialized(key)))

    assert cirq.Circuit(cirq.decompose(op3)) == expected_circuit
    assert cirq.measurement_key_names(expected_circuit) == set(expected_measurement_keys_in_order)

    # Verify that mapped_circuit gives the same operations.
    assert op3.mapped_circuit(deep=True) == expected_circuit

def test_keys_under_parent_path():
    a = cirq.LineQubit(0)
    op1 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(a, key='A')))
    assert cirq.measurement_key_names(op1) == {'A'}
    op2 = op1.with_key_path(('B',))
    assert cirq.measurement_key_names(op2) == {'B:A'}
    op3 = cirq.with_key_path_prefix(op2, ('C',))
    assert cirq.measurement_key_names(op3) == {'C:B:A'}
    op4 = op3.repeat(2)
    assert cirq.measurement_key_names(op4) == {'C:B:0:A', 'C:B:1:A'}

def test_mapped_circuit_preserves_moments():
    q0, q1 = cirq.LineQubit.range(2)
    fc = cirq.FrozenCircuit(cirq.Moment(cirq.X(q0)), cirq.Moment(cirq.X(q1)))
    op = cirq.CircuitOperation(fc)
    assert op.mapped_circuit() == fc
    assert op.repeat(3).mapped_circuit(deep=True) == fc * 3

def test_mapped_op():
    q0, q1 = cirq.LineQubit.range(2)
    a, b = (sympy.Symbol(x) for x in 'ab')
    fc1 = cirq.FrozenCircuit(cirq.X(q0) ** a, cirq.measure(q0, q1, key='m'))
    op1 = (
        cirq.CircuitOperation(fc1)
        .with_params({'a': 'b'})
        .with_qubits(q1, q0)
        .with_measurement_key_mapping({'m': 'k'})
    )
    fc2 = cirq.FrozenCircuit(cirq.X(q1) ** b, cirq.measure(q1, q0, key='k'))
    op2 = cirq.CircuitOperation(fc2)

    assert op1.mapped_op() == op2

def test_tag_propagation():
    # Tags are not propagated from the CircuitOperation to its components.
    # TODO: support tag propagation for better serialization.
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.FrozenCircuit(cirq.X(a), cirq.H(b), cirq.H(c), cirq.CZ(a, c))
    op = cirq.CircuitOperation(circuit)
    test_tag = 'test_tag'
    op = op.with_tags(test_tag)

    assert test_tag in op.tags

    # TODO: Tags must propagate during decomposition.
    sub_ops = cirq.decompose(op)
    for op in sub_ops:
        assert test_tag not in op.tags

def test_mapped_circuit_keeps_keys_under_parent_path():
    q = cirq.LineQubit(0)
    op1 = cirq.CircuitOperation(
        cirq.FrozenCircuit(
            cirq.measure(q, key='A'),
            cirq.measure_single_paulistring(cirq.X(q), key='B'),
            cirq.MixedUnitaryChannel.from_mixture(cirq.bit_flip(0.5), key='C').on(q),
            cirq.KrausChannel.from_channel(cirq.phase_damp(0.5), key='D').on(q),
        )
    )
    op2 = op1.with_key_path(('X',))
    assert cirq.measurement_key_names(op2.mapped_circuit()) == {'X:A', 'X:B', 'X:C', 'X:D'}

def test_mapped_circuit_allows_repeated_keys():
    q = cirq.LineQubit(0)
    op1 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.measure(q, key='A')))
    op2 = cirq.CircuitOperation(cirq.FrozenCircuit(op1, op1))
    circuit = op2.mapped_circuit(deep=True)
    cirq.testing.assert_has_diagram(
        circuit, "0: ───M('A')───M('A')───", use_unicode_characters=True
    )
    op1 = cirq.measure(q, key='A')
    op2 = cirq.CircuitOperation(cirq.FrozenCircuit(op1, op1))
    circuit = op2.mapped_circuit()
    cirq.testing.assert_has_diagram(
        circuit, "0: ───M('A')───M('A')───", use_unicode_characters=True
    )

@pytest.mark.parametrize('sim', ALL_SIMULATORS)
def test_simulate_no_repetition_ids_both_levels(sim):
    q = cirq.LineQubit(0)
    inner = cirq.Circuit(cirq.measure(q, key='a'))
    middle = cirq.Circuit(
        cirq.CircuitOperation(inner.freeze(), repetitions=2, use_repetition_ids=False)
    )
    outer_subcircuit = cirq.CircuitOperation(
        middle.freeze(), repetitions=2, use_repetition_ids=False
    )
    circuit = cirq.Circuit(outer_subcircuit)
    result = sim.run(circuit)
    assert result.records['a'].shape == (1, 4, 1)

@pytest.mark.parametrize('sim', ALL_SIMULATORS)
def test_simulate_no_repetition_ids_outer(sim):
    q = cirq.LineQubit(0)
    inner = cirq.Circuit(cirq.measure(q, key='a'))
    middle = cirq.Circuit(cirq.CircuitOperation(inner.freeze(), repetitions=2))
    outer_subcircuit = cirq.CircuitOperation(
        middle.freeze(), repetitions=2, use_repetition_ids=False
    )
    circuit = cirq.Circuit(outer_subcircuit)
    result = sim.run(circuit)
    assert result.records['0:a'].shape == (1, 2, 1)
    assert result.records['1:a'].shape == (1, 2, 1)

@pytest.mark.parametrize('sim', ALL_SIMULATORS)
def test_simulate_no_repetition_ids_inner(sim):
    q = cirq.LineQubit(0)
    inner = cirq.Circuit(cirq.measure(q, key='a'))
    middle = cirq.Circuit(
        cirq.CircuitOperation(inner.freeze(), repetitions=2, use_repetition_ids=False)
    )
    outer_subcircuit = cirq.CircuitOperation(middle.freeze(), repetitions=2)
    circuit = cirq.Circuit(outer_subcircuit)
    result = sim.run(circuit)
    assert result.records['0:a'].shape == (1, 2, 1)
    assert result.records['1:a'].shape == (1, 2, 1)

@pytest.mark.parametrize('sim', ALL_SIMULATORS)
def test_repeat_until(sim):
    q = cirq.LineQubit(0)
    key = cirq.MeasurementKey('m')
    c = cirq.Circuit(
        cirq.X(q),
        cirq.CircuitOperation(
            cirq.FrozenCircuit(cirq.X(q), cirq.measure(q, key=key)),
            use_repetition_ids=False,
            repeat_until=cirq.KeyCondition(key),
        ),
    )
    measurements = sim.run(c).records['m'][0]
    assert len(measurements) == 2
    assert measurements[0] == (0,)
    assert measurements[1] == (1,)

@pytest.mark.parametrize('sim', ALL_SIMULATORS)
def test_repeat_until_sympy(sim):
    q1, q2 = cirq.LineQubit.range(2)
    circuitop = cirq.CircuitOperation(
        cirq.FrozenCircuit(cirq.X(q2), cirq.measure(q2, key='b')),
        use_repetition_ids=False,
        repeat_until=cirq.SympyCondition(sympy.Eq(sympy.Symbol('a'), sympy.Symbol('b'))),
    )
    c = cirq.Circuit(cirq.measure(q1, key='a'), circuitop)
    # Validate commutation
    assert len(c) == 2
    assert cirq.control_keys(circuitop) == {cirq.MeasurementKey('a')}
    measurements = sim.run(c).records['b'][0]
    assert len(measurements) == 2
    assert measurements[0] == (1,)
    assert measurements[1] == (0,)

@pytest.mark.parametrize('sim', [cirq.Simulator(), cirq.DensityMatrixSimulator()])
def test_post_selection(sim):
    q = cirq.LineQubit(0)
    key = cirq.MeasurementKey('m')
    c = cirq.Circuit(
        cirq.CircuitOperation(
            cirq.FrozenCircuit(cirq.X(q) ** 0.2, cirq.measure(q, key=key)),
            use_repetition_ids=False,
            repeat_until=cirq.KeyCondition(key),
        )
    )
    result = sim.run(c)
    assert result.records['m'][0][-1] == (1,)
    for i in range(len(result.records['m'][0]) - 1):
        assert result.records['m'][0][i] == (0,)

def test_repeat_until_diagram():
    q = cirq.LineQubit(0)
    key = cirq.MeasurementKey('m')
    c = cirq.Circuit(
        cirq.CircuitOperation(
            cirq.FrozenCircuit(cirq.X(q) ** 0.2, cirq.measure(q, key=key)),
            use_repetition_ids=False,
            repeat_until=cirq.KeyCondition(key),
        )
    )
    cirq.testing.assert_has_diagram(
        c,
        """
0: ───[ 0: ───X^0.2───M('m')─── ](no_rep_ids, until=m)───
""",
        use_unicode_characters=True,
    )

def test_repeat_until_error():
    q = cirq.LineQubit(0)
    with pytest.raises(ValueError, match='Cannot use repetitions with repeat_until'):
        cirq.CircuitOperation(
            cirq.FrozenCircuit(),
            use_repetition_ids=True,
            repeat_until=cirq.KeyCondition(cirq.MeasurementKey('a')),
        )
    with pytest.raises(ValueError, match='Infinite loop'):
        cirq.CircuitOperation(
            cirq.FrozenCircuit(cirq.measure(q, key='m')),
            use_repetition_ids=False,
            repeat_until=cirq.KeyCondition(cirq.MeasurementKey('a')),
        )

# TODO: Operation has a "gate" property. What is this for a CircuitOperation?


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;

namespace SenchaMinify
{
    public class SenchaBundleOrderer : SenchaOrderer, IBundleOrderer
    {
        public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
        {
            var senchaBundleFiles = files.Select(f => new SenchaBundleFile(f));
            var ordered = OrderFiles(senchaBundleFiles);
            var result = ordered.Select(ef => ef.File);
            return result;
        }
    }
}


text:
package org.stagemonitor.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IOUtils {

	private static final int EOF = -1;
	private static final int BUFFER_SIZE = 4096;
	private static final Logger logger = LoggerFactory.getLogger(IOUtils.class);

	private IOUtils() {
	}

	public static void copy(InputStream input, OutputStream output) throws IOException {
		int n;
		final byte[] buffer = new byte[BUFFER_SIZE];
		while (EOF != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
	}

	public static void write(String str, OutputStream out) throws IOException {
		out.write(str.getBytes());
	}

	public static String toString(InputStream input) throws IOException {
		if (input == null) {
			return null;
		}
		final InputStreamReader inputStreamReader = new InputStreamReader(input);
		final StringBuilder stringBuilder = new StringBuilder();
		final char[] buffer = new char[BUFFER_SIZE];
		int n = 0;
		while (EOF != (n = inputStreamReader.read(buffer))) {
			stringBuilder.append(buffer, 0, n);
		}
		return stringBuilder.toString();
	}

	public static void closeQuietly(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				// ignore
			}
		}
	}

	public static void consumeAndClose(InputStream is) {
		if (is == null) {
			return;
		}
		try {
			while (is.read() != EOF) {}
		} catch (IOException e) {
			logger.warn(e.getMessage(), e);
		} finally {
			closeQuietly(is);
		}
	}

	public static InputStream getResourceAsStream(String name) {
		return IOUtils.class.getClassLoader().getResourceAsStream(name);
	}

	public static String getResourceAsString(String name) {
		try {
			return toString(getResourceAsStream(name));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static byte[] readToBytes(InputStream inputStream) throws IOException {
		final ByteArrayOutputStream output = new ByteArrayOutputStream();
		copy(inputStream, output);
		return output.toByteArray();
	}
}


text:
package com.creative.front_server;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.creative.connector.back_server.Connector;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

  private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

  /**
   * Simply selects the home view to render by returning its name.
   */
  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate );

    return "home";
  }

}


text:
package com.infinityraider.elementalinvocations.api;

/**
 * Interface representing a magic charge
 */
public interface IMagicCharge {
    /**
     * @return the Element of the charge
     */
    Element element();

    /**
     * @return the potency of the charge
     */
    int potency();
}


text:
package com.appolica.flubber.animation.providers;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.view.View;

import com.appolica.flubber.AnimationBody;

public class FlipY extends BaseProvider {

    @Override
    public Animator getAnimationFor(AnimationBody animationBody, View view) {

        final float startRotation = view.getRotationY();
        final float endRotation = startRotation + 180f;

        final PropertyValuesHolder rotationPVH =
                PropertyValuesHolder.ofFloat(View.ROTATION_Y, startRotation, endRotation);

        final ObjectAnimator animation =
                ObjectAnimator.ofPropertyValuesHolder(view, rotationPVH);

        return animation;
    }
}