text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ekingsoft</groupId>
  <artifactId>ekapp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>ekapp Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springside</groupId>
    <artifactId>springside3-parent</artifactId>
    <version>3.3.2</version>
    <relativePath>../../modules/parent/pom.xml</relativePath>
  </parent>

  <!-- 项目属性 -->
  <properties>
    <jdbc.driver.groupId>com.h2database</jdbc.driver.groupId>
    <jdbc.driver.artifactId>h2</jdbc.driver.artifactId>
    <jdbc.driver.version>${h2.version}</jdbc.driver.version>
  </properties>

  <!-- 依赖项定义 -->
  <dependencies>
    <!-- spring begin -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-annotation_1.0_spec</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring end -->

    <!-- dependency spring2.5.6-->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.3</version>
      <classifier>jdk15</classifier>
    </dependency>

    <!--
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib-ext-spring</artifactId>
      <version>1.0.2</version>
    </dependency>

    <dependency>
      <groupId>net.sf.spring-json</groupId>
      <artifactId>spring-json</artifactId>
      <version>1.3.0</version>
    </dependency>
    -->
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>

    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- database begin -->
    <!-- hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-jmx</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
    </dependency>
    <dependency>
      <groupId>javassist</groupId>
      <artifactId>javassist</artifactId>
    </dependency>

    <!--
      dbcp <dependency> <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId> </dependency>
    -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- jdbc driver -->
    <dependency>
      <groupId>${jdbc.driver.groupId}</groupId>
      <artifactId>${jdbc.driver.artifactId}</artifactId>
      <version>${jdbc.driver.version}</version>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>net.sourceforge.jtds</groupId>
      <artifactId>jtds</artifactId>
      <version>1.2.2</version>
      <scope>runtime</scope>
    </dependency>

    <!-- database end -->

    <!-- web begin -->
    <!--
      no struts <dependency> <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId> </dependency> <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-convention-plugin </artifactId> </dependency>
      <dependency> <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId> </dependency>
    -->

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.16</version>
    </dependency>

    <dependency>
      <groupId>org.tuckey</groupId>
      <artifactId>urlrewritefilter</artifactId>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
    </dependency>
    <!-- web end -->

    <!-- webservice begin -->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-ws-security</artifactId>
    </dependency>

    <dependency>
      <groupId>net.sf.dozer</groupId>
      <artifactId>dozer</artifactId>
    </dependency>
    <!-- webservice end -->

    <!--  rest begin -->
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey.contribs</groupId>
      <artifactId>jersey-spring</artifactId>
    </dependency>

    <!-- Jackson JSON Mapper -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-jaxrs</artifactId>
    </dependency>
    <!-- rest end -->

    <!-- security begin -->
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
    </dependency>

    <dependency>
      <groupId>com.octo.captcha</groupId>
      <artifactId>jcaptcha</artifactId>
    </dependency>
    <!-- security end -->

    <!-- jms begin -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-core</artifactId>
    </dependency>
    <!-- jms end -->

    <!-- quartz -->
    <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
    </dependency>

    <!-- logging begin -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>0.9.21</version>
    </dependency>
    <!-- logging end -->

    <!-- email begin -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
    </dependency>
    <!-- email end -->

    <!-- utils begin-->
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.collections</groupId>
      <artifactId>google-collections</artifactId>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
    </dependency>

    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>

    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
      <groupId>net.jcip</groupId>
      <artifactId>jcip-annotations</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
    </dependency>
    <!-- utils end -->

    <!--  xml begin -->
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
    </dependency>

    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
    </dependency>

    <dependency>
      <groupId>jaxen</groupId>
      <artifactId>jaxen</artifactId>
    </dependency>
    <!--  xml end -->

    <!-- poi begin -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
    </dependency>
    <!-- poi end -->

    <!-- test begin -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>

    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

    <!-- selenium 2.0 -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-htmlunit-driver</artifactId>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-firefox-driver</artifactId>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-ie-driver</artifactId>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-remote-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.dbunit</groupId>
      <artifactId>dbunit</artifactId>
    </dependency>

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>

    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jsp-2.1-jetty</artifactId>
    </dependency>

    <!-- test end -->

    <!-- hibernate tools -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-tools</artifactId>
    </dependency>
    <dependency>
      <groupId>com.yahoo.platform.yui</groupId>
      <artifactId>yuicompressor</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>

      <!-- compiler插件, 设定JDK版本 -->
      <!--
        <plugin> <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3</version> <configuration> <source>1.6</source>
        <target>1.6</target> </configuration> </plugin>
      -->
      <!-- eclipse插件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <wtpversion>2.0</wtpversion>
          <additionalProjectnatures>
            <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
          </additionalProjectnatures>
        </configuration>
      </plugin>

      <!-- jetty插件 -->
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
      </plugin>

      <!-- Hibernate lazy load bytecode enhancement -->
      <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
          <execution>
            <id>instrument-hibernate-entity</id>
            <phase>process-classes</phase>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <tasks>
            <taskdef name="instrument"
              classname="org.hibernate.tool.instrument.javassist.InstrumentTask">
              <classpath>
                <path refid="maven.runtime.classpath" />
                <path refid="maven.plugin.classpath" />
              </classpath>
            </taskdef>
            <instrument verbose="false">
              <fileset dir="${project.build.outputDirectory}">
                <include name="**/entity/**/*.class" />
              </fileset>
            </instrument>
          </tasks>
        </configuration>
      </plugin>

      <!-- test插件,加大内存 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <argLine>-Xmx128M</argLine>
          <useSystemClassLoader>false</useSystemClassLoader>
        </configuration>
      </plugin>

      <!-- cobertura插件 ,取消不需要计算覆盖率的类 -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <configuration>
          <instrumentation>
            <excludes>
              <exclude>**/entity/**/*.class</exclude>
            </excludes>
          </instrumentation>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
Returns the TextStyleTableRecord with the specified name.

## Syntax

**C#**

``` C#
public TextStyleTableRecord Element(
	string name,
	bool openForWrite = false
)
```

**VB**

``` VB
Public Function Element (
	name As String,
	Optional openForWrite As Boolean = false
) As TextStyleTableRecord
```

### Parameters

name

Type: string
The name of the TextStyleTableRecord.

openForWrite (Optional)

Type: bool
True, if the object should be opened for-write. By default the object is opened readonly.

### Return Value
Type: TextStyleTableRecord
The TextStyleTableRecord with the specified name.
Back to Top

## See Also

#### Reference
TextStyleContainer Class
Linq2Acad Namespace

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <amendments />
    <sponsors>
      <item>
        <byRequestType />
        <fullName>Rep. Meng, Grace [D-NY-6]</fullName>
        <bioguideId>M001188</bioguideId>
        <middleName />
        <identifiers>
          <lisID>2148</lisID>
          <bioguideId>M001188</bioguideId>
          <gpoId />
        </identifiers>
        <district>6</district>
        <party>D</party>
        <firstName>Grace</firstName>
        <lastName>Meng</lastName>
        <state>NY</state>
      </item>
    </sponsors>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <systemCode>hsif00</systemCode>
          <subcommittees>
            <item>
              <systemCode>hsif14</systemCode>
              <name>Health Subcommittee</name>
              <activities>
                <item>
                  <date>2017-02-03T15:58:35Z</date>
                  <name>Referred to</name>
                </item>
              </activities>
            </item>
          </subcommittees>
          <chamber>House</chamber>
          <name>Energy and Commerce Committee</name>
          <activities>
            <item>
              <date>2017-01-31T15:04:25Z</date>
              <name>Referred to</name>
            </item>
          </activities>
        </item>
      </billCommittees>
    </committees>
    <createDate>2017-02-01T04:48:47Z</createDate>
    <titles>
      <item>
        <chamberName />
        <parentTitleType />
        <title>Medicaid Coverage of Tobacco Cessation Nonprescription Drugs Act</title>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <title>Medicaid Coverage of Tobacco Cessation Nonprescription Drugs Act</title>
        <titleType>Short Titles as Introduced</titleType>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <title>To remove the limitation on Medicaid coverage of tobacco cessation nonprescription drugs.</title>
        <titleType>Official Title as Introduced</titleType>
        <chamberCode />
      </item>
      <item>
        <chamberName />
        <parentTitleType />
        <title>Medicaid Coverage of Tobacco Cessation Nonprescription Drugs Act</title>
        <titleType>Display Title</titleType>
        <chamberCode />
      </item>
    </titles>
    <billNumber>774</billNumber>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Drug therapy</name>
          </item>
          <item>
            <name>Drug, alcohol, tobacco use</name>
          </item>
          <item>
            <name>Health promotion and preventive care</name>
          </item>
          <item>
            <name>Medicaid</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Health</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <introducedDate>2017-01-31</introducedDate>
    <laws />
    <congress>115</congress>
    <committeeReports />
    <notes />
    <cboCostEstimates />
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Ms. MENG:H.R. 774.Congress has the power to enact this legislation pursuantto the following:Article I, Section 8 of the United States Constitution.[Page H820]
]]></constitutionalAuthorityStatementText>
    <relatedBills />
    <latestAction>
      <text>Referred to the Subcommittee on Health.</text>
      <links />
      <actionDate>2017-02-03</actionDate>
    </latestAction>
    <billType>HR</billType>
    <cosponsors />
    <originChamber>House</originChamber>
    <recordedVotes />
    <version>1.0.0</version>
    <calendarNumbers />
    <title>Medicaid Coverage of Tobacco Cessation Nonprescription Drugs Act</title>
    <actions>
      <actionTypeCounts>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
        <placeholderTextForH>1</placeholderTextForH>
        <introducedInHouse>1</introducedInHouse>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>4</houseOfRepresentatives>
      </actionByCounts>
      <item>
        <actionDate>2017-02-03</actionDate>
        <committee>
          <name>Health Subcommittee</name>
          <systemCode>hsif14</systemCode>
        </committee>
        <links />
        <sourceSystem>
          1
          <name>House committee actions</name>
        </sourceSystem>
        <text>Referred to the Subcommittee on Health.</text>
        <type>Committee</type>
      </item>
      <item>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <text>Referred to the House Committee on Energy and Commerce.</text>
        <committee>
          <name>Energy and Commerce Committee</name>
          <systemCode>hsif00</systemCode>
        </committee>
        <links />
        <actionCode>H11100</actionCode>
        <actionDate>2017-01-31</actionDate>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <text>Introduced in House</text>
        <committee />
        <links />
        <actionCode>Intro-H</actionCode>
        <actionDate>2017-01-31</actionDate>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <text>Introduced in House</text>
        <committee />
        <links />
        <actionCode>1000</actionCode>
        <actionDate>2017-01-31</actionDate>
      </item>
    </actions>
    <updateDate>2017-07-31T20:00:16Z</updateDate>
    <summaries>
      <billSummaries>
        <item>
          <versionCode>00</versionCode>
          <text><![CDATA[
This bill amends title XIX (Medicaid) of the Social Security Act to eliminate restrictions on state Medicaid program coverage of nonprescription drugs for tobacco cessation. Under current law, a state Medicaid program may exclude from coverage, or otherwise restrict, such drugs, except for those recommended to pregnant women.
]]></text>
          <actionDesc>Introduced in House</actionDesc>
          <updateDate>2017-01-31T05:00:00Z</updateDate>
          <actionDate>2017-01-31</actionDate>
          <lastSummaryUpdateDate>2017-07-31T19:48:47Z</lastSummaryUpdateDate>
          <name>Introduced in House</name>
        </item>
      </billSummaries>
    </summaries>
    <policyArea>
      <name>Health</name>
    </policyArea>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
/**
 * Created by ice3x2 on 2015. 6. 13..
 */
var gulp = require('gulp');
var mocha = require('gulp-mocha');

var fs = require('fs');
var colors = require('colors');
var argv = require('yargs').argv;

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

    if(argv.single) {
        fs.stat(argv.single, function(err, stat) {
            if(err == null) {
                return runTest(argv.single);
            } else if(err.code == 'ENOENT') {
                fs.stat('test/' + argv.single, function(err, stat) {
                    if(err == null) {
                        return runTest(['test/' + argv.single]);
                    } else if(err.code == 'ENOENT') {
                        console.log(colors.red.underline(argv.single + ' is not a file.'));
                    } else {
                        console.error(err);
                    }
                });
            } else {
                console.error(err);
            }
        });
    } else {
        runTest(['test/**/*.js']);
    }

    function runTest(srcsList) {
        return gulp.src(srcsList, {read: true})
            .pipe(mocha({reporter: 'nyan',timeout : 5000}))
            .once('error', function (err) {
                console.error(err);
                process.exit(1);
            })
            .once('end', function () {
                process.exit();
            });
    }

});


text:
package org.testng.remote.strprotocol;

import static org.testng.remote.RemoteTestNG.isVerbose;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class JsonMessageSender extends BaseMessageSender {

  public JsonMessageSender(String host, int port) {
    super(host, port, false);
  }

  public JsonMessageSender(String host, int port, boolean ack) {
    super(host, port, ack);
  }

  @Override
  public void sendMessage(IMessage message) throws Exception {
    if (m_outStream == null) {
      throw new IllegalStateException("Trying to send a message on a shutdown sender");
    }

    synchronized (m_outStream) {
      p("Sending message " + message);

      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(m_outStream, "UTF-8"));
      JsonWriter writer = new JsonWriter(bw);
      writeMessage(writer, message);
      bw.newLine();
      bw.flush();

      waitForAck();
    }
  }

  void writeMessage(JsonWriter writer, IMessage message) throws IOException {
    writer.beginObject();

    MessageType messageType = message.getType();
    writer.name("type").value(messageType.getValue());
    writer.name("data");
    Gson gson = new GsonBuilder().create();
    gson.toJson(message, message.getClass(), writer);

    writer.endObject();
  }

  @Override
  public IMessage receiveMessage() throws Exception {
    if (m_inReader == null) {
      try {
        m_inReader = new BufferedReader(new InputStreamReader(m_inStream, "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        m_inReader = new BufferedReader(new InputStreamReader(m_inStream));
      }
    }
    String msg = m_inReader.readLine();
    p("received message: " + msg);

    IMessage message = null;
    if (msg != null) {
      message = deserializeMessage(msg);
    }

    try {
      sendAck();
    } catch (Exception e) {
      if (isVerbose()) {
        System.out.println("sendAck failed with error: " + e.getMessage());
        e.printStackTrace();
      }
    }
    return message;
  }

  IMessage deserializeMessage(String jsonMsg) throws IOException {
    try (JsonReader reader = new JsonReader(new StringReader(jsonMsg))) {
      reader.beginObject();

      String name = reader.nextName();
      if (!"type".equals(name)) {
        throw new IOException("type node first");
      }

      int msgType = reader.nextInt();
      MessageType type = MessageType.fromValue(msgType);
      if (type == null) {
        throw new IOException("unknown message type: " + msgType + ", raw json: " + jsonMsg);
      }

      name = reader.nextName();
      if (!"data".equals(name)) {
        throw new IOException("data node then");
      }

      Gson gson = new GsonBuilder().create();
      IMessage message = null;
      switch (type) {
      case GENERIC:
        message = gson.fromJson(reader, GenericMessage.class);
        break;
      case SUITE:
        message = gson.fromJson(reader, SuiteMessage.class);
        break;
      case TEST:
        message = gson.fromJson(reader, TestMessage.class);
        break;
      case TEST_RESULT:
        message = gson.fromJson(reader, TestResultMessage.class);
        break;
      default:
        throw new IOException("unsupported message type: " + msgType + ", raw json: " + jsonMsg);
      }

      reader.endObject();

      return message;
    }
  }

  private static void p(String msg) {
    if (isVerbose()) {
      System.out.println("[JsonMessageSender] " + msg); //$NON-NLS-1$
    }
  }
}


text:
require 'bundler'
Bundler.setup(:default, :development)

require 'mongoid-scroll'
require 'faker'

Mongoid.connect_to 'mongoid_scroll_demo'
Mongoid.purge!

module Feed
  class Item
    include Mongoid::Document
    field :title, type: String
    field :position, type: Integer
    index(position: 1, _id: 1)
  end
end

# total items to insert
total_items = 20
# a MongoDB query will be executed every scroll_by items
scroll_by = 7

# insert items with a position out-of-order
rands = (0..total_items).to_a.sort { rand }[0..total_items]
total_items.times do |_i|
  Feed::Item.create! title: Faker::Lorem.sentence, position: rands.pop
end

Moped.logger = Logger.new($stdout)
Moped.logger.level = Logger::DEBUG

Feed::Item.create_indexes

total_shown = 0
next_cursor = nil
loop do
  current_cursor = next_cursor
  next_cursor = nil
  Feed::Item.asc(:position).limit(scroll_by).scroll(current_cursor) do |item, cursor|
    puts "#{item.position}: #{item.title}"
    next_cursor = cursor
    total_shown += 1
  end
  break unless next_cursor
  # destroy an item just for the heck of it, scroll is not affected
  Feed::Item.asc(:position).first.destroy
end

# this will be 20
puts "Shown #{total_shown} items."


text:
package meetNow.logic;

public class CreateException extends Exception {

	private static final long serialVersionUID = 1L;

}


text:
var list = new LinkedList();
list.append(15);
list.print();
console.log(list.indexOf(15));
list.append(10);
list.print();
console.log(list.indexOf(10));
list.append(13);
list.print();
console.log(list.indexOf(13));
console.log(list.indexOf(10));
list.append(11);
list.append(12);
list.print();
console.log(list.removeAt(1));
list.print()
console.log(list.removeAt(3));
list.print();
list.append(14);
list.print();
list.insert(0,16);
list.print();
list.insert(1,17);
list.print();
list.insert(list.size(),18);
list.print();
list.remove(16);
list.print();
list.remove(11);
list.print();
list.remove(18);
list.print();


text:
<?php

namespace Sistema\SisreimpBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sistema\SisreimpBundle\Entity\PatenteVehiculo;
use Sistema\SisreimpBundle\Form\PatenteVehiculoType;

/**
 * PatenteVehiculo controller.
 *
 * @Route("/patentevehiculo")
 */
class PatenteVehiculoController extends Controller
{

    /**
     * Lists all PatenteVehiculo entities.
     *
     * @Route("/", name="patentevehiculo")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('SistemaSisreimpBundle:PatenteVehiculo')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new PatenteVehiculo entity.
     *
     * @Route("/", name="patentevehiculo_create")
     * @Method("POST")
     * @Template("SistemaSisreimpBundle:PatenteVehiculo:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new PatenteVehiculo();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('patentevehiculo_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a PatenteVehiculo entity.
    *
    * @param PatenteVehiculo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(PatenteVehiculo $entity)
    {
        $form = $this->createForm(new PatenteVehiculoType(), $entity, array(
            'action' => $this->generateUrl('patentevehiculo_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new PatenteVehiculo entity.
     *
     * @Route("/new", name="patentevehiculo_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new PatenteVehiculo();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a PatenteVehiculo entity.
     *
     * @Route("/{id}", name="patentevehiculo_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SistemaSisreimpBundle:PatenteVehiculo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PatenteVehiculo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing PatenteVehiculo entity.
     *
     * @Route("/{id}/edit", name="patentevehiculo_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SistemaSisreimpBundle:PatenteVehiculo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PatenteVehiculo entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a PatenteVehiculo entity.
    *
    * @param PatenteVehiculo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(PatenteVehiculo $entity)
    {
        $form = $this->createForm(new PatenteVehiculoType(), $entity, array(
            'action' => $this->generateUrl('patentevehiculo_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing PatenteVehiculo entity.
     *
     * @Route("/{id}", name="patentevehiculo_update")
     * @Method("PUT")
     * @Template("SistemaSisreimpBundle:PatenteVehiculo:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SistemaSisreimpBundle:PatenteVehiculo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PatenteVehiculo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('patentevehiculo_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a PatenteVehiculo entity.
     *
     * @Route("/{id}", name="patentevehiculo_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('SistemaSisreimpBundle:PatenteVehiculo')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find PatenteVehiculo entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('patentevehiculo'));
    }

    /**
     * Creates a form to delete a PatenteVehiculo entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('patentevehiculo_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php

require_once("inc_menu.php");
require_once("inc_tabbar.php");

$page['title'] = getlocal("page_agent.title");
$page['menuid'] = $page['opid'] == $page['currentopid'] ? "profile" : "operators";

function tpl_content() { global $page, $mibewroot, $errors;
?>

<?php if( $page['opid'] ) { ?>
<?php echo getlocal("page_agent.intro") ?>
<?php } ?>
<?php if( !$page['opid'] ) { ?>
<?php echo getlocal("page_agent.create_new") ?>
<?php } ?>

<?php
require_once('inc_errors.php');
?>
<?php if( $page['needChangePassword'] ) { ?>

<?php echo getlocal("error.no_password") ?>

<?php } else if( $page['stored'] ) { ?>

<?php echo getlocal("data.saved") ?>

<?php } ?>

<?php if( $page['opid'] || $page['canmodify'] ) { ?>
<form name="agentForm" method="post" action="<?php echo $mibewroot ?>/operator/operator.php">
<?php print_csrf_token_input() ?>
<input type="hidden" name="opid" value="<?php echo safe_htmlspecialchars($page['opid']) ?>"/>
<?php if(!$page['showjabber']) { ?>
<input type="hidden" name="jabber" value="<?php echo form_value('jabber') ?>"/>
<?php if(form_value_cb('jabbernotify')) { ?><input type="hidden" name="jabbernotify" value="on"/><?php } ?>
<?php } ?>

<?php if(!$page['needChangePassword']) { print_tabbar(); } ?>

<?php echo getlocal('form.field.login') ?>*

				<input type="text" name="login" size="40" value="<?php echo form_value('login') ?>" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.login.description') ?>

<?php echo getlocal('form.field.mail') ?>

				<input type="text" name="email" size="40" value="<?php echo form_value('email') ?>" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.mail.description') ?>

<?php echo getlocal('form.field.password') ?><?php if( !$page['opid'] || $page['needChangePassword'] ) { ?>*<?php } ?>

				<input type="password" name="password" size="40" value="" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?> autocomplete="off"/>

 — <?php echo getlocal('form.field.password.description') ?>

<?php echo getlocal('form.field.password_confirm') ?><?php if( !$page['opid'] || $page['needChangePassword'] ) { ?>*<?php } ?>

				<input type="password" name="passwordConfirm" size="40" value="" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?> autocomplete="off"/>

 — <?php echo getlocal('form.field.password_confirm.description') ?>

<?php echo getlocal('form.field.agent_name') ?>*

				<input type="text" name="name" size="40" value="<?php echo form_value('name') ?>" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.agent_name.description') ?>

<?php echo getlocal('form.field.agent_commonname') ?>*

				<input type="text" name="commonname" size="40" value="<?php echo form_value('commonname') ?>" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.agent_commonname.description') ?>

<?php if($page['showjabber']) { ?>

<?php echo getlocal('form.field.jabber') ?>

				<input type="text" name="jabber" size="40" value="<?php echo form_value('jabber') ?>" class="formauth"<?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.jabber.description') ?>

<?php echo getlocal('form.field.jabbernotify') ?>

				<input type="checkbox" name="jabbernotify" value="on"<?php echo form_value_cb('jabbernotify') ? " checked=\"checked\"" : "" ?><?php echo $page['canmodify'] ? "" : " disabled=\"disabled\"" ?>/>

 — <?php echo getlocal('form.field.jabbernotify.description') ?>

<?php } ?>

<?php if($page['canmodify']) { ?>

			<input type="image" name="save" value="" src="<?php echo $mibewroot . safe_htmlspecialchars(getlocal("image.button.save")) ?>" alt="<?php echo safe_htmlspecialchars(getlocal("button.save")) ?>"/>

<?php } ?>

		<?php echo getlocal("common.asterisk_explanation") ?>

</form>
<?php } ?>
<?php
} /* content */

require_once('inc_main.php');
?>


text:
{% load crispy_forms_tags %}

{% if control == "button" %}

    <button type="button" class="btn btn-secondary btn-sm" data-property-editor="true" data-form-id="form-node-{{ node_id }}-edit-properties">
       {{ labels }}
    </button>

{% endif %}

{% if control == "editor" %}

    <form action="{% url 'cvgraph:change' %}" class="form-horizontal" method="post">
      {% csrf_token %}
      <input type="hidden" name="_labels" value="{{ labels }}"/>
      <input type="hidden" name="_id" value="{{ node_id }}"/>
      <input type="hidden" name="_operation" value="update"/>
      {{ form|crispy }}

          <button type="submit" class="btn">Save</button>

    </form>

{% endif %}


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the LinuxOsInfo class.
 * @constructor
 * Information about a Linux OS.
 * @member {string} [linuxOsState] The state of the Linux OS. Possible values
 * include: 'NonDeprovisioned', 'DeprovisionRequested', 'DeprovisionApplied'
 *
 */
function LinuxOsInfo() {
}

/**
 * Defines the metadata of LinuxOsInfo
 *
 * @returns {object} metadata of LinuxOsInfo
 *
 */
LinuxOsInfo.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'LinuxOsInfo',
    type: {
      name: 'Composite',
      className: 'LinuxOsInfo',
      modelProperties: {
        linuxOsState: {
          required: false,
          serializedName: 'linuxOsState',
          type: {
            name: 'String'
          }
        }
      }
    }
  };
};

module.exports = LinuxOsInfo;


text:
from .api import *
from .main import *
from .controller_utils import *
from .admin import *
from .user import *


text:
'''serializer_helper.py'''

from heronpy.api.serializer import PythonSerializer

import heronpy.api.api_constants as constants

import heron.common.src.python.pex_loader as pex_loader

class SerializerHelper(object):
  """Helper class for getting serializer for component"""
  @staticmethod
  def get_serializer(context):
    """Returns a serializer for a given context"""
    cluster_config = context.get_cluster_config()
    serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None)
    if serializer_clsname is None:
      return PythonSerializer()
    else:
      try:
        topo_pex_path = context.get_topology_pex_path()
        pex_loader.load_pex(topo_pex_path)
        serializer_cls = pex_loader.import_and_get_class(topo_pex_path, serializer_clsname)
        serializer = serializer_cls()
        return serializer
      except Exception as e:
        raise RuntimeError("Error with loading custom serializer class: %s, with error message: %s"
                           % (serializer_clsname, str(e)))


text:
require("./spec_helper");

var stik = window.stik;

describe("Context", function(){
  describe("#load", function(){
    it("should run the execution unit it is bound to", function(){
      var template, modules, executionUnitDouble, injectedTemplate;

      injectedTemplate = false;

      template = document.createElement( "div" );

      executionUnitDouble = function( $template ){
        injectedTemplate = $template;
      };

      context = stik.context({
        controller: "AppCtrl",
        action: "list",
        template: template
      });

      context.load( executionUnitDouble, {} );

      expect( injectedTemplate ).toEqual( template );
    });
  });
});


text: export const API_ENDPOINT: string = 'https://qc-inpections.herokuapp.com/api';


text:
@implementation SPoTCDTVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(!self.managedObjectContext)
    {
        [self useSPoTDocument];
    }
    else
    {
        NSLog(@"Already have a managed object context");
    }
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
}

-(IBAction)refresh
{
    [self.refreshControl beginRefreshing];
    dispatch_queue_t fetchQ = dispatch_queue_create("Flickr Fetch", NULL);
    dispatch_async(fetchQ, ^{
        NSArray *photos = [FlickrFetcher stanfordPhotos];
        // Put the photos in CoreData
        [self.managedObjectContext performBlock:^{
            for(NSDictionary *photo in photos)
            {
                [Photo photoWithFlickrInfo:photo inManagedObjectContext:self.managedObjectContext];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.refreshControl endRefreshing];
            });
        }];
    });
}

-(void)useSPoTDocument
{
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"SPoT"];
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
    if(![[NSFileManager defaultManager] fileExistsAtPath:[url path]])
    {
        NSLog(@"Creating the demo document (%@)", [url path]);
        [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            if(success)
            {
                self.managedObjectContext = document.managedObjectContext;
                [self refresh];
            }
            else
            {
                NSLog(@"Could not create the document at %@", url);
            }
        }];
    }
    else if(document.documentState == UIDocumentStateClosed)
    {
        [document openWithCompletionHandler:^(BOOL success) {
            if(success)
            {
                self.managedObjectContext = document.managedObjectContext;
            }
        }];
    }
    else
    {
        self.managedObjectContext = document.managedObjectContext;
    }
}

@end


text:
ACCEPTED

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

#### Published in
Pilze aus dem Umanakdist. 12 (1897)

#### Original name
Phoma armeriae-sibericae Allesch., 1897

### Remarks
null


text:
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/core/test_utils.html">
<link rel="import" href="/core/trace_model/object_collection.html">

<script>
'use strict';

tv.b.unittest.testSuite(function() { // @suppress longLineCheck
  var TestObjectInstance = function(parent, id, category, name, creationTs) {
    tv.c.trace_model.ObjectInstance.call(
        this, parent, id, category, name, creationTs);
  };

  TestObjectInstance.prototype = {
    __proto__: tv.c.trace_model.ObjectInstance.prototype
  };

  test('objectInstanceSubtype', function() {
    // Register that TestObjects are bound to TestObjectInstance.
    tv.c.trace_model.ObjectInstance.register(
        TestObjectInstance,
        {typeName: 'TestObject'});

    try {
      var collection = new tv.c.trace_model.ObjectCollection({ });
      collection.idWasCreated(
          '0x1000', 'tv.e.cc', 'Frame', 10);
      collection.idWasDeleted(
          '0x1000', 'tv.e.cc', 'Frame', 15);
      collection.idWasCreated(
          '0x1000', 'skia', 'TestObject', 20);
      collection.idWasDeleted(
          '0x1000', 'skia', 'TestObject', 25);

      var testFrame = collection.getObjectInstanceAt('0x1000', 10);
      assert.instanceOf(testFrame, tv.c.trace_model.ObjectInstance);
      assert.notInstanceOf(testFrame, TestObjectInstance);

      var testObject = collection.getObjectInstanceAt('0x1000', 20);
      assert.instanceOf(testObject, tv.c.trace_model.ObjectInstance);
      assert.instanceOf(testObject, TestObjectInstance);
    } finally {
      tv.c.trace_model.ObjectInstance.unregister(TestObjectInstance);
    }
  });

  test('twoSnapshots', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasCreated(
        '0x1000', 'cat', 'Frame', 10);
    collection.addSnapshot(
        '0x1000', 'cat', 'Frame', 10, {foo: 1});
    collection.addSnapshot(
        '0x1000', 'cat', 'Frame', 20, {foo: 2});

    collection.updateBounds();
    assert.equal(collection.bounds.min, 10);
    assert.equal(collection.bounds.max, 20);

    var s0 = collection.getSnapshotAt('0x1000', 1);
    assert.isUndefined(s0);

    var s1 = collection.getSnapshotAt('0x1000', 10);
    assert.equal(s1.args.foo, 1);

    var s2 = collection.getSnapshotAt('0x1000', 15);
    assert.equal(s2.args.foo, 1);
    assert.equal(s1, s2);

    var s3 = collection.getSnapshotAt('0x1000', 20);
    assert.equal(s3.args.foo, 2);
    assert.equal(s1.object, s3.object);

    var s4 = collection.getSnapshotAt('0x1000', 25);
    assert.equal(s4, s3);
  });

  test('twoObjectsSharingOneID', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasCreated(
        '0x1000', 'tv.e.cc', 'Frame', 10);
    collection.idWasDeleted(
        '0x1000', 'tv.e.cc', 'Frame', 15);
    collection.idWasCreated(
        '0x1000', 'skia', 'Picture', 20);
    collection.idWasDeleted(
        '0x1000', 'skia', 'Picture', 25);

    var frame = collection.getObjectInstanceAt('0x1000', 10);
    assert.equal(frame.category, 'tv.e.cc');
    assert.equal(frame.name, 'Frame');

    var picture = collection.getObjectInstanceAt('0x1000', 20);
    assert.equal(picture.category, 'skia');
    assert.equal(picture.name, 'Picture');

    var typeNames = tv.b.dictionaryKeys(collection.getAllInstancesByTypeName());
    typeNames.sort();
    assert.deepEqual(
        ['Frame', 'Picture'],
        typeNames);
    assert.deepEqual(
        [frame],
        collection.getAllInstancesByTypeName()['Frame']);
    assert.deepEqual(
        [picture],
        collection.getAllInstancesByTypeName()['Picture']);
  });

  test('createSnapDelete', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasCreated(
        '0x1000', 'cat', 'Frame', 10);
    collection.addSnapshot(
        '0x1000', 'cat', 'Frame', 10, {foo: 1});
    collection.idWasDeleted(
        '0x1000', 'cat', 'Frame', 15);

    collection.updateBounds();
    assert.equal(collection.bounds.min, 10);
    assert.equal(collection.bounds.max, 15);

    var s10 = collection.getSnapshotAt('0x1000', 10);
    var i10 = s10.objectInstance;
    assert.equal(i10.creationTs, 10);
    assert.equal(i10.deletionTs, 15);
  });

  test('boundsOnUndeletedObject', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasCreated(
        '0x1000', 'cat', 'Frame', 10);
    collection.addSnapshot(
        '0x1000', 'cat', 'Frame', 15, {foo: 1});

    collection.updateBounds();
    assert.equal(10, collection.bounds.min);
    assert.equal(15, collection.bounds.max);
  });

  test('snapshotWithCustomBaseTypeThenDelete', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    var s10 = collection.addSnapshot(
        '0x1000', 'cat', 'cc::PictureLayerImpl', 10, {}, 'cc::LayerImpl');
    collection.idWasDeleted(
        '0x1000', 'cat', 'cc::LayerImpl', 15);
    collection.updateBounds();
    assert.equal(10, collection.bounds.min);
    assert.equal(15, collection.bounds.max);
    assert.equal(s10.objectInstance.name, 'cc::PictureLayerImpl');
    assert.equal(s10.objectInstance.baseTypeName, 'cc::LayerImpl');
  });

  test('newWithSnapshotThatChangesBaseType', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    var i10 = collection.idWasCreated(
        '0x1000', 'cat', 'cc::LayerImpl', 10);
    var s15 = collection.addSnapshot(
        '0x1000', 'cat', 'cc::PictureLayerImpl', 15, {}, 'cc::LayerImpl');
    collection.updateBounds();
    assert.equal(10, collection.bounds.min);
    assert.equal(15, collection.bounds.max);
    assert.equal(s15.objectInstance, i10);
    assert.equal(i10.name, 'cc::PictureLayerImpl');
    assert.equal(i10.baseTypeName, 'cc::LayerImpl');
  });

  test('deleteThenSnapshotWithCustomBase', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasDeleted(
        '0x1000', 'cat', 'cc::LayerImpl', 10);
    var s15 = collection.addSnapshot(
        '0x1000', 'cat', 'cc::PictureLayerImpl', 15, {}, 'cc::LayerImpl');
    collection.updateBounds();
    assert.equal(10, collection.bounds.min);
    assert.equal(15, collection.bounds.max);
    assert.equal(s15.objectInstance.name, 'cc::PictureLayerImpl');
  });

  test('autoDelete', function() {
    var collection = new tv.c.trace_model.ObjectCollection({});
    collection.idWasCreated(
        '0x1000', 'cat', 'Frame', 10);
    collection.addSnapshot(
        '0x1000', 'cat', 'Frame', 10, {foo: 1});
    collection.autoDeleteObjects(15);

    var s10 = collection.getSnapshotAt('0x1000', 10);
    var i10 = s10.objectInstance;
    assert.equal(15, i10.deletionTs);
  });
});
</script>


text:
/***************************************************************/
/***            Psyco equivalent of classobject.h              ***/
/***************************************************************/

#ifndef _PSY_CLASSOBJECT_H
#define _PSY_CLASSOBJECT_H

#include "pabstract.h"
#include "pobject.h"

/* Instance methods */
#define METHOD_im_func DEF_FIELD(PyMethodObject, PyObject *, im_func, OB_type)
#define METHOD_im_self                                                         \
  DEF_FIELD(PyMethodObject, PyObject *, im_self, METHOD_im_func)
#define iMETHOD_IM_FUNC FIELD_INDEX(METHOD_im_func)
#define iMETHOD_IM_SELF FIELD_INDEX(METHOD_im_self)
#define METHOD_TOTAL FIELDS_TOTAL(METHOD_im_self)

EXTERNFN vinfo_t *pinstancemethod_call(PsycoObject *po, vinfo_t *methobj,
                                       vinfo_t *arg, vinfo_t *kw);

/***************************************************************/
/***   Virtual-time object builder                           ***/

/* not-yet-computed instance method objects. Usually not computed at all,
   but if it needs be, will call PyMethod_New(). */
EXTERNVAR source_virtual_t psyco_computed_method;

EXTERNFN
vinfo_t *PsycoMethod_New(PyObject *func, vinfo_t *self);

#endif /* _PSY_CLASSOBJECT_H */


text:
package com.stratuscom.harvester.work;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import com.stratuscom.harvester.Strings;

/**

 @author trasukg
 */
public class ContextualWorkManager {

    List<Context> contexts=new ArrayList<Context>();

    public WorkingContext createContext(String name, ClassLoader contextLoader) {
        Context context=new Context(name, contextLoader);
        contexts.add(context);
        return context;
    }

    private class Context implements WorkingContext {
        String name=Strings.UNNAMED;
        ClassLoader contextLoader;

        public String getName() {
            return name;
        }

        public Context(String name, ClassLoader contextLoader) {
            this.name=name;
            this.contextLoader=contextLoader;
            executor=new BasicExecutor(contextLoader, name);
        }

        BasicExecutor executor=null;

        @Override
        public ScheduledExecutorService getScheduledExecutorService() {
            return executor;
        }

        @Override
        public int getActiveThreadCount() {
            return executor.getActiveCount();
        }

        @Override
        public void shutdown() {
            executor.shutdownNow();
        }

        @Override
        public void interrupt() {
            executor.shutdownNow();
        }

    }
}


text:
"""d4rl_adroit_pen dataset."""
from typing import Any

from tensorflow_datasets.d4rl import dataset_builder
import tensorflow_datasets.public_api as tfds

class D4rlAdroitPen(dataset_builder.D4RLDatasetBuilder):
  """DatasetBuilder for d4rl_adroit_pen dataset."""

  VERSION = tfds.core.Version('1.1.0')
  RELEASE_NOTES = {
      '1.0.0': 'Initial release.',
      '1.1.0': 'Added is_last.',
  }

  # pytype: disable=wrong-keyword-args
  # pylint: disable=protected-access
  # Pen uses a different policy size in expert-v1
  BUILDER_CONFIGS = dataset_builder.ADROIT_BUILDER_CONFIGS[:-1] + [
      dataset_builder.BuilderConfig(
          name='v1-expert',
          dataset_dir='hand_dapg_v1',
          env='adroit',
          file_suffix='-expert-v1',
          step_metadata_keys=frozenset([
              dataset_builder._QPOS, dataset_builder._QVEL,
              dataset_builder._ADROIT_BODY_POS, dataset_builder._ACTION_MEAN,
              dataset_builder._ACTION_LOG_STD
          ]),
          episode_metadata_keys=frozenset([dataset_builder._ALGORITHM]),
          has_policy_metadata=True,
          has_policy_last_fc_log_std=True,
          policy_size=64,  # pytype: disable=wrong-arg-types  # gen-stub-imports
      ),
  ]

  # pylint: enable=protected-access
  # pytype: enable=wrong-keyword-args

  def __init__(self, **kwargs: Any):
    config = dataset_builder.DatasetConfig(
        name='pen', obs_len=45, action_len=24, qpos_len=30, qvel_len=30)
    super().__init__(ds_config=config, **kwargs)


text:
package e2e

import (
	"fmt"
	"os"
	"strings"
	"syscall"
	"time"

	"go.etcd.io/etcd/client/pkg/v3/fileutil"
	"go.etcd.io/etcd/pkg/v3/expect"
	"go.etcd.io/etcd/tests/v3/framework/integration"
	"go.uber.org/zap"
)

const noOutputLineCount = 2 // cov-enabled binaries emit PASS and coverage count lines

var (
	coverDir = integration.MustAbsPath(os.Getenv("COVERDIR"))
)

func SpawnCmdWithLogger(lg *zap.Logger, args []string, envVars map[string]string) (*expect.ExpectProcess, error) {
	cmd := args[0]
	env := mergeEnvVariables(envVars)
	switch {
	case strings.HasSuffix(cmd, "/etcd"):
		cmd = cmd + "_test"
	case strings.HasSuffix(cmd, "/etcdctl"):
		cmd = cmd + "_test"
	case strings.HasSuffix(cmd, "/etcdutl"):
		cmd = cmd + "_test"
	case strings.HasSuffix(cmd, "/etcdctl3"):
		cmd = CtlBinPath + "_test"
		env = append(env, "ETCDCTL_API=3")
	}

	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	covArgs, err := getCovArgs()
	if err != nil {
		return nil, err
	}
	// when withFlagByEnv() is used in testCtl(), env variables for ctl is set to os.env.
	// they must be included in ctl_cov_env.

	all_args := append(args[1:], covArgs...)
	lg.Info("spawning process", zap.Strings("args", all_args), zap.String("working-dir", wd))
	ep, err := expect.NewExpectWithEnv(cmd, all_args, env)
	if err != nil {
		return nil, err
	}
	ep.StopSignal = syscall.SIGTERM
	return ep, nil
}

func getCovArgs() ([]string, error) {
	if !fileutil.Exist(coverDir) {
		return nil, fmt.Errorf("could not find coverage folder: %s", coverDir)
	}
	covArgs := []string{
		fmt.Sprintf("-test.coverprofile=e2e.%v.coverprofile", time.Now().UnixNano()),
		"-test.outputdir=" + coverDir,
	}
	return covArgs, nil
}


text:
import warnings

def ErrorMiddleware(*args, **kw):
    warnings.warn(
        'weberror.exceptions.errormiddleware.ErrorMiddleware has been moved '
        'to weberror.errormiddleware.ErrorMiddleware',
        DeprecationWarning, stacklevel=2)
    from weberror.errormiddleware import ErrorMiddleware
    return ErrorMiddleware(*args, **kw)

def handle_exception(*args, **kw):
    warnings.warn(
        'weberror.exceptions.errormiddleware.handle_exception has been moved '
        'to weberror.errormiddleware.handle_exception',
        DeprecationWarning, stacklevel=2)
    from weberror.errormiddleware import handle_exceptions
    return handle_exceptions(*args, **kw)


text:
namespace TTengine.Systems
{
    #region Using statements

    using System;
    using System.Collections.Generic;
    using Artemis;
    using Artemis.Attributes;
    using Artemis.System;
    using Artemis.Manager;

    using TTengine.Comps;

    #endregion

    /// The expiration system.
    [ArtemisEntitySystem(GameLoopType = GameLoopType.Update, Layer = 3)]
    public class ExpirationSystem : EntityComponentProcessingSystem<ExpiresComp>
    {

        protected double deltaTimeStep = 0;

        protected override void ProcessEntities(IDictionary<int, Entity> entities)
        {
            // retrieve the delta time step once, before looping over all entities.
            deltaTimeStep = TimeSpan.FromTicks(this.EntityWorld.Delta).TotalSeconds;
            base.ProcessEntities(entities);
        }

        /// Processes the specified entity.
        /// <param name="entity">The entity.</param>
        public override void Process(Entity entity, ExpiresComp expiresComponent)
        {
            if (expiresComponent != null && expiresComponent.IsActive)
            {
                expiresComponent.ReduceLifeTime(deltaTimeStep);

                if (expiresComponent.IsExpired)
                {
                    entity.Delete();
                }
            }
        }
    }
}


text:
using System.Web.Mvc;
using BundlingAndMinifyingInlineCssJs.ResponseFilters;

namespace Encompass.Mvc.Attributes
{
    /// <summary>
    ///     Attribute that can be used to utilize the BundleMinifyInlineJsCss library which bundles and minifies inline
    ///     javascript and css.
    /// </summary>
    public class BundleMinifyInlineCssJsAttribute : ActionFilterAttribute
    {
        #region methods

        /// <summary>
        ///     Bundles and minifies inline javascript and css for the current action.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
            => filterContext.HttpContext.Response.Filter = new BundleAndMinifyResponseFilter(filterContext.HttpContext.Response.Filter);

        #endregion
    }
}


text:
from collections import OrderedDict
import json
import logging
import os
import random

import numpy as np
import tensorflow as tf

from tensorforce import util, TensorforceError
from tensorforce.agents import Recorder
import tensorforce.agents
from tensorforce.core import ArrayDict, TensorSpec, TensorforceConfig

class Agent(Recorder):
    """
    Tensorforce agent interface.
    """

    @staticmethod
    def create(agent='tensorforce', environment=None, **kwargs):
        """
        Create an agent from a specification.

        Args:
            agent (specification | Agent class/object | callable[states -> actions]): JSON file,
                specification key, configuration dictionary, library module, or `Agent`
                class/object. Alternatively, an act-function mapping states to actions which is
                supposed to be recorded.
                (default: Tensorforce base agent).
            environment (Environment object): Environment which the agent is supposed to be trained
                on, environment-related arguments like state/action space specifications and
                maximum episode length will be extract if given
                (recommended).
            kwargs: Additional agent arguments.
        """
        if isinstance(agent, Recorder):
            if environment is not None:
                # TODO:
                # assert agent.spec['states'] == environment.states()
                # assert agent.spec['actions'] == environment.actions()
                # assert environment.max_episode_timesteps() is None or \
                #     agent.spec['max_episode_timesteps'] >= environment.max_episode_timesteps()
                pass

            for key, value in kwargs.items():
                if key == 'parallel_interactions':
                    assert agent.spec[key] >= value
                else:
                    assert agent.spec[key] == value

            if agent.is_initialized:
                agent.reset()
            else:
                agent.initialize()

            return agent

        elif (isinstance(agent, type) and issubclass(agent, Agent)) or callable(agent):
            # Type specification, or Recorder
            if environment is not None:
                if 'states' in kwargs:
                    # TODO:
                    # assert kwargs['states'] == environment.states()
                    pass
                else:
                    kwargs['states'] = environment.states()
                if 'actions' in kwargs:
                    # assert kwargs['actions'] == environment.actions()
                    pass
                else:
                    kwargs['actions'] = environment.actions()
                if environment.max_episode_timesteps() is None:
                    pass
                elif 'max_episode_timesteps' in kwargs:
                    # assert kwargs['max_episode_timesteps'] >= environment.max_episode_timesteps()
                    pass
                else:
                    kwargs['max_episode_timesteps'] = environment.max_episode_timesteps()

            if isinstance(agent, type) and issubclass(agent, Agent):
                agent = agent(**kwargs)
                assert isinstance(agent, Agent)
            else:
                if 'recorder' not in kwargs:
                    raise TensorforceError.required(name='Recorder', argument='recorder')
                agent = Recorder(fn_act=agent, **kwargs)
            return Agent.create(agent=agent, environment=environment)

        elif isinstance(agent, dict):
            # Dictionary specification
            agent.update(kwargs)
            kwargs = dict(agent)
            agent = kwargs.pop('agent', kwargs.pop('type', 'default'))

            return Agent.create(agent=agent, environment=environment, **kwargs)

        elif isinstance(agent, str):
            if os.path.isfile(agent):
                # JSON file specification
                with open(agent, 'r') as fp:
                    agent = json.load(fp=fp)
                return Agent.create(agent=agent, environment=environment, **kwargs)

            elif agent in tensorforce.agents.agents:
                # Keyword specification
                agent = tensorforce.agents.agents[agent]
                return Agent.create(agent=agent, environment=environment, **kwargs)

            else:
                # Library specification
                _agent = util.try_import_module(module=agent, parent_class=Agent)
                if _agent is not None:
                    return Agent.create(agent=_agent, environment=environment, **kwargs)

                raise TensorforceError.value(name='Agent.create', argument='agent', value=agent)

        else:
            raise TensorforceError.type(name='Agent.create', argument='agent', dtype=type(agent))

    @staticmethod
    def load(directory=None, filename=None, format=None, environment=None, **kwargs):
        """
        Restores an agent from a directory/file.

        Args:
            directory (str): Checkpoint directory
                (required, unless saver is specified).
            filename (str): Checkpoint filename, with or without append and extension
                (default: "agent").
            format ("checkpoint" | "numpy" | "hdf5"): File format
                (default: format matching directory and
                filename, required to be unambiguous).
            environment (Environment object): Environment which the agent is supposed to be trained
                on, environment-related arguments like state/action space specifications and
                maximum episode length will be extract if given
                (recommended).
            kwargs: Additional agent arguments.
        """
        if directory is not None:
            if filename is None:
                filename = 'agent'
            agent = os.path.join(directory, os.path.splitext(filename)[0] + '.json')
            if not os.path.isfile(agent) and agent[agent.rfind('-') + 1: -5].isdigit():
                agent = agent[:agent.rindex('-')] + '.json'
            if os.path.isfile(agent):
                with open(agent, 'r') as fp:
                    agent = json.load(fp=fp)
                if 'agent' in kwargs:
                    if 'agent' in agent and agent['agent'] != kwargs['agent']:
                        raise TensorforceError.value(
                            name='Agent.load', argument='agent', value=kwargs['agent']
                        )
                    agent['agent'] = kwargs.pop('agent')
            else:
                agent = kwargs
                kwargs = dict()
        else:
            agent = kwargs
            kwargs = dict()

        # Overwrite values
        if agent.get('max_episode_timesteps') is None:
            if environment is not None and environment.max_episode_timesteps() is not None:
                if 'max_episode_timesteps' in kwargs:
                    assert kwargs['max_episode_timesteps'] >= environment.max_episode_timesteps()
                    agent['max_episode_timesteps'] = kwargs['max_episode_timesteps']
                else:
                    agent['max_episode_timesteps'] = environment.max_episode_timesteps()
        if 'parallel_interactions' in kwargs and kwargs['parallel_interactions'] > 1:
            agent['parallel_interactions'] = kwargs['parallel_interactions']

        agent.pop('internals', None)
        agent.pop('initial_internals', None)
        saver_restore = False
        if 'saver' in agent and isinstance(agent['saver'], dict):
            if not agent.get('load', True):
                raise TensorforceError.value(
                    name='Agent.load', argument='saver[load]', value=agent['saver']['load']
                )
            agent['saver'] = dict(agent['saver'])
            agent['saver']['load'] = True
            saver_restore = True
        elif 'saver' in kwargs and isinstance(kwargs['saver'], dict):
            if not kwargs.get('load', True):
                raise TensorforceError.value(
                    name='Agent.load', argument='saver[load]', value=kwargs['saver']['load']
                )
            kwargs['saver'] = dict(kwargs['saver'])
            kwargs['saver']['load'] = True
            saver_restore = True
        agent = Agent.create(agent=agent, environment=environment, **kwargs)
        if not saver_restore:
            agent.restore(directory=directory, filename=filename, format=format)

        return agent

    def __init__(
        self, states, actions, max_episode_timesteps=None, parallel_interactions=1, config=None,
        recorder=None
    ):
        util.overwrite_staticmethod(obj=self, function='create')
        util.overwrite_staticmethod(obj=self, function='load')

        # Check whether spec attribute exists
        if not hasattr(self, 'spec'):
            raise TensorforceError.required_attribute(name='Agent', attribute='spec')

        # Tensorforce config
        if config is None:
            config = dict()
        self.config = TensorforceConfig(**config)

        # TensorFlow logging
        tf.get_logger().setLevel(self.config.tf_log_level)

        # TensorFlow eager mode
        if self.config.eager_mode:
            tf.config.run_functions_eagerly(run_eagerly=True)

        # Random seed
        if self.config.seed is not None:
            random.seed(a=self.config.seed)
            np.random.seed(seed=self.config.seed)
            tf.random.set_seed(seed=self.config.seed)

        super().__init__(
            fn_act=None, states=states, actions=actions,
            max_episode_timesteps=max_episode_timesteps,
            parallel_interactions=parallel_interactions, recorder=recorder
        )

    def __str__(self):
        return self.__class__.__name__

    def get_specification(self):
        """
        Returns the agent specification.

        Returns:
            dict: Agent specification.
        """
        return dict(self.spec)

    def get_architecture(self):
        """
        Returns a string representation of the network layer architecture (policy, baseline,
        state-preprocessing).

        Returns:
            str: String representation of network architecture.
        """
        return self.model.get_architecture()

    def initialize(self):
        """
        Initializes the agent. Automatically triggered as part of Agent.create/load.
        """
        super().initialize()

        # Initialize model
        if not hasattr(self, 'model'):
            raise TensorforceError.required_attribute(name='Agent', attribute='model')
        self.model.initialize()

        # Value space specifications
        assert self.states_spec == self.model.states_spec
        self.internals_spec = self.model.internals_spec
        self.auxiliaries_spec = self.model.auxiliaries_spec
        assert self.actions_spec == self.model.actions_spec
        assert self.terminal_spec == self.model.terminal_spec
        assert self.reward_spec == self.model.reward_spec
        assert self.parallel_spec == self.model.parallel_spec
        self.deterministic_spec = self.model.deterministic_spec

        # Parallel observe buffers
        self.terminal_buffer = [list() for _ in range(self.parallel_interactions)]
        self.reward_buffer = [list() for _ in range(self.parallel_interactions)]

        # Store agent spec as JSON
        if self.model.saver is not None:
            path = os.path.join(self.model.saver_directory, self.model.saver_filename + '.json')
            try:
                with open(path, 'w') as fp:
                    spec = OrderedDict(self.spec)
                    spec['internals'] = self.internals_spec
                    spec['initial_internals'] = self.initial_internals()
                    json.dump(obj=spec, fp=fp, cls=TensorforceJSONEncoder)
            except BaseException:
                try:
                    with open(path, 'w') as fp:
                        spec = OrderedDict()
                        spec['states'] = self.spec['states']
                        spec['actions'] = self.spec['actions']
                        spec['internals'] = self.internals_spec
                        spec['initial_internals'] = self.initial_internals()
                        json.dump(obj=spec, fp=fp, cls=TensorforceJSONEncoder)
                except BaseException:
                    os.remove(path)
                    raise

        # Reset model
        timesteps, episodes, updates = self.model.reset()
        self.timesteps = timesteps.numpy().item()
        self.episodes = episodes.numpy().item()
        self.updates = updates.numpy().item()

    def close(self):
        """
        Closes the agent.
        """
        super().close()
        self.model.close()
        del self.model

    def reset(self):
        """
        Resets possibly inconsistent internal values, for instance, after saving and restoring an
        agent. Automatically triggered as part of Agent.create/load/initialize/restore.
        """
        super().reset()

        # Reset observe buffers
        for buffer in self.terminal_buffer:
            buffer.clear()
        for buffer in self.reward_buffer:
            buffer.clear()

        # Reset model
        timesteps, episodes, updates = self.model.reset()
        self.timesteps = timesteps.numpy().item()
        self.episodes = episodes.numpy().item()
        self.updates = updates.numpy().item()

        if self.model.saver is not None:
            self.model.save()

    def initial_internals(self):
        """
        Returns the initial internal agent state(s), to be used at the beginning of an episode as
        `internals` argument for `act()` in independent mode

        Returns:
            dict[internal]: Dictionary containing initial internal agent state(s).
        """
        return self.model.initial_internals.to_dict()

    def tracked_tensors(self):
        """
        Returns the current value of all tracked tensors (as specified by "tracking" agent
        argument). Note that not all tensors change at every timestep.

        Returns:
            dict[values]: Dictionary containing the current value of all tracked tensors.
        """
        return self.model.tracked_tensors()

    def act(
        self, states, internals=None, parallel=0, independent=False, deterministic=True,
        # Deprecated
        evaluation=None
    ):
        """
        Returns action(s) for the given state(s), needs to be followed by `observe()` unless
        independent mode.

        See the [act-observe script](https://github.com/tensorforce/tensorforce/blob/master/examples/act_observe_interface.py)
        for an example application as part of the act-observe interface.

        Args:
            states (dict[state] | iter[dict[state]]): Dictionary containing state(s) to be acted on
                (required).
            internals (dict[internal] | iter[dict[internal]]): Dictionary containing current
                internal agent state(s), either given by `initial_internals()` at the beginning of
                an episode or as return value of the preceding `act()` call
                (required if independent mode and agent
                has internal states).
            parallel (int | iter[int]): Parallel execution index
                (default: 0).
            independent (bool): Whether act is not part of the main agent-environment interaction,
                and this call is thus not followed by observe()
                (default: false).
            deterministic (bool): Whether action should be chosen deterministically, so no
                sampling and no exploration, only valid in independent mode
                (default: true).

        Returns:
            dict[action] | iter[dict[action]], dict[internal] | iter[dict[internal]] if `internals`
            argument given: Dictionary containing action(s), dictionary containing next internal
            agent state(s) if independent mode.
        """
        if evaluation is not None:
            raise TensorforceError.deprecated(
                name='Agent.act', argument='evaluation', replacement='independent'
            )

        return super().act(
            states=states, internals=internals, parallel=parallel, independent=independent,
            deterministic=deterministic
        )

    def fn_act(
        self, states, internals, parallel, independent, deterministic, is_internals_none,
        num_parallel
    ):

        # Separate auxiliaries
        def function(name, spec):
            auxiliary = ArrayDict()
            if self.config.enable_int_action_masking and spec.type == 'int' and \
                    spec.num_values is not None:
                if name is None:
                    name = 'action'
                # Mask, either part of states or default all true
                auxiliary['mask'] = states.pop(name + '_mask', np.ones(
                    shape=(num_parallel,) + spec.shape + (spec.num_values,), dtype=spec.np_type()
                ))
            return auxiliary

        auxiliaries = self.actions_spec.fmap(function=function, cls=ArrayDict, with_names=True)
        if self.states_spec.is_singleton() and not states.is_singleton():
            states[None] = states.pop('state')

        # Inputs to tensors
        states = self.states_spec.to_tensor(value=states, batched=True, name='Agent.act states')
        if independent and not is_internals_none:
            internals = self.internals_spec.to_tensor(
                value=internals, batched=True, recover_empty=True, name='Agent.act internals'
            )
        auxiliaries = self.auxiliaries_spec.to_tensor(
            value=auxiliaries, batched=True, name='Agent.act auxiliaries'
        )
        if independent:
            deterministic = self.deterministic_spec.to_tensor(
                value=deterministic, batched=False, name='Agent.act deterministic'
            )
        else:
            parallel = self.parallel_spec.to_tensor(
                value=parallel, batched=True, name='Agent.act parallel'
            )

        # Model.act()
        if not independent:
            actions, timesteps = self.model.act(
                states=states, auxiliaries=auxiliaries, parallel=parallel
            )
            self.timesteps = timesteps.numpy().item()

        elif len(self.internals_spec) > 0:
            if len(self.auxiliaries_spec) > 0:
                actions, internals = self.model.independent_act(
                    states=states, internals=internals, auxiliaries=auxiliaries,
                    deterministic=deterministic
                )
            else:
                assert len(auxiliaries) == 0
                actions, internals = self.model.independent_act(
                    states=states, internals=internals, deterministic=deterministic
                )

        else:
            if len(self.auxiliaries_spec) > 0:
                actions = self.model.independent_act(
                    states=states, auxiliaries=auxiliaries, deterministic=deterministic
                )
            else:
                assert len(auxiliaries) == 0
                actions = self.model.independent_act(states=states, deterministic=deterministic)

        # Outputs from tensors
        actions = self.actions_spec.from_tensor(
            tensor=actions, batched=True, name='Agent.act output actions'
        )
        if independent and len(self.internals_spec) > 0:
            internals = self.internals_spec.from_tensor(
                tensor=internals, batched=True, name='Agent.act output internals'
            )

        if self.model.saver is not None:
            self.model.save()

        return actions, internals

    def observe(self, reward=0.0, terminal=False, parallel=0):
        """
        Observes reward and whether a terminal state is reached, needs to be preceded by `act()`.

        See the [act-observe script](https://github.com/tensorforce/tensorforce/blob/master/examples/act_observe_interface.py)
        for an example application as part of the act-observe interface.

        Args:
            reward (float | iter[float]): Reward
                (default: 0.0).
            terminal (bool | 0 | 1 | 2 | iter[...]): Whether a terminal state is reached, or 2 if
                the episode was aborted
                (default: false).
            parallel (int, iter[int]): Parallel execution index
                (default: 0).

        Returns:
            int: Number of performed updates.
        """
        reward, terminal, parallel = super().observe(
            reward=reward, terminal=terminal, parallel=parallel
        )

        # Process per parallel interaction
        num_updates = 0
        for p, t, r in zip(parallel.tolist(), terminal.tolist(), reward.tolist()):

            # Buffer inputs
            self.terminal_buffer[p].append(t)
            self.reward_buffer[p].append(r)

            # Continue if not terminal and buffer_observe
            if t == 0 and (
                self.config.buffer_observe == 'episode' or
                len(self.terminal_buffer[p]) < self.config.buffer_observe
            ):
                continue

            # Buffered terminal/reward inputs
            ts = np.asarray(self.terminal_buffer[p], dtype=self.terminal_spec.np_type())
            rs = np.asarray(self.reward_buffer[p], dtype=self.reward_spec.np_type())
            self.terminal_buffer[p].clear()
            self.reward_buffer[p].clear()

            # Inputs to tensors
            terminal_tensor = self.terminal_spec.to_tensor(
                value=ts, batched=True, name='Agent.observe terminal'
            )
            reward_tensor = self.reward_spec.to_tensor(
                value=rs, batched=True, name='Agent.observe reward'
            )
            parallel_tensor = self.parallel_spec.to_tensor(
                value=p, batched=False, name='Agent.observe parallel'
            )

            # Model.observe()
            updated, episodes, updates = self.model.observe(
                terminal=terminal_tensor, reward=reward_tensor, parallel=parallel_tensor
            )
            num_updates += int(updated.numpy().item())
            self.episodes = episodes.numpy().item()
            self.updates = updates.numpy().item()

        if self.model.saver is not None:
            self.model.save()

        return num_updates

    def save(self, directory, filename=None, format='checkpoint', append=None):
        """
        Saves the agent to a checkpoint.

        Args:
            directory (str): Checkpoint directory
                (required).
            filename (str): Checkpoint filename, without extension
                (default: agent name).
            format ("checkpoint" | "saved-model" | "numpy" | "hdf5"): File format, "checkpoint"
                uses the [TensorFlow Checkpoint](https://www.tensorflow.org/guide/checkpoint) to
                save the model, "saved-model" uses the
                [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) to save an
                optimized act-only model (use only if you really need TF's SavedModel format,
                loading not supported), whereas the others store only variables as NumPy/HDF5 file
                (default: TensorFlow Checkpoint).
            append ("timesteps" | "episodes" | "updates"): Append timestep/episode/update to
                checkpoint filename
                (default: none).

        Returns:
            str: Checkpoint path.
        """
        # TODO: Messes with required parallel disentangling, better to remove unfinished episodes
        # from memory, but currently entire episode buffered anyway...
        # Empty buffers before saving
        # for parallel in range(self.parallel_interactions):
        #     if self.buffer_indices[parallel] > 0:
        #         self.model_observe(parallel=parallel)
        os.makedirs(directory, exist_ok=True)
        path = self.model.save(directory=directory, filename=filename, format=format, append=append)

        if filename is None:
            filename = self.model.name
        spec_path = os.path.join(directory, filename + '.json')
        try:
            with open(spec_path, 'w') as fp:
                spec = OrderedDict(self.spec)
                spec['internals'] = self.internals_spec
                spec['initial_internals'] = self.initial_internals()
                json.dump(obj=spec, fp=fp, cls=TensorforceJSONEncoder)
        except BaseException:
            logging.warning("Some agent argument could not be encoded to JSON as part of "
                            "Agent.save(), likely a Python object or class. Either specify as "
                            "module string or dictionary, or pass the full set of agent arguments "
                            "when loading via Agent.load().")
            try:
                with open(spec_path, 'w') as fp:
                    spec = OrderedDict()
                    spec['states'] = self.spec['states']
                    spec['actions'] = self.spec['actions']
                    spec['internals'] = self.internals_spec
                    spec['initial_internals'] = self.initial_internals()
                    json.dump(obj=spec, fp=fp, cls=TensorforceJSONEncoder)
            except BaseException:
                os.remove(spec_path)

        return path

    def restore(self, directory=None, filename=None, format=None):
        """
        Restores the agent from a checkpoint.

        Args:
            directory (str): Checkpoint directory
                (required).
            filename (str): Checkpoint filename, with or without append and extension
                (default: agent name).
            format ("checkpoint" | "numpy" | "hdf5"): File format
                (default: format matching directory and
                filename, required to be unambiguous).
        """
        if not hasattr(self, 'model'):
            raise TensorforceError(message="Missing agent attribute model.")

        if not self.is_initialized:
            self.initialize()

        if filename is None:
            filename = self.model.name

        # format implicitly given if file exists
        if format is None and os.path.isfile(os.path.join(directory, filename)):
            if '.data-' in filename:
                filename = filename[:filename.index('.data-')]
                format = 'checkpoint'
            elif filename.endswith('.npz'):
                filename = filename[:-4]
                format = 'numpy'
            elif filename.endswith('.hdf5'):
                filename = filename[:-5]
                format = 'hdf5'
            elif filename.endswith('.h5'):
                filename = filename[:-3]
                format = 'hdf5'
            else:
                assert False
        elif format is None and os.path.isfile(os.path.join(directory, filename + '.index')):
            format = 'checkpoint'
        elif format is None and os.path.isfile(os.path.join(directory, filename + '.npz')):
            format = 'numpy'
        elif format is None and (
            os.path.isfile(os.path.join(directory, filename + '.hdf5')) or
            os.path.isfile(os.path.join(directory, filename + '.h5'))
        ):
            format = 'hdf5'

        else:
            # infer format from directory
            found = None
            latest = -1
            for name in os.listdir(directory):
                if format in (None, 'numpy') and name == filename + '.npz':
                    assert found is None
                    found = 'numpy'
                    latest = None
                elif format in (None, 'numpy') and name.startswith(filename) and \
                        name.endswith('.npz'):
                    assert found is None or found == 'numpy'
                    found = 'numpy'
                    n = int(name[len(filename) + 1: -4])
                    if n > latest:
                        latest = n
                elif format in (None, 'hdf5') and \
                        (name == filename + '.hdf5' or name == filename + '.h5'):
                    assert found is None
                    found = 'hdf5'
                    latest = None
                elif format in (None, 'hdf5') and name.startswith(filename) and \
                        (name.endswith('.hdf5') or name.endswith('.h5')):
                    assert found is None or found == 'hdf5'
                    found = 'hdf5'
                    n = int(name[len(filename) + 1: -5])
                    if n > latest:
                        latest = n

            if latest == -1:
                if format is None:
                    format = 'checkpoint'
                else:
                    assert format == 'checkpoint'
                if not os.path.isfile(os.path.join(directory, filename + '.index')):
                    import tensorflow as tf
                    path = tf.train.latest_checkpoint(checkpoint_dir=directory)
                    if not path:
                        raise TensorforceError.exists_not(name='Checkpoint', value=directory)
                    _directory, filename = os.path.split(path)
                    assert _directory == directory

            else:
                if format is None:
                    format = found
                else:
                    assert format == found
                if latest is not None:
                    filename = filename + '-' + str(latest)

        self.timesteps, self.episodes, self.updates = self.model.restore(
            directory=directory, filename=filename, format=format
        )

    # def get_variables(self):
    #     """
    #     Returns the names of all agent variables.

    #     Returns:
    #         list[str]: Names of variables.
    #     """
    #     return [
    #         variable.name[len(self.model.name) + 1: -2] for variable in self.model.get_variables()
    #     ]

    # def get_variable(self, variable):
    #     """
    #     Returns the value of the variable with the given name.

    #     Args:
    #         variable (string): Variable name
    #             (required).

    #     Returns:
    #         numpy-array: Variable value.
    #     """
    #     return self.model.get_variable(variable=variable)

    # def assign_variable(self, variable, value):
    #     """
    #     Assigns the given value to the variable with the given name.

    #     Args:
    #         variable (string): Variable name
    #             (required).
    #         value (variable-compatible value): Value to assign to variable
    #             (required).
    #     """
    #     self.model.assign_variable(variable=variable, value=value)

    # def summarize(self, summary, value, step=None):
    #     """
    #     Records a value for the given custom summary label (as specified via summarizer[custom]).

    #     Args:
    #         variable (string): Custom summary label
    #             (required).
    #         value (summary-compatible value): Summary value to record
    #             (required).
    #         step (int): Summary recording step
    #             (default: current timestep).
    #     """
    #     self.model.summarize(summary=summary, value=value, step=step)

    # def get_output_tensors(self, function):
    #     """
    #     Returns the names of output tensors for the given function.

    #     Args:
    #         function (str): Function name
    #             (required).

    #     Returns:
    #         list[str]: Names of output tensors.
    #     """
    #     if function in self.model.output_tensors:
    #         return self.model.output_tensors[function]
    #     else:
    #         raise TensorforceError.value(
    #             name='agent.get_output_tensors', argument='function', value=function
    #         )

    # def get_available_summaries(self):
    #     """
    #     Returns the summary labels provided by the agent.

    #     Returns:
    #         list[str]: Available summary labels.
    #     """
    #     return self.model.get_available_summaries()

    # def get_query_tensors(self, function):
    #     """
    #     Returns the names of queryable tensors for the given function.

    #     Args:
    #         function (str): Function name
    #             (required).

    #     Returns:
    #         list[str]: Names of queryable tensors.
    #     """
    #     if function in self.model.query_tensors:
    #         return self.model.query_tensors[function]
    #     else:
    #         raise TensorforceError.value(
    #             name='agent.get_query_tensors', argument='function', value=function
    #         )

class TensorforceJSONEncoder(json.JSONEncoder):
    """
    Custom JSON encoder which is NumPy-compatible.
    """

    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, TensorSpec):
            return obj.json()
        else:
            return super().default(obj)


text:
import type { IconifyOptional, IconifyIcon } from '@iconify/types';

// Export icon and full icon types
export { IconifyIcon };
export type FullIconifyIcon = Required<IconifyIcon>;

/**
 * Expression to test part of icon name.
 */
export const matchName = /^[a-z0-9]+(-[a-z0-9]+)*$/;

/**
 * Default values for all optional IconifyIcon properties
 */
export const iconDefaults: Required<IconifyOptional> = Object.freeze({
	left: 0,
	top: 0,
	width: 16,
	height: 16,
	rotate: 0,
	vFlip: false,
	hFlip: false,
});

/**
 * Add optional properties to icon
 */
export function fullIcon(data: IconifyIcon): FullIconifyIcon {
	return { ...iconDefaults, ...data };
}


text:
use crate::from_headers::*;
use crate::permission::CosmosPermission;
use crate::Permission;
use azure_sdk_core::errors::AzureError;
use azure_sdk_core::{etag_from_headers, session_token_from_headers};
use http::HeaderMap;
use std::borrow::Cow;

#[derive(Debug, Clone, PartialEq)]
pub struct GetPermissionResponse<'a> {
    pub permission: Permission<'a, Cow<'a, str>>,
    pub charge: f64,
    pub etag: String,
    pub activity_id: uuid::Uuid,
    pub session_token: String,
    pub content_path: String,
    pub alt_content_path: String,
}

impl<'a> std::convert::TryFrom<(&HeaderMap, &[u8])> for GetPermissionResponse<'a> {
    type Error = AzureError;
    fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> {
        let headers = value.0;
        let body = value.1;

        debug!("headers == {:#?}", headers);
        debug!("body == {:#?}", std::str::from_utf8(body)?);

        // first get the Cosmos REST API permission
        let cosmos_permission: CosmosPermission<'_> = serde_json::from_slice(body)?;
        debug!("cosmos_permission== {:#?}", cosmos_permission);

        // now convert into the SDK struct
        let permission = Permission::try_from(cosmos_permission)?;

        Ok(Self {
            permission,
            charge: request_charge_from_headers(headers)?,
            etag: etag_from_headers(headers)?,
            activity_id: activity_id_from_headers(headers)?,
            session_token: session_token_from_headers(headers)?,
            content_path: content_path_from_headers(headers)?.to_owned(),
            alt_content_path: alt_content_path_from_headers(headers)?.to_owned(),
        })
    }
}