text:
// Transmogrify License
//
// Copyright (c) 2001, ThoughtWorks, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the ThoughtWorks, Inc. nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify;

public abstract class ReferenceTool {
  protected SymTabAST _tree = null;

  public ReferenceTool(SymTabAST tree) {
    _tree = tree;
  }

  protected void walkChildren( SymTabAST node ) {
    if ( node.getFirstChild() != null ) {
      walkSelfAndSiblings( (SymTabAST)node.getFirstChild() );
    }
  }

  private void walkSelfAndSiblings( SymTabAST node ) {
    handleNode( node );
    SymTabAST sibling = (SymTabAST)node.getNextSibling();
    while ( sibling != null ) {
      handleNode( sibling );
      sibling = (SymTabAST)sibling.getNextSibling();
    }
  }

  protected abstract void handleNode(SymTabAST node);
}


text:
package net.bluemix.todo.store;

import static org.easymock.EasyMock.createControl;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.getCurrentArguments;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.bluemix.todo.model.ToDo;

import org.bson.types.ObjectId;
import org.easymock.IAnswer;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;

public class MongoStoreTest {

	private DBCollection createMockCollection() {
		IMocksControl control = createControl();
		return control.createMock(DBCollection.class);
	}

	private DBCursor createMockCursor() {
		IMocksControl control = createControl();
		return control.createMock(DBCursor.class);
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGetAll() {
		DBCollection coll = createMockCollection();
		DBCursor cursor = createMockCursor();
		expect(cursor.hasNext()).andAnswer(new IAnswer<Boolean>() {
			private int count = 0;
			@Override
			public Boolean answer() throws Throwable {
				count++;
				return count == 3 ? false : true;
			}
		}).anyTimes();
		expect(cursor.next()).andAnswer(new IAnswer<DBObject>() {
			private int count = 0;
			@Override
			public DBObject answer() throws Throwable {
				count++;
				BasicDBObject dbObj = new BasicDBObject();
				dbObj.put("title", "This is todo " + count);
				dbObj.put("completed", false);
				dbObj.put("order", count);
				//Object IDs must be 24 characters long
				dbObj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa" + count));
				return dbObj;
			}
		}).anyTimes();
		cursor.close();
		expectLastCall();
		replay(cursor);
		expect(coll.find()).andReturn(cursor);
		replay(coll);
		MongoStore store = new MongoStore(coll);
		Collection<ToDo> todos = store.getAll();
		List<ToDo> testToDos = new ArrayList<ToDo>();
		ToDo td1 = new ToDo();
		td1.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
		td1.setTitle("This is todo 1");
		td1.setOrder(1);
		ToDo td2 = new ToDo();
		td2.setId("aaaaaaaaaaaaaaaaaaaaaaa2");
		td2.setTitle("This is todo 2");
		td2.setOrder(2);
		testToDos.add(td1);
		testToDos.add(td2);
		assertEquals(testToDos, todos);
		verify(cursor);
		verify(coll);
	}

	@Test
	public void testGet() {
		DBCollection coll = createMockCollection();
		DBCursor cursor = createMockCursor();
		expect(cursor.hasNext()).andAnswer(new IAnswer<Boolean>() {
			private int count = 0;
			@Override
			public Boolean answer() throws Throwable {
				count++;
				return count == 2 ? false : true;
			}
		}).anyTimes();
		expect(cursor.next()).andAnswer(new IAnswer<DBObject>() {
			private int count = 0;
			@Override
			public DBObject answer() throws Throwable {
				count++;
				BasicDBObject dbObj = new BasicDBObject();
				dbObj.put("title", "This is todo " + count);
				dbObj.put("completed", false);
				dbObj.put("order", count);
				//Object IDs must be 24 characters long
				dbObj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa" + count));
				return dbObj;
			}
		}).anyTimes();
		cursor.close();
		expectLastCall();
		replay(cursor);
		DBCursor emptyCursor = createMockCursor();
		expect(emptyCursor.hasNext()).andReturn(false);
		replay(emptyCursor);
		expect(coll.find(eq(new BasicDBObject("_id", "aaaaaaaaaaaaaaaaaaaaaaa1")))).andReturn(cursor);
		expect(coll.find(eq(new BasicDBObject("_id", "1")))).andReturn(emptyCursor);
		replay(coll);
		MongoStore store = new MongoStore(coll);
		ToDo td = store.get("1");
		assertNull(td);
		td = store.get("aaaaaaaaaaaaaaaaaaaaaaa1");
		ToDo td1 = new ToDo();
		td1.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
		td1.setTitle("This is todo 1");
		td1.setOrder(1);
		assertEquals(td, td1);
		verify(cursor);
		verify(emptyCursor);
		verify(coll);
	}

	@Test
	public void testPersist() {
		DBCollection coll = createMockCollection();
		ToDo td = new ToDo();
		td.setTitle("This is a test");
		td.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
		expect(coll.insert(isA(DBObject.class))).andAnswer(new IAnswer<WriteResult>() {
			@Override
			public WriteResult answer() throws Throwable {
				DBObject obj = (DBObject)getCurrentArguments()[0];
				obj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa1"));
				return null;
			}
		});
		replay(coll);
		MongoStore store = new MongoStore(coll);
		assertEquals(td, store.persist(td));
		verify(coll);
	}

	@Test
	public void testUpdate() {
		DBCollection coll = createMockCollection();
		DBCursor cursor = createMockCursor();
		DBObject query = new BasicDBObject("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa2"));
		DBObject dbObj = new BasicDBObject();
		dbObj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa2"));
		dbObj.put("title", "new title");
		dbObj.put("completed", true);
		dbObj.put("order", 0);
		expect(cursor.next()).andReturn(dbObj);
		cursor.close();
		expectLastCall();
		replay(cursor);
		expect(coll.find(eq(query))).andReturn(cursor);
		ToDo newTd = new ToDo();
		newTd.setId("aaaaaaaaaaaaaaaaaaaaaaa2");
		newTd.setCompleted(true);
		newTd.setTitle("new title");
		newTd.setOrder(0);
		expect(coll.update(eq(query), eq(dbObj))).andReturn(null);
		replay(coll);
		MongoStore store = new MongoStore(coll);
		assertEquals(newTd, store.update("aaaaaaaaaaaaaaaaaaaaaaa2", newTd));
		verify(cursor);
		verify(coll);
	}

	@Test
	public void testDelete() {
		ToDo td = new ToDo();
		td.setId("aaaaaaaaaaaaaaaaaaaaaaa2");
		td.setTitle("this is a test");
		BasicDBObject dbObj = new BasicDBObject();
		dbObj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa2"));
		DBCollection coll = createMockCollection();
		expect(coll.remove(eq(dbObj))).andReturn(null);
		replay(coll);
		MongoStore store = new MongoStore(coll);
		store.delete("aaaaaaaaaaaaaaaaaaaaaaa2");
		verify(coll);
	}

	@Test
	public void testCount() throws Exception {
	  DBCollection coll = createMockCollection();
    DBCursor cursor = createMockCursor();
    expect(cursor.hasNext()).andAnswer(new IAnswer<Boolean>() {
      private int count = 0;
      @Override
      public Boolean answer() throws Throwable {
        count++;
        return count == 3 ? false : true;
      }
    }).anyTimes();
    expect(cursor.next()).andAnswer(new IAnswer<DBObject>() {
      private int count = 0;
      @Override
      public DBObject answer() throws Throwable {
        count++;
        BasicDBObject dbObj = new BasicDBObject();
        dbObj.put("title", "This is todo " + count);
        dbObj.put("completed", false);
        dbObj.put("order", count);
        //Object IDs must be 24 characters long
        dbObj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa" + count));
        return dbObj;
      }
    }).anyTimes();
    cursor.close();
    expectLastCall();
    replay(cursor);
    expect(coll.find()).andReturn(cursor);
    replay(coll);
    MongoStore store = new MongoStore(coll);
    assertEquals(2, store.count());
    verify(cursor);
    verify(coll);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestLibrary.Models
{
    public class Credentials
    {
        public string UserName { get; }

        public string Password { get; }

        public string Path { get; }

        public Credentials(string userName, string password, string path = "token")
        {
            UserName = userName;
            Password = password;
            Path = path;
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Solanum biflorum var. kotoensis Y.C.Liu & C.H.Ou

### Remarks
null


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Unity-SCORM Integration Kit: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Unity-SCORM Integration Kit
    1.0

Integrate Unity3d Projects with your LMS via SCORM

Main Page

Classes

Files

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

Class List

Class Index

Class Hierarchy

Class Members

StudentRecord Member List

This is the complete list of members for StudentRecord, including all inherited members.

commentsFromLearner	StudentRecord

commentsFromLMS	StudentRecord

completionStatus	StudentRecord

CompletionStatusType enum name	StudentRecord

completionThreshold	StudentRecord

credit	StudentRecord

CreditType enum name	StudentRecord

entry	StudentRecord

EntryType enum name	StudentRecord

ExitType enum name	StudentRecord

interactions	StudentRecord

InteractionType enum name	StudentRecord

launchData	StudentRecord

learnerID	StudentRecord

learnerName	StudentRecord

learnerPreference	StudentRecord

learnerScore	StudentRecord

location	StudentRecord

maxTimeAllowed	StudentRecord

mode	StudentRecord

ModeType enum name	StudentRecord

objectives	StudentRecord

progressMeasure	StudentRecord

ResultType enum name	StudentRecord

scaledPassingScore	StudentRecord

successStatus	StudentRecord

SuccessStatusType enum name	StudentRecord

suspendData	StudentRecord

timeLimitAction	StudentRecord

TimeLimitActionType enum name	StudentRecord

totalTime	StudentRecord

version	StudentRecord

<address class="footer">
Generated on Mon Jun 29 2015 09:38:00 for Unity-SCORM Integration Kit by

 1.8.9.1
</address>


text:
if (typeof navigator !== 'undefined' && navigator.languages === undefined) {
  navigator.languages = [navigator.language];
}

// iOS Safari doesn't even have the Intl object defined
if (typeof Intl === 'undefined') {
  window.Intl = {};
}


text:
package tiller

import (
	"bytes"
	"fmt"
	"log"
	"strings"

	"k8s.io/client-go/kubernetes"

	"k8s.io/helm/pkg/chartutil"
	"k8s.io/helm/pkg/kube"
	"k8s.io/helm/pkg/proto/hapi/release"
	rudderAPI "k8s.io/helm/pkg/proto/hapi/rudder"
	"k8s.io/helm/pkg/proto/hapi/services"
	relutil "k8s.io/helm/pkg/releaseutil"
	"k8s.io/helm/pkg/rudder"
	"k8s.io/helm/pkg/tiller/environment"
)

// ReleaseModule is an interface that allows ReleaseServer to run operations on release via either local implementation or Rudder service
type ReleaseModule interface {
	Create(r *release.Release, req *services.InstallReleaseRequest, env *environment.Environment) error
	Update(current, target *release.Release, req *services.UpdateReleaseRequest, env *environment.Environment) error
	Rollback(current, target *release.Release, req *services.RollbackReleaseRequest, env *environment.Environment) error
	Status(r *release.Release, req *services.GetReleaseStatusRequest, env *environment.Environment) (string, error)
	Delete(r *release.Release, req *services.UninstallReleaseRequest, env *environment.Environment) (string, []error)
}

// LocalReleaseModule is a local implementation of ReleaseModule
type LocalReleaseModule struct {
	clientset kubernetes.Interface
}

// Create creates a release via kubeclient from provided environment
func (m *LocalReleaseModule) Create(r *release.Release, req *services.InstallReleaseRequest, env *environment.Environment) error {
	b := bytes.NewBufferString(r.Manifest)
	return env.KubeClient.Create(r.Namespace, b, req.Timeout, req.Wait)
}

// Update performs an update from current to target release
func (m *LocalReleaseModule) Update(current, target *release.Release, req *services.UpdateReleaseRequest, env *environment.Environment) error {
	c := bytes.NewBufferString(current.Manifest)
	t := bytes.NewBufferString(target.Manifest)
	return env.KubeClient.Update(target.Namespace, c, t, req.Force, req.Recreate, req.Timeout, req.Wait)
}

// Rollback performs a rollback from current to target release
func (m *LocalReleaseModule) Rollback(current, target *release.Release, req *services.RollbackReleaseRequest, env *environment.Environment) error {
	c := bytes.NewBufferString(current.Manifest)
	t := bytes.NewBufferString(target.Manifest)
	return env.KubeClient.Update(target.Namespace, c, t, req.Force, req.Recreate, req.Timeout, req.Wait)
}

// Status returns kubectl-like formatted status of release objects
func (m *LocalReleaseModule) Status(r *release.Release, req *services.GetReleaseStatusRequest, env *environment.Environment) (string, error) {
	return env.KubeClient.Get(r.Namespace, bytes.NewBufferString(r.Manifest))
}

// Delete deletes the release and returns manifests that were kept in the deletion process
func (m *LocalReleaseModule) Delete(rel *release.Release, req *services.UninstallReleaseRequest, env *environment.Environment) (kept string, errs []error) {
	vs, err := GetVersionSet(m.clientset.Discovery())
	if err != nil {
		return rel.Manifest, []error{fmt.Errorf("Could not get apiVersions from Kubernetes: %v", err)}
	}
	return DeleteRelease(rel, vs, env.KubeClient)
}

// RemoteReleaseModule is a ReleaseModule which calls Rudder service to operate on a release
type RemoteReleaseModule struct{}

// Create calls rudder.InstallRelease
func (m *RemoteReleaseModule) Create(r *release.Release, req *services.InstallReleaseRequest, env *environment.Environment) error {
	request := &rudderAPI.InstallReleaseRequest{Release: r}
	_, err := rudder.InstallRelease(request)
	return err
}

// Update calls rudder.UpgradeRelease
func (m *RemoteReleaseModule) Update(current, target *release.Release, req *services.UpdateReleaseRequest, env *environment.Environment) error {
	upgrade := &rudderAPI.UpgradeReleaseRequest{
		Current:  current,
		Target:   target,
		Recreate: req.Recreate,
		Timeout:  req.Timeout,
		Wait:     req.Wait,
		Force:    req.Force,
	}
	_, err := rudder.UpgradeRelease(upgrade)
	return err
}

// Rollback calls rudder.Rollback
func (m *RemoteReleaseModule) Rollback(current, target *release.Release, req *services.RollbackReleaseRequest, env *environment.Environment) error {
	rollback := &rudderAPI.RollbackReleaseRequest{
		Current:  current,
		Target:   target,
		Recreate: req.Recreate,
		Timeout:  req.Timeout,
		Wait:     req.Wait,
	}
	_, err := rudder.RollbackRelease(rollback)
	return err
}

// Status returns status retrieved from rudder.ReleaseStatus
func (m *RemoteReleaseModule) Status(r *release.Release, req *services.GetReleaseStatusRequest, env *environment.Environment) (string, error) {
	statusRequest := &rudderAPI.ReleaseStatusRequest{Release: r}
	resp, err := rudder.ReleaseStatus(statusRequest)
	if resp == nil {
		return "", err
	}
	return resp.Info.Status.Resources, err
}

// Delete calls rudder.DeleteRelease
func (m *RemoteReleaseModule) Delete(r *release.Release, req *services.UninstallReleaseRequest, env *environment.Environment) (string, []error) {
	deleteRequest := &rudderAPI.DeleteReleaseRequest{Release: r}
	resp, err := rudder.DeleteRelease(deleteRequest)

	errs := make([]error, 0)
	result := ""

	if err != nil {
		errs = append(errs, err)
	}
	if resp != nil {
		result = resp.Release.Manifest
	}
	return result, errs
}

// DeleteRelease is a helper that allows Rudder to delete a release without exposing most of Tiller inner functions
func DeleteRelease(rel *release.Release, vs chartutil.VersionSet, kubeClient environment.KubeClient) (kept string, errs []error) {
	manifests := relutil.SplitManifests(rel.Manifest)
	_, files, err := sortManifests(manifests, vs, UninstallOrder)
	if err != nil {
		// We could instead just delete everything in no particular order.
		// FIXME: One way to delete at this point would be to try a label-based
		// deletion. The problem with this is that we could get a false positive
		// and delete something that was not legitimately part of this release.
		return rel.Manifest, []error{fmt.Errorf("corrupted release record. You must manually delete the resources: %s", err)}
	}

	filesToKeep, filesToDelete := filterManifestsToKeep(files)
	if len(filesToKeep) > 0 {
		kept = summarizeKeptManifests(filesToKeep, kubeClient, rel.Namespace)
	}

	errs = []error{}
	for _, file := range filesToDelete {
		b := bytes.NewBufferString(strings.TrimSpace(file.Content))
		if b.Len() == 0 {
			continue
		}
		if err := kubeClient.Delete(rel.Namespace, b); err != nil {
			log.Printf("uninstall: Failed deletion of %q: %s", rel.Name, err)
			if err == kube.ErrNoObjectsVisited {
				// Rewrite the message from "no objects visited"
				obj := ""
				if file.Head != nil && file.Head.Metadata != nil {
					obj = "[" + file.Head.Kind + "] " + file.Head.Metadata.Name
				}
				err = fmt.Errorf("release %q: object %q not found, skipping delete", rel.Name, obj)
			}
			errs = append(errs, err)
		}
	}
	return kept, errs
}


text:
<!--

    Copyright © 2016-2022 The Thingsboard Authors

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.thingsboard</groupId>
        <version>3.4.2-SNAPSHOT</version>
        <artifactId>common</artifactId>
    </parent>
    <groupId>org.thingsboard.common</groupId>
    <artifactId>edge-api</artifactId>
    <packaging>jar</packaging>

    <name>Thingsboard Server Remote Edge wrapper</name>
    <url>https://thingsboard.io</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <main.dir>${basedir}/../..</main.dir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.thingsboard.common</groupId>
            <artifactId>data</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thingsboard.common</groupId>
            <artifactId>queue</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thingsboard.common</groupId>
            <artifactId>message</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative-boringssl-static</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <id>thingsboard-repo-deploy</id>
            <name>ThingsBoard Repo Deployment</name>
            <url>https://repo.thingsboard.io/artifactory/libs-release-public</url>
        </repository>
    </distributionManagement>

</project>


text:
<ion-header>
    <ion-navbar>
        <ion-title>筛选</ion-title>
    </ion-navbar>
</ion-header>
<ion-content>
    <form [formGroup]="searchForm" (ngSubmit)="sent(searchForm.value)">
        <ion-list>
            <ion-item>
                <ion-label>会议编码</ion-label>
                <ion-input text-right type="text" formControlName="MeetRecod" placeholder="请输入"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label>会议主题</ion-label>
                <ion-input text-right type="text" formControlName="Title" placeholder="请输入"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label>会议类型</ion-label>
                <ion-select  text-right formControlName="TypeId" cancelText="取消" okText="确定" placeholder="请选择">
                    <ion-option *ngFor="let type of MeetTypeLs;let i = index" [value]="type.Id">{{type.Name}}</ion-option>
                </ion-select>
            </ion-item>
            <ion-item>
                <ion-label>状态</ion-label>
                <ion-input text-right type="text" formControlName="Status" placeholder="请输入"></ion-input>
            </ion-item>

        </ion-list>
        <div text-center>
            <button ion-button color="energized" (click)="reset()" small outline>重置</button>
            <button ion-button color="assertive" type="submit" small>搜索</button>
        </div>
    </form>
</ion-content>


text:
var editor,
    changed,
    lastTxt;

function init() {
  editor = document.getElementsByTagName("textarea")[0];
  if (editor) {
    changed = 0;
    lastTxt = editor.value;
    setInterval(tick, 10000);
    editor.addEventListener("keyup", keyUp);
  }
}
init();

function keyUp() {
  if (editor.value !== lastTxt) {
    changed = 2;
  }
}

function tick() {
  if (changed > 0) {
    changed = 1;
    $.post("?get=json&file="+filename, $(document.forms[0]).serialize(),
      function(data) {
        if (data.success) {
          changed--;
          console.log("saved");
        }
      }, "json");
  } else {
    $.get(filename+"?now="+Date.now(), function(data){
      if (changed === 0 && editor.value !== data) {
        editor.value = data;
        lastTxt = editor.value;
        console.log("loaded");
      }
    });
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.clinica.dao;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 *
 * @author Eduardo
 */
public class DaoManagerHiber {
    private static DaoManagerHiber myself = null;

    private SessionFactory sessionFactory;
    private Session s;

    public DaoManagerHiber(){

    try{

        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        s = sessionFactory.openSession();

    }catch(Throwable th){

        System.err.println("Enitial SessionFactory creation failed"+th);

        throw new ExceptionInInitializerError(th);

    }

  }

    public static DaoManagerHiber getInstance(){
        if(myself==null)
            myself = new DaoManagerHiber();

        return myself;
    }

    public void persist(Object o){

        s.clear();
            s = sessionFactory.openSession();

        Transaction tr = s.beginTransaction();

        s.save(o);

        tr.commit();

        s.flush();
    }

    public List recover(String hql){
        Transaction tr = null;
        try{

            s = sessionFactory.openSession();

        }catch(org.hibernate.exception.JDBCConnectionException ex){
            s.close();
            s=sessionFactory.openSession();
        }

        tr = s.beginTransaction();

        Query query = s.createQuery(hql);

        s.flush();

        return query.list();
    }

    public List recoverSQL(String sql){
        Transaction tr = null;
        try{

            s = sessionFactory.openSession();

        }catch(org.hibernate.exception.JDBCConnectionException ex){
            s.close();
            s=sessionFactory.openSession();
        }

        tr = s.beginTransaction();

        Query query = s.createSQLQuery(sql);

        s.flush();

        return query.list();
    }

    public List recover(Object o){

        Criteria c = s.createCriteria(o.getClass());

        c.add(Example.create(o).enableLike(MatchMode.ANYWHERE).ignoreCase().excludeProperty("codigo"));

        List l = c.list();
        s.flush();

        return l;
    }

    public void update(Object o){
        s.clear();
        s = sessionFactory.openSession();
        Transaction tr = s.beginTransaction();

        s.update(o);

        tr.commit();

        s.flush();
    }

    public void delete(Object o){
        Transaction tr = null;
        try{
            s.clear();
            s = sessionFactory.openSession();
            tr = s.beginTransaction();
        }catch(Exception ex){
            s.close();
            s=sessionFactory.openSession();
            tr = s.beginTransaction();
        }

        s.delete(o);

        tr.commit();

        s.flush();
    }

    public static void main(String args[]){
        SchemaExport se = new SchemaExport(new AnnotationConfiguration().configure());
	se.create(true, true);
    }
}


text:
/*
 * Java GPX Library (@__identifier__@).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This package contains classes for formatting and parsing coordinates to and
 * from a ISO 6709 location
 * string.
 *
 * @version 2.2
 * @since 1.0
 */
package io.jenetics.jpx.format;


text:
import { css } from 'lit';
import componentStyles from '../../styles/component.styles';

export default css`
  ${componentStyles}

  :host {
    display: block;
  }

  .responsive-media {
    position: relative;
  }

  .responsive-media ::slotted(*) {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important;
    height: 100% !important;
  }

  .responsive-media--cover ::slotted(embed),
  .responsive-media--cover ::slotted(iframe),
  .responsive-media--cover ::slotted(img),
  .responsive-media--cover ::slotted(video) {
    object-fit: cover !important;
  }

  .responsive-media--contain ::slotted(embed),
  .responsive-media--contain ::slotted(iframe),
  .responsive-media--contain ::slotted(img),
  .responsive-media--contain ::slotted(video) {
    object-fit: contain !important;
  }
`;


text:
import os
import math
from . import errors
from ... util import log
from .. spi_interfaces import SPI_INTERFACES

class SpiBaseInterface(object):
    """ abstract class for different spi backends"""

    def __init__(self, dev, spi_speed):
        self._dev = dev
        self._spi_speed = spi_speed

    def send_packet(self, data):
        """SHOULD BE PRIVATE"""
        raise NotImplementedError

    def compute_packet(self, data):
        """SHOULD BE PRIVATE"""
        return data

    def error(self, text):
        """SHOULD BE PRIVATE"""
        msg = 'Error with dev: {}, spi_speed: {} - {}'.format(
            self._dev, self._spi_speed, text)
        log.error(msg)
        raise IOError(msg)

class SpiFileInterface(SpiBaseInterface):
    """ using os open/write to send data"""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if not os.path.exists(self._dev):
            self.error(errors.CANT_FIND_ERROR)

        self._spi = open(self._dev, 'wb')

        log.info('file io spi dev {:s}'.format(self._dev))

    def send_packet(self, data):
        """SHOULD BE PRIVATE"""
        package_size = 4032  # bit smaller than 4096 because of headers
        for i in range(int(math.ceil(len(data) / package_size))):
            start = i * package_size
            end = (i + 1) * package_size
            self._spi.write(data[start:end])
            self._spi.flush()

class SpiPeripheryInterface(SpiBaseInterface):
    """ using `python-periphery` to send data"""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if not os.path.exists(self._dev):
            self.error(errors.CANT_FIND_ERROR)

        try:
            from periphery import SPI
            self._spi = SPI(self._dev, 0, self._spi_speed * 1e6)
        except ImportError:
            self.error(errors.CANT_IMPORT_PERIPHERY_ERROR)

        log.info('periphery spi dev {:s} speed @ {:.2f} MHz'.format(
            self._dev, self._spi.max_speed / 1e6))

    def send_packet(self, data):
        """SHOULD BE PRIVATE"""
        package_size = 4032  # bit smaller than 4096 because of headers
        for i in range(int(math.ceil(len(data) / package_size))):
            start = i * package_size
            end = (i + 1) * package_size
            self._spi.transfer(data[start:end])

class SpiPyDevInterface(SpiBaseInterface):
    """ using py-spidev to send data"""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        d = self._dev.replace('/dev/spidev', '')
        ids = (int(i) for i in d.split('.'))
        try:
            self._device_id, self._device_cs = ids
        except:
            self.error(errors.BAD_FORMAT_ERROR)

        if not os.path.exists(self._dev):
            self.error(errors.CANT_FIND_ERROR)
        # permissions check
        try:
            fd = open(self._dev, 'r')
            fd.close()
        except IOError as e:
            if e.errno == 13:
                self.error(errors.PERMISSION_ERROR)
            else:
                raise e
        # import spidev and cache error
        try:
            import spidev
            self._spi = spidev.SpiDev()
        except ImportError:
            self.error(errors.CANT_IMPORT_SPIDEV_ERROR)
        self._spi.open(self._device_id, self._device_cs)
        self._spi.max_speed_hz = int(self._spi_speed * 1e6)
        log.info(
            'py-spidev dev {:s} speed @ {:.2f} MHz'.format(
                self._dev, self._spi.max_speed_hz / 1e6))

    def send_packet(self, data):
        """SHOULD BE PRIVATE"""
        self._spi.xfer2(list(data))

class SpiDummyInterface(SpiBaseInterface):
    """ interface for testing proposal"""

    def send_packet(self, data):
        """ do nothing """
        pass

_SPI_INTERFACES = [
    SpiFileInterface,
    SpiPyDevInterface,
    SpiPeripheryInterface,
    SpiDummyInterface
]


text:
package pla.todo.model;

import io.realm.RealmObject;

public class Todo extends RealmObject {
    private int id;
    private String message;
    private boolean checked;

    public void setId(int id) {
        this.id = id;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public boolean getChecked() {
        return checked;
    }
}


text:
const path = require('path');
const Base = require('./base');

module.exports = class extends Base {
  constructor(...args) {
    super(...args);
    this.outputFile = path.join(think.RUNTIME_PATH, 'export_hugo.zip');
  }

  generate(posts) {
    return this.generateZipFile(this.outputFile, zip => {
      for(let post of posts) {
        let content = `
---
title: "${post.title}"
date: "${post.create_time}"
slug: ${post.pathname}
draft: ${post.status !== 3 || !post.is_public ? 'true' : 'false'}
lastMod: ${post.update_time}
comments: ${post.allow_comment}
categories: ${post.cate.length ? post.cate[0].pathname : ''}
tags: ${JSON.stringify(post.tag.map(tag => tag.name))}
---

${post.markdown_content}`;

        zip.file(`content/post/${think.datetime(post.create_time, 'YYYY/MM')}/${post.title}.md`, content);
      }
    });
  }

  async run() {
    let posts = await this.getPosts();
    return this.generate(posts);
  }
}


text:
/*global require,loadingDialogInstance*/

import {tableModule} from './tableModule';
import {actions} from './actions';
import {tooltip} from './tooltip';

export function main() {
  loadingDialogInstance.open();
  tableModule.main();
  actions.main();
  tooltip.main();
  $j('#btn-student-contacts').attr({
    'class': 'selected'
  });
}


text:
<?php
namespace WMS\Bundle\BusinessRulesEngineBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use WMS\Bundle\BusinessRulesEngineBundle\DependencyInjection\Compiler\ExpressionLanguageExtensionPass;
use WMS\Bundle\BusinessRulesEngineBundle\DependencyInjection\Compiler\RulesResolverPass;

class WMSBusinessRulesEngineBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);
        $container->addCompilerPass(new RulesResolverPass());
        $container->addCompilerPass(new ExpressionLanguageExtensionPass());
    }
}


text:
id: getting-started
title: Getting Started
layout: docs
category: Quick Start
permalink: docs/getting-started.html
next: tutorial
---

## Requirements

1. OS X - This repo only contains the iOS implementation right now, and Xcode only runs on Mac.
2. New to Xcode?  [Download it](https://developer.apple.com/xcode/downloads/) from the Mac App Store.
3. [Homebrew](http://brew.sh/) is the recommended way to install node, watchman, and flow.
4. `brew install node`. New to [node](https://nodejs.org/) or [npm](https://docs.npmjs.com/)?
5. `brew install watchman`. We recommend installing [watchman](https://facebook.github.io/watchman/docs/install.html), otherwise you might hit a node file watching bug.
6. `brew install flow`. If you want to use [flow](http://www.flowtype.org).

## Quick start

- `npm install -g react-native-cli`
- `react-native init AwesomeProject`

In the newly created folder `AwesomeProject/`

- Open `AwesomeProject.xcodeproj` and hit run in Xcode.
- Open `index.ios.js` in your text editor of choice and edit some lines.
- Hit cmd+R in your iOS simulator to reload the app and see your change!

Congratulations! You've just successfully run and modified your first React Native app.

_If you run into any issues getting started, see the [troubleshooting page](/react-native/docs/troubleshooting.html#content)._


text:
<server description="Default Server">

    <featureManager>
        <feature>jsp-2.2</feature>
    </featureManager>

    <httpEndpoint id="defaultHttpEndpoint"
		  host="*"
                  httpPort="9080"
                  httpsPort="9443" />

    <keyStore id="defaultKeyStore"
              password="Liberty" />

</server>


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

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Package org.springframework.security.ui.savedrequest (Spring Security 2.0.4 API)
</TITLE>

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

Spring Security Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.springframework.security.ui.savedrequest

Packages that use org.springframework.security.ui.savedrequest

org.springframework.security.ui
Authentication processing mechanisms, which respond to the submission of authentication
credentials using various protocols (eg BASIC, CAS, form login etc).

org.springframework.security.util
General utility classes used throughout the Spring Security framework.

org.springframework.security.wrapper
Populates a Servlet request with a new Spring Security compliant
HttpServletRequestWrapper.

Classes in org.springframework.security.ui.savedrequest used by org.springframework.security.ui

SavedRequest

          Represents central information from a HttpServletRequest.

Classes in org.springframework.security.ui.savedrequest used by org.springframework.security.util

SavedRequest

          Represents central information from a HttpServletRequest.

Classes in org.springframework.security.ui.savedrequest used by org.springframework.security.wrapper

SavedRequest

          Represents central information from a HttpServletRequest.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

Spring Security Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2004-2008 SpringSource, Inc. All Rights Reserved.


text:
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Java Service Wrapper - wrapper.java.library.path.append_system_path Property</title>

<map name="wrapperLogo">
<area href="http://wrapper.tanukisoftware.org" coords="90,90,88" shape="circle">
</map>
<map name="wrapperTitle">
<area href="http://www.tanukisoftware.com" coords="28,32,176,48" shape="rect">
</map>

Essentials

Introduction

Integration Methods

Configuration Properties

Launching Your Application

                        >>
                        Show Your Support
                        <<

Sponsors

Documentation

JMX Control

Security Model

Feature Examples

Debugging Your Application

Troubleshooting

FAQ

Release Notes

Project History

Javadocs API

Buttons

Authors

License

Download

Binaries

Source Code

Get Involved

Source Forge

Subversion Repository

Issue Tracking

Mailing Lists and Archives

Forums (Old)

Hosted by:

wrapper.java.library.path.append_system_path Property

<title>wrapper.java.library.path.append_system_path Property</title>

Configuration Property Overview

Configuration Property Overview

JVM Configuration Properties

Property List by Name

wrapper.java.library.path.append_system_path

            The Java Service Wrapper includes a native library component, and thus
            requires that the location of that library be specified by passing its
            location to the JVM using the java.library.path system property.

            Normally when Java is launched and a library path is not specified, the
            JVM will default to using the system PATH on Windows and the LD_LIBRARY_PATH
            on Unix systems to locate any native libraries loaded by the application.
            This is akin to what happens with the CLASSPATH environment variable when
            a specific classpath is not specified when launching the JVM.   The use of
            the CLASSPATH environment variable has fallen out of style because of all
            the conflict problems which can arise when multiple Java applications are
            installed on the same machine.  The same issues are all there with the
            library path as well.  But some applications still make use of the system
            PATH or LD_LIBRARY_PATH by default.

            In general, it is advised that you avoid potential problems when your
            application is deployed by being conservative about which directories
            will be included in the java library path.   However if there is a need
            to search the entire PATH, then this property will cause the Wrapper to
            append the contents of the system PATH or LD_LIBRARY_PATH to the java
            library path used to launch the JVM.  It is appended rather than
            prepended so that directories configured using the
            wrapper.java.library.path.<n>
            properties will be given priority.  Defaults to false.

Example:

wrapper.java.library.path.append_system_path=true

NOTE MEG

                Some native libraries reference other dynamically linked libraries.
                Java will locate the initial JNI library using the java library path,
                but the secondary libraries are loaded using the default mechanism
                for the platform.

                On Windows, the system will first look in the current working
                directory (The location of the wrapper.exe), then it will look in
                the Windows system32 directory and the Windows directory.  Finally,
                it will search the entire system PATH.  If both DLLs are located in
                your application's lib directory, it may be necessary to add its
                location to your system path as follows.  The PATH is for Windows
                and the LD_LIBRARY_PATH makes the configuration file cross
                platform so it works on Unix systems as well.

set.PATH=..%WRAPPER_FILE_SEPARATOR%bin%WRAPPER_PATH_SEPARATOR%%PATH%
set.LD_LIBRARY_PATH=..%WRAPPER_FILE_SEPARATOR%bin%WRAPPER_PATH_SEPARATOR%%LD_LIBRARY_PATH%

                Not that placing the secondary library on the PATH rather than in the
                current working directory has a risk that an old version of the library
                could be encountered first in the Windows system32 directory if it was
                installed by another application.  This is due to the order in which
                the system looks for the file.

                This problem has been seen when working with SAP's JCO libraries
                if other SAP applications are also installed on the system.

by Leif Mortenson

                            Copyright ©1999-2004 by Tanuki Software.
                            All Rights Reserved.

                            last modified:


text:
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const ClientGenerator = require('../../generators/client');
const constants = require('../../generators/generator-constants');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;

const mockBlueprintSubGen = class extends ClientGenerator {
  constructor(args, opts) {
    super(args, { fromBlueprint: true, ...opts }); // fromBlueprint variable is important

    const jhContext = (this.jhipsterContext = this.options.jhipsterContext);

    if (!jhContext) {
      this.error('This is a JHipster blueprint and should be used only like jhipster --blueprints myblueprint');
    }

    this.configOptions = jhContext.configOptions || {};
  }

  get initializing() {
    return super._initializing();
  }

  get prompting() {
    return super._prompting();
  }

  get configuring() {
    return super._configuring();
  }

  get default() {
    return super._default();
  }

  get writing() {
    const phaseFromJHipster = super._writing();
    const customPhaseSteps = {
      addExternalResourcesToRootStep() {
        this.addExternalResourcesToRoot('<link rel="stylesheet" href="content/css/my.css">', 'Comment added by JHipster API');
      },
    };
    return { ...phaseFromJHipster, ...customPhaseSteps };
  }
};

describe('needle API Client: JHipster client generator with blueprint', () => {
  before(done => {
    helpers
      .run(path.join(__dirname, '../../generators/client'))
      .withOptions({
        fromCli: true,
        defaults: true,
        skipServer: true,
        db: 'postgresql',
        auth: 'jwt',
        blueprint: 'myblueprint',
        skipChecks: true,
      })
      .withGenerators([[mockBlueprintSubGen, 'jhipster-myblueprint:client']])
      .on('end', done);
  });

  it('Assert index.html contain the comment and the resource added', () => {
    assert.fileContent(`${CLIENT_MAIN_SRC_DIR}index.html`, '<!-- Comment added by JHipster API -->');
    assert.fileContent(`${CLIENT_MAIN_SRC_DIR}index.html`, '<link rel="stylesheet" href="content/css/my.css" />');
  });
});


text:
package com.gnaix.app.s1.activity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.gnaix.app.s1.R;
import com.gnaix.app.s1.bean.Forum;
import com.gnaix.app.s1.bean.Group;
import com.gnaix.app.s1.bean.Tag;

public class ForumListFragment extends PageFragment implements OnChildClickListener {
    private ExpandableListView mListView;

    private ForumListAdapter mForumListAdapter;
    private ArrayList<Group> mGroups;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGroups = new ArrayList<Group>();
    }

    private ArrayList<Group> parseXML(XmlPullParser parser) throws XmlPullParserException, IOException {
        Log.e("ParsingActivity", ">>>>>>>>>>>>>>>>>.. parseXML..................");
        ArrayList<Group> list = new ArrayList<Group>();
        int eventType = parser.getEventType();
        Group group = null;
        Forum forum = null;
        Tag tag = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
            case XmlPullParser.START_DOCUMENT:
                break;
            case XmlPullParser.START_TAG:
                String name = parser.getName();
                // Log.e("ParsingActivity", " >>>>>.... Tag name   = " + name);
                if (name.equals("group")) {
                    group = new Group();
                    list.add(group);
                    group.setName(parser.getAttributeValue(null, "name"));
                } else if (name.equals("froum")) {
                    forum = new Forum();
                    forum.setFid(Integer.parseInt(parser.getAttributeValue(null, "id")));
                    forum.setName(parser.getAttributeValue(null, "name"));
                    group.getForums().add(forum);
                } else if (name.equals("tag")){
                    tag = new Tag();
                    tag.setId(Integer.parseInt(parser.getAttributeValue(null, "id")));
                    tag.setName(parser.getAttributeValue(null, "name"));
                    forum.getTags().add(tag);
                }
                break;
            case XmlPullParser.END_TAG:
                break;
            }
            eventType = parser.next();
        }
        return list;
    }

    private void loadFavForum() {
        // TODO Auto-generated method stub
    }

    private class ForumListAdapter extends BaseExpandableListAdapter {
        private LayoutInflater mLayoutInflater;
        private Resources mRes;
        private ArrayList<Group> mGroups;
        private int checkedGroupPosition = ExpandableListView.INVALID_POSITION;
        private int checkedChildPosition = ExpandableListView.INVALID_POSITION;

        public class GroupViewHolder {
            public ImageView indicator;
            public TextView forumTitle;
        }

        public ForumListAdapter(Context context) {
            mLayoutInflater = LayoutInflater.from(context);
            mRes = context.getResources();
            mGroups = new ArrayList<Group>();
        }

        @Override
        public int getGroupCount() {
            return mGroups == null ? 0 : mGroups.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return mGroups.get(groupPosition).getForums().size();
        }

        @Override
        public Group getGroup(int groupPosition) {
            return mGroups.get(groupPosition);
        }

        @Override
        public Forum getChild(int groupPosition, int childPosition) {
            return mGroups.get(groupPosition).getForums().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        public void setData(ArrayList<Group> list) {
            mGroups.clear();
            mGroups = list;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new GroupViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.forum_group_layout, null, false);
                viewHolder.indicator = (ImageView) convertView.findViewById(R.id.image1);
                viewHolder.forumTitle = (TextView) convertView.findViewById(R.id.text1);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (GroupViewHolder) convertView.getTag();
            }
            if (isExpanded) {
                viewHolder.indicator.setImageResource(R.drawable.group_indicator_expand);
            } else {
                viewHolder.indicator.setImageResource(R.drawable.group_indicator_collapse);
            }
            viewHolder.forumTitle.setText(getGroup(groupPosition).getName());
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
                ViewGroup parent) {
            if (convertView == null) {
                convertView = mLayoutInflater.inflate(R.layout.forum_item, null, false);
            }
            ((TextView) convertView).setText(getChild(groupPosition, childPosition).getName());
            if (checkedGroupPosition == groupPosition && checkedChildPosition == childPosition) {
                convertView.setBackgroundColor(mRes.getColor(R.color.deep_yellow));
            } else {
                convertView.setBackgroundColor(mRes.getColor(R.color.light_yellow));
            }
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public void setItemSelected(int groupPosition, int childPosition) {
            checkedGroupPosition = groupPosition;
            checkedChildPosition = childPosition;
        }

        public Forum getSelected() {
            if (checkedGroupPosition != ExpandableListView.INVALID_POSITION
                    && checkedChildPosition != ExpandableListView.INVALID_POSITION) {
                return mForumListAdapter.getChild(checkedGroupPosition, checkedChildPosition);
            } else {
                return null;
            }
        }

        public void clear() {
            if (mGroups != null) {
                mGroups.clear();
            }

        }
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        mForumListAdapter.setItemSelected(groupPosition, childPosition);
        if (mListener != null) {
            mListener.onForumSelected(mForumListAdapter.getChild(groupPosition, childPosition));
        }
        mForumListAdapter.notifyDataSetChanged();
        return true;
    }

    public Forum getSelectedForum() {
        return mForumListAdapter.getSelected();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mForumListAdapter != null) {
            mForumListAdapter.clear();
        }
    }

    public OnForumSelectedListener mListener;

    public void setOnForumSelectedListener(OnForumSelectedListener listener) {
        mListener = listener;
    }

    public interface OnForumSelectedListener {
        public void onForumSelected(Forum forum);

        /**
         * 当论坛列表加载完成时,返回第一个论坛
         * @param forum
         */
        public void onLoadFinish(Forum forum);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.forum_list_layout;
    }

    @Override
    public void bindViews() {
        mListView = (ExpandableListView) getView().findViewById(R.id.list);
        mListView.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
        mListView.setOnChildClickListener(this);
        mForumListAdapter = new ForumListAdapter(getActivity());
        mForumListAdapter.setData(mGroups);
        mListView.setAdapter(mForumListAdapter);
    }

    @Override
    public void refresh() {
        new AsyncTask<Void, Void, ArrayList<Group>>() {
            @Override
            protected ArrayList<Group> doInBackground(Void... params) {
                ArrayList<Group> list = null;
                try {
                    XmlPullParserFactory pullParserFactory;
                    pullParserFactory = XmlPullParserFactory.newInstance();
                    XmlPullParser parser = pullParserFactory.newPullParser();
                    InputStream in_s = getActivity().getAssets().open("forumtree.xml");
                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    parser.setInput(in_s, null);
                    list = parseXML(parser);
                    loadFavForum();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return list;
            }

            protected void onPostExecute(ArrayList<Group> result) {
                mGroups.addAll(result);
                if(mGroups.size()>0) {
                    setRefreshRequired(false);
                }
                mForumListAdapter.notifyDataSetChanged();
                if (mListener != null) {
                    mListener.onLoadFinish(mForumListAdapter.getGroup(0).getForums().get(0));
                }
            }
        }.execute();
    }

}


text:
Repositório dos grupos de estudos ativos do Training Center.

#### Atenção!!!
Após criação do repositório do grupo de estudos o responsável ***deve abrir um PR*** adicionando o nome do grupo e seu nome como responsável. A tabela abaixo segue em ordem alfabética pela coluna do nome do grupo de estudos.

| Grupo | Organizador |
| ----- | ----- |
| [Blockchain](https://github.com/training-center/blockchain-study-group) | [Camila Vilarinho](https://github.com/camilaavilarinho) |
| [Clojure](https://github.com/training-center/clojure-study-group) | [William Oliveira](https://github.com/woliveiras) |
| [Elixir](https://github.com/training-center/elixir-study-group) | [Leandro Bighetti](https://github.com/lbighetti) |
| [Frontend](https://github.com/training-center/frontend-study-group) | [Leonan Machado](https://github.com/leonantvrs) |
| [Go](https://github.com/training-center/go-study-group) | [Bruno Gonçalves](https://github.com/brunogbr) |
| [GraphQL](https://github.com/training-center/graphql-study-group) | [Leonardo Turbiani](https://github.com/Turbiani) |
| [Java](https://github.com/training-center/java-study-group) | [Otávio Prado](https://github.com/otavioprado) |
| [JavaScript](https://github.com/training-center/javascript-study-group) | [Alexsandro Silva Alves](https://github.com/AlexsandroSA) |
| [Kotlin](https://github.com/training-center/kotlin-study-group) | [Álisson Morais](https://github.com/alissonfpmorais) |
| [PHP/OOP](https://github.com/training-center/php-study-group) | [Diego Brocanelli](https://github.com/Diego-Brocanelli) |
| [Python](https://github.com/training-center/python-study-group) | [Ciro Valente](https://github.com/cvalentefilho) |
| [React](https://github.com/training-center/react-study-group) | [Richard Manzoli](https://github.com/manzolirch) |
| [Ruby](https://github.com/training-center/ruby-study-group) | [Giovanni Naufal](https://github.com/gionaufal) |
| [SAP](https://github.com/training-center/sap-study-group) | [Raphael Pacheco](https://github.com/pacheco7) |
| [Swift](https://github.com/training-center/swift-study-group) | [Amadeu Cavalcante](https://github.com/amadeu01) |


text:
package org.terasology.engine.rendering.nui.layers.ingame.metrics;

import com.google.common.collect.Lists;
import gnu.trove.list.TDoubleList;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.map.TObjectDoubleMap;

import java.text.NumberFormat;
import java.util.List;

public abstract class TimeMetricsMode extends MetricsMode {

    private int limit;
    private NumberFormat format;
    private String unit = "ms";

    public TimeMetricsMode(String name, int limit) {
        super(name);
        this.limit = limit;
        format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
    }

    public TimeMetricsMode(String name, int limit, String unit) {
        this(name, limit);
        this.limit = limit;
    }

    @Override
    public String getMetrics() {
        StringBuilder builder = new StringBuilder();
        builder.append(getName());
        builder.append("\n");
        displayMetrics(gatherMetrics(), builder);
        return builder.toString();
    }

    protected abstract TObjectDoubleMap<String> gatherMetrics();

    private void displayMetrics(TObjectDoubleMap<String> metrics, StringBuilder builder) {
        final List<String> activities = Lists.newArrayList();
        final TDoubleList values = new TDoubleArrayList();
        sortMetrics(metrics, activities, values);

        for (int i = 0; i < limit && i < activities.size(); ++i) {
            builder.append(activities.get(i));
            builder.append(": ");
            builder.append(format.format(values.get(i)));
            builder.append(unit);
            builder.append("\n");
        }
    }

    private void sortMetrics(TObjectDoubleMap<String> metrics, final List<String> activities, final TDoubleList values) {
        metrics.forEachEntry((s, v) -> {
            boolean inserted = false;
            for (int i = 0; i < values.size() && i < limit; i++) {
                if (v > values.get(i)) {
                    values.insert(i, v);
                    activities.add(i, s);
                    inserted = true;
                    break;
                }
            }

            if (!inserted && values.size() < limit) {
                activities.add(s);
                values.add(v);
            }
            return true;
        });
    }
}


text:
#region License

#endregion License

using System;
using System.IO;
using System.Linq;
using System.Text;

using JsonFx.Model;
using JsonFx.Serialization;
using Xunit;

using Assert=JsonFx.AssertPatched;

namespace JsonFx.Bson
{
	public class BsonTokenizerTests
	{
		#region Constants

		private const string TraitName = "BSON";
		private const string TraitValue = "Tokenizer";

		#endregion Constants

		#region Array Tests

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_ArrayRoot_ReturnsDocument()
		{
			// BSON doesn't provide a way to know if the root element is an array

			var input = new byte[]
			{
				0x26, 0x00, 0x00, 0x00,
					0x02, (byte)'0', 0, 0x08, 0x00, 0x00, 0x00, (byte)'a', (byte)'w', (byte)'e', (byte)'s', (byte)'o', (byte)'m', (byte)'e', 0x00,
					0x01, (byte)'1', 0, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x14, 0x40,
					0x10, (byte)'2', 0, 0xC2, 0x07, 0x00, 0x00,
				0x00
			};

			var expected = new[]
		    {
				ModelGrammar.TokenObjectBeginUnnamed,
				ModelGrammar.TokenProperty("0"),
				ModelGrammar.TokenPrimitive("awesome"),
				ModelGrammar.TokenProperty("1"),
				ModelGrammar.TokenPrimitive(5.05),
				ModelGrammar.TokenProperty("2"),
				ModelGrammar.TokenPrimitive(1986),
				ModelGrammar.TokenObjectEnd
		    };

			var tokenizer = new BsonReader.BsonTokenizer();
			var actual = tokenizer.GetTokens(input).ToArray();

			Assert.Equal(expected, actual);
		}

		#endregion Array Tests

		#region Object Tests

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_HelloWorld_ReturnsDocument()
		{
			// input from example at http://bsonspec.org/#/specification
			var input = Encoding.UTF8.GetBytes(
				"\x16\x00\x00\x00\x02hello\x00"+
				"\x06\x00\x00\x00world\x00\x00");

			var expected = new[]
			{
				ModelGrammar.TokenObjectBeginUnnamed,
				ModelGrammar.TokenProperty("hello"),
				ModelGrammar.TokenPrimitive("world"),
				ModelGrammar.TokenObjectEnd
			};

			var tokenizer = new BsonReader.BsonTokenizer();
			var actual = tokenizer.GetTokens(input).ToArray();

			Assert.Equal(expected, actual);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_ArrayAsProperty_ReturnsDocument()
		{
			// input from example at http://bsonspec.org/#/specification

			// Encoding doesn't seem to like control chars
			//var input = Encoding.UTF8.GetBytes(
			//    "1\x00\x00\x00\x04BSON\x00&\x00"+
			//    "\x00\x00\x020\x00\x08\x00\x00"+
			//    "\x00awesome\x00\x011\x00333333"+
			//    "\x14@\x102\x00\xc2\x07\x00\x00"+
			//    "\x00\x00");

			var input = new byte[]
			{
				0x31, 0x00, 0x00, 0x00,
				0x04, (byte)'B', (byte)'S', (byte)'O', (byte)'N', 0x00,
				0x26, 0x00, 0x00, 0x00,
					0x02, (byte)'0', 0, 0x08, 0x00, 0x00, 0x00, (byte)'a', (byte)'w', (byte)'e', (byte)'s', (byte)'o', (byte)'m', (byte)'e', 0x00,
					0x01, (byte)'1', 0, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x14, 0x40,
					0x10, (byte)'2', 0, 0xC2, 0x07, 0x00, 0x00,
				0x00,
				0x00
			};

		    var expected = new[]
		    {
				ModelGrammar.TokenObjectBeginUnnamed,
				ModelGrammar.TokenProperty("BSON"),
				ModelGrammar.TokenArrayBeginUnnamed,
				ModelGrammar.TokenPrimitive("awesome"),
				ModelGrammar.TokenPrimitive(5.05),
				ModelGrammar.TokenPrimitive(1986),
				ModelGrammar.TokenArrayEnd,
				ModelGrammar.TokenObjectEnd
		    };

		    var tokenizer = new BsonReader.BsonTokenizer();
		    var actual = tokenizer.GetTokens(input).ToArray();

		    Assert.Equal(expected, actual);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_BooleanValue_ReturnsDocument()
		{
			// input from example at http://codebetter.com/blogs/karlseguin/archive/2010/03/05/bson-serialization.aspx
			var input = new byte[]
				{
					13, 0, 0, 0, 8, 118, 97, 108, 105, 100, 0, 1, 0
				};

			var expected = new[]
			{
				ModelGrammar.TokenObjectBeginUnnamed,
				ModelGrammar.TokenProperty("valid"),
				ModelGrammar.TokenTrue,
				ModelGrammar.TokenObjectEnd
			};

			var tokenizer = new BsonReader.BsonTokenizer();
			var actual = tokenizer.GetTokens(input).ToArray();

			Assert.Equal(expected, actual);
		}

		#endregion Object Tests

		#region Input Edge Case Tests

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_NullByteArray_ThrowsArgumentNullException()
		{
			var input = (byte[])null;
			var expected = new Token<ModelTokenType>[0];

			var tokenizer = new BsonReader.BsonTokenizer();

			ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
				delegate()
				{
					var actual = tokenizer.GetTokens(input).ToArray();
				});

			Assert.Equal("bytes", ex.ParamName);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_NullStream_ThrowsArgumentNullException()
		{
			var input = (Stream)null;
			var expected = new Token<ModelTokenType>[0];

			var tokenizer = new BsonReader.BsonTokenizer();

			ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
				delegate()
				{
					var actual = tokenizer.GetTokens(input).ToArray();
				});

			Assert.Equal("stream", ex.ParamName);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_EmptyByteArray_ReturnsEmptySequence()
		{
			var input = new byte[0];
			var expected = new Token<ModelTokenType>[0];

			var tokenizer = new BsonReader.BsonTokenizer();
			var actual = tokenizer.GetTokens(input).ToArray();

			Assert.Equal(expected, actual);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void GetTokens_EmptyStream_ReturnsEmptySequence()
		{
			var input = Stream.Null;
			var expected = new Token<ModelTokenType>[0];

			var tokenizer = new BsonReader.BsonTokenizer();
			var actual = tokenizer.GetTokens(input).ToArray();

			Assert.Equal(expected, actual);
		}

		#endregion Input Edge Case Tests
	}
}


text:
/*importing Sniglet*/
/*@import url("http://fonts.googleapis.com/css?family=Sniglet");*/

/*basic reset*/
* {margin: 0; padding: 0; box-sizing: border-box;}

body {
    padding-top: 100px;
    background: url('../img/login-bg.png');
    font-family: Sniglet;
}
main {
    width: 500px; margin: 0 auto; padding-bottom: 10px;
    background: white; border-radius: 3px; overflow: hidden;
}
h1 {
    font-size: 24px; font-weight: normal;
    background: hsl(120, 40%, 95%); color: hsl(120, 40%, 40%);
    text-align: center;
    padding: 20px 0; margin-bottom: 40px;
}

.flp {padding: 0 50px;}
/*Let's place the label over the input*/
.flp div {position: relative; margin-bottom: 30px;}

.flp input, .flp label {
    width: 400px; display: block;
    font: inherit; font-size: 16px; line-height: 24px;
    /*fixed height for FF line height issue.
    height = 24(lineheight) + 10*2(padding) + 2(border)*/
    height: 46px;
    border: 1px solid #999;
}
.flp input {padding: 10px; outline: none; border-radius: 3px;}
.flp label {
    position: absolute; left: 0; top: 0;
    /*left/right padding will be 2px less, adjusted by padding on .ch*/
    padding: 10px 8px;
    border-color: transparent; color: #666;
    cursor: text;
}

/*label styles*/
.ch {
    display: block; float: left;
    position: relative; /*for upward animation*/
    background: white;
}
.ch:first-child {padding-left: 2px;}
.ch:last-child {padding-right: 2px;}

/*active input label*/
.focussed {
    /*when any input is already focussed clicking on it(label) again won't do anything*/
    pointer-events: none;
}

/*buttons*/
#submit {
    width: 200px;
    background: #27AE60;
    color: white;
    border: 0 none;
    border-radius: 1px;
    cursor: pointer;
    padding: 10px 5px;
    margin: -5px 90px 15px 90px;
    font-size: medium;
}
#submit:hover, #submit:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #27AE60;
}


text:
require 'spec_helper'

describe 'mysql_java_connector::links' do
  context 'supported operating systems' do
    on_supported_os.each do |os, facts|
      context "on #{os}" do
        let(:title) { '/opt/tomcat_app/lib' }
        let(:facts) do
          facts
        end
        let :pre_condition do
          'include mysql_java_connector'
        end
        context "mysql_java_connector class with custom parameters" do
          it { is_expected.to contain_file('/opt/tomcat_app/lib/mysql-connector-java.jar')
            .with({
              'ensure' => 'link',
              'target' => '/opt/MySQL-connector/latest/mysql-connector-java-5.1.34-bin.jar',
          })}
        end
      end
    end
  end
end


text:
JavaScript port of the [OpenChemLib](https://github.com/actelion/openchemlib) Java library.

    Maintained by Zakodium

  [![NPM version][npm-image]][npm-url]
  [![build status][ci-image]][ci-url]
  [![npm download][download-image]][download-url]
  [![DOI](https://www.zenodo.org/badge/23346814.svg)](https://www.zenodo.org/badge/latestdoi/23346814)

## Installation

```console
npm install openchemlib
```

## Documentation

This library is available in three different builds: `minimal`, `core` and `full`.
Each larger build contains all functionalities from the smaller ones.

The `core` build is the one that you get when you `require('openchemlib')`. It
contains all functionalities that can be used in Node.js.

The `minimal` (`require('openchemlib/minimal')`) build is a smaller one
(~ half the size of `core`) that is meant to be used in a browser application
if bundle size matters and prediction functionalities are not needed.

The `full` build (`require('openchemlib/full')`) build is the largest build.
It contains a structure viewer and a structure editor for browser applications.

- [TypeDoc home page](https://cheminfo.github.io/openchemlib-js/index.html)

### Modules present in minimal, core and full builds

- [Molecule](https://cheminfo.github.io/openchemlib-js/classes/Molecule.html)
- [Reaction](https://cheminfo.github.io/openchemlib-js/classes/Reaction.html)
- [RingCollection](https://cheminfo.github.io/openchemlib-js/classes/RingCollection.html)
- [SDFileParser](https://cheminfo.github.io/openchemlib-js/classes/SDFileParser.html)
- [SSSearcher](https://cheminfo.github.io/openchemlib-js/classes/SSSearcher.html)
- [SSSearcherWithIndex](https://cheminfo.github.io/openchemlib-js/classes/SSSearcherWithIndex.html)
- [Util](https://cheminfo.github.io/openchemlib-js/modules/Util.html)

### Modules present only in core and full builds

- [CanonizerUtil](https://cheminfo.github.io/openchemlib-js/classes/CanonizerUtil.html)
- [ConformerGenerator](https://cheminfo.github.io/openchemlib-js/classes/ConformerGenerator.html)
- [DruglikenessPredictor](https://cheminfo.github.io/openchemlib-js/classes/DruglikenessPredictor.html)
- [DrugScoreCalculator](https://cheminfo.github.io/openchemlib-js/modules/DrugScoreCalculator.html)
- [ForceFieldMMFF94](https://cheminfo.github.io/openchemlib-js/classes/ForceFieldMMFF94.html)
- [MoleculeProperties](https://cheminfo.github.io/openchemlib-js/classes/MoleculeProperties.html)
- [ToxicityPredictor](https://cheminfo.github.io/openchemlib-js/classes/ToxicityPredictor.html)

### Modules present only in full build

- [StructureEditor](https://cheminfo.github.io/openchemlib-js/classes/StructureEditor.html)
- [StructureView](https://cheminfo.github.io/openchemlib-js/modules/StructureView.html)
- [SVGRenderer](https://cheminfo.github.io/openchemlib-js/modules/SVGRenderer.html)

## Development

To build this project, you need :

- Java JDK (Tested with version 17)
- GWT (Tested with version 2.10, [Download build here](http://www.gwtproject.org/download.html))
- Node.js (Tested with version 18, [Dowload here](https://nodejs.org/en/download/))

### Install dependencies

`npm ci`

### Configure directories

Copy `config.default.json` to `config.json` and put the path to the GWT classes on your computer.
If you want to use a custom JDK installation, set the "jdk" key to be the path to your JDK directory.

### npm scripts

To run one of the scripts, use `npm run <scriptName>`.
To pass an options, use `npm run <scriptName> -- --option`.

**Options**:

- -m [name]: only process module "name"
- -v: verbose output

#### compile:min / compile:pretty

Execute the GWT compiler.

#### export

Transform the GWT compiled files to JavaScript modules.

#### build:min / build:pretty

Compile and export.

#### copy:openchemlib

Copy the required java files from the openchemlib project.

## License

[BSD-3-Clause](./LICENSE)

[npm-image]: https://img.shields.io/npm/v/openchemlib.svg
[npm-url]: https://www.npmjs.com/package/openchemlib
[ci-image]: https://github.com/cheminfo/openchemlib-js/workflows/Node.js%20CI/badge.svg?branch=main
[ci-url]: https://github.com/cheminfo/openchemlib-js/actions?query=workflow%3A%22Node.js+CI%22
[download-image]: https://img.shields.io/npm/dm/openchemlib.svg
[download-url]: https://www.npmjs.com/package/openchemlib


text:
"""docstring goes here""" # :-)

from django.conf import settings
from django.contrib.auth.models import User
import base64
import os
import sys

from api.models import Registry

def initialise_crypto():
    nbytes = 256/8
    Registry.set_encoded('__MINE_HMAC_KEY__', os.urandom(nbytes), False)
    Registry.set_encoded('__MINE_HMAC_PAD__', os.urandom(nbytes), False)
    Registry.set_encoded('__MINE_IVGEN_SEED__', os.urandom(nbytes), False)
    Registry.set_encoded('__MINE_SECRET_KEY__', os.urandom(nbytes), False)
    Registry.set_encoded('__MINE_SECRET_PAD__', os.urandom(nbytes), False)

def create_user(username, password):
    u = User()
    u.username = username
    u.set_password(password)
    u.save()

def usage():
    print "usage:"
    print "\tinit-crypto # call only once"
    print "\tcreate-user username password"
    print "\tset key value [0|1] # 1 to permit overwrites"
    print "\tset-encoded key value [0|1] # 1 to permit overwrites"

def main(argv):
    cmds = {
	'create-user': create_user,
	'init-crypto': initialise_crypto,
	'set': Registry.set,
	'set-encoded': Registry.set_encoded,
	}
    fn = usage
    if len(argv) > 0:
        fn = cmds.get(argv[0], usage)
    fn(*argv[1:])

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package org.cagrid.gaards.dorian.test.system;

import gov.nih.nci.cagrid.testing.system.deployment.ServiceContainer;
import gov.nih.nci.cagrid.testing.system.deployment.steps.CopyServiceStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DeleteServiceStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DeployServiceStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DestroyContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.StartContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.StopContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.UnpackContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.story.ServiceStoryBase;
import gov.nih.nci.cagrid.testing.system.haste.Step;
import gov.nih.nci.cagrid.testing.system.utils.steps.ModifyConfigurationStep;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.xml.namespace.QName;

import org.cagrid.gaards.authentication.BasicAuthentication;
import org.cagrid.gaards.authentication.common.AuthenticationProfile;
import org.cagrid.gaards.authentication.faults.InvalidCredentialFault;
import org.cagrid.gaards.authentication.test.system.steps.AuthenticationStep;
import org.cagrid.gaards.authentication.test.system.steps.InvalidAuthentication;
import org.cagrid.gaards.authentication.test.system.steps.SuccessfullAuthentication;
import org.cagrid.gaards.authentication.test.system.steps.ValidateSupportedAuthenticationProfilesStep;
import org.cagrid.gaards.dorian.federation.AutoApprovalPolicy;
import org.cagrid.gaards.dorian.federation.GridUserStatus;
import org.cagrid.gaards.dorian.federation.TrustedIdPStatus;
import org.cagrid.gaards.dorian.idp.Application;
import org.cagrid.gaards.dorian.idp.CountryCode;
import org.cagrid.gaards.dorian.idp.LocalUserRole;
import org.cagrid.gaards.dorian.idp.LocalUserStatus;
import org.cagrid.gaards.dorian.idp.StateCode;
import org.cagrid.gaards.dorian.stubs.types.PermissionDeniedFault;
import org.cagrid.gaards.dorian.test.system.steps.ChangeLocalUserPasswordStep;
import org.cagrid.gaards.dorian.test.system.steps.CleanupDorianStep;
import org.cagrid.gaards.dorian.test.system.steps.ConfigureGlobusToTrustDorianStep;
import org.cagrid.gaards.dorian.test.system.steps.FindGridUserStep;
import org.cagrid.gaards.dorian.test.system.steps.FindLocalUserStep;
import org.cagrid.gaards.dorian.test.system.steps.GetAsserionSigningCertificateStep;
import org.cagrid.gaards.dorian.test.system.steps.GridCredentialRequestStep;
import org.cagrid.gaards.dorian.test.system.steps.GridUserSearchStep;
import org.cagrid.gaards.dorian.test.system.steps.InvalidGridCredentialRequest;
import org.cagrid.gaards.dorian.test.system.steps.RegisterUserWithDorianIdentityProviderStep;
import org.cagrid.gaards.dorian.test.system.steps.SuccessfullGridCredentialRequest;
import org.cagrid.gaards.dorian.test.system.steps.UpdateGridUserStatusStep;
import org.cagrid.gaards.dorian.test.system.steps.UpdateLocalUserStatusStep;
import org.cagrid.gaards.dorian.test.system.steps.VerifyTrustedIdPStep;

public class DorianLocaIdentityProviderTest extends ServiceStoryBase {

    private File properties;
    private File tempService;
    private ConfigureGlobusToTrustDorianStep trust;

	public DorianLocaIdentityProviderTest() {
		super();
	}

    public DorianLocaIdentityProviderTest(ServiceContainer container) {
        this(container, null);
    }

    public DorianLocaIdentityProviderTest(ServiceContainer container, File properties) {
        super(container);
        this.properties = properties;
    }

    @Override
    public String getName() {
        return "Dorian Local Identity Provider System Test";
    }

    public String getDescription() {
        return "Dorian Local Identity Provider System Test";
    }

    protected Vector<Step> steps() {
        Vector<Step> steps = new Vector<Step>();
        try {
            steps.add(new UnpackContainerStep(getContainer()));
            File originalPropertyFile = new File(tempService
					.getAbsolutePath()
					+ File.separator
					+ "etc"
					+ File.separator
					+ "dorian.properties");
            steps.add(new ModifyConfigurationStep(originalPropertyFile, properties));

            steps.add(new DeployServiceStep(getContainer(), this.tempService.getAbsolutePath()));

            trust = new ConfigureGlobusToTrustDorianStep(getContainer());
            steps.add(trust);

            steps.add(new StartContainerStep(getContainer()));

            GetAsserionSigningCertificateStep signingCertStep = new GetAsserionSigningCertificateStep(getContainer());
            steps.add(signingCertStep);

            String serviceURL = getContainer().getContainerBaseURI().toString() + "cagrid/Dorian";

            // Test Get supported authentication types

            Set<QName> expectedProfiles = new HashSet<QName>();
            expectedProfiles.add(AuthenticationProfile.BASIC_AUTHENTICATION);
            steps.add(new ValidateSupportedAuthenticationProfilesStep(serviceURL, expectedProfiles));

            SuccessfullAuthentication success = new SuccessfullAuthentication("dorian", "Mr.", "Administrator",
                "dorian@dorian.org", signingCertStep);

            // Test Successful authentication
            BasicAuthentication cred = new BasicAuthentication();
            cred.setUserId("dorian");
            cred.setPassword("DorianAdmin$1");
            AuthenticationStep adminAuth = new AuthenticationStep(serviceURL, success, cred);
            steps.add(adminAuth);

            // Get Admin's Grid Credentials

            GridCredentialRequestStep admin = new GridCredentialRequestStep(serviceURL, adminAuth,
                new SuccessfullGridCredentialRequest());
            steps.add(admin);

            // Test that the Dorian Idp is properly registered.

            VerifyTrustedIdPStep idp = new VerifyTrustedIdPStep(serviceURL, admin, "Dorian");
            idp.setDisplayName("Dorian");
            idp.setStatus(TrustedIdPStatus.Active);
            idp.setUserPolicyClass(AutoApprovalPolicy.class.getName());
            idp.setAuthenticationServiceURL(serviceURL);
            idp.setPublish(true);
            steps.add(idp);

            // Create Users
            List<Application> users = new ArrayList<Application>();
            for (int i = 0; i < 3; i++) {
                Application a = new Application();
                a.setUserId("jdoe" + i);
                a.setPassword("K00lM0N$$" + i);
                a.setFirstName("John" + i);
                a.setLastName("Doe" + i);
                a.setEmail(a.getUserId() + "@cagrid.org");
                a.setOrganization("cagrid.org");
                a.setAddress("123" + i + " Grid Way");
                a.setCity("Columbus");
                a.setState(StateCode.OH);
                a.setCountry(CountryCode.US);
                a.setZipcode("43210");
                a.setPhoneNumber("(555) 555-555" + i);
                users.add(a);
                steps.add(new RegisterUserWithDorianIdentityProviderStep(serviceURL, a));
            }

            // Test that the user accounts were create correctly
            for (int i = 0; i < 3; i++) {
                steps.add(new FindLocalUserStep(serviceURL, admin, users.get(i), LocalUserStatus.Pending,
                    LocalUserRole.Non_Administrator));
            }

            // Test that the users cannot authenticate until they are approved.
            for (int i = 0; i < users.size(); i++) {
                BasicAuthentication auth = new BasicAuthentication();
                auth.setUserId(users.get(i).getUserId());
                auth.setPassword(users.get(i).getPassword());
                steps
                    .add(new AuthenticationStep(serviceURL, new InvalidAuthentication(
                        "The application for this account has not yet been reviewed.", InvalidCredentialFault.class),
                        auth));
            }

            // Approve the user accounts

            for (int i = 0; i < users.size(); i++) {
                steps.add(new UpdateLocalUserStatusStep(serviceURL, admin, users.get(i).getUserId(),
                    LocalUserStatus.Active));
            }

            // Test that the user accounts were approved correctly
            for (int i = 0; i < users.size(); i++) {
                steps.add(new FindLocalUserStep(serviceURL, admin, users.get(i), LocalUserStatus.Active,
                    LocalUserRole.Non_Administrator));
            }

            // Test successful Authentication
            List<GridCredentialRequestStep> userCredentials = new ArrayList<GridCredentialRequestStep>();

            for (int i = 0; i < users.size(); i++) {
                SuccessfullAuthentication sa = new SuccessfullAuthentication(users.get(i).getUserId(), users.get(i)
                    .getFirstName(), users.get(i).getLastName(), users.get(i).getEmail(), signingCertStep);

                // Test Successful authentication
                BasicAuthentication ba = new BasicAuthentication();
                ba.setUserId(users.get(i).getUserId());
                ba.setPassword(users.get(i).getPassword());
                AuthenticationStep userAuth = new AuthenticationStep(serviceURL, sa, ba);
                steps.add(userAuth);
                GridCredentialRequestStep proxy = new GridCredentialRequestStep(serviceURL, userAuth,
                    new SuccessfullGridCredentialRequest());
                steps.add(proxy);
                userCredentials.add(proxy);

                FindGridUserStep gridUser = new FindGridUserStep(serviceURL, admin, proxy);
                gridUser.setExpectedEmail(users.get(i).getEmail());
                gridUser.setExpectedFirstName(users.get(i).getFirstName());
                gridUser.setExpectedLastName(users.get(i).getLastName());
                gridUser.setExpectedLocalUserId(users.get(i).getUserId());
                gridUser.setExpectedStatus(GridUserStatus.Active);
                steps.add(gridUser);

                GridUserSearchStep gridUserRecord = new GridUserSearchStep(serviceURL,proxy);
                gridUserRecord.setExpectedEmail(users.get(i).getEmail());
                gridUserRecord.setExpectedFirstName(users.get(i).getFirstName());
                gridUserRecord.setExpectedLastName(users.get(i).getLastName());
                steps.add(gridUserRecord);
            }

            // Test Suspending Accounts Locally

            for (int i = 0; i < users.size(); i++) {
                steps.add(new UpdateLocalUserStatusStep(serviceURL, admin, users.get(i).getUserId(),
                    LocalUserStatus.Suspended));
                steps.add(new FindLocalUserStep(serviceURL, admin, users.get(i), LocalUserStatus.Suspended,
                    LocalUserRole.Non_Administrator));
                BasicAuthentication auth = new BasicAuthentication();
                auth.setUserId(users.get(i).getUserId());
                auth.setPassword(users.get(i).getPassword());
                steps.add(new AuthenticationStep(serviceURL, new InvalidAuthentication(
                    "The account has been suspended.", InvalidCredentialFault.class), auth));
                steps.add(new UpdateLocalUserStatusStep(serviceURL, admin, users.get(i).getUserId(),
                    LocalUserStatus.Active));
                steps.add(new FindLocalUserStep(serviceURL, admin, users.get(i), LocalUserStatus.Active,
                    LocalUserRole.Non_Administrator));
            }

            // Test suspending grid accounts

            for (int i = 0; i < users.size(); i++) {
                steps.add(new UpdateGridUserStatusStep(serviceURL, admin, userCredentials.get(i),
                    GridUserStatus.Suspended));

                FindGridUserStep gridUser = new FindGridUserStep(serviceURL, admin, userCredentials.get(i));
                gridUser.setExpectedEmail(users.get(i).getEmail());
                gridUser.setExpectedFirstName(users.get(i).getFirstName());
                gridUser.setExpectedLastName(users.get(i).getLastName());
                gridUser.setExpectedLocalUserId(users.get(i).getUserId());
                gridUser.setExpectedStatus(GridUserStatus.Suspended);
                steps.add(gridUser);

                SuccessfullAuthentication sa = new SuccessfullAuthentication(users.get(i).getUserId(), users.get(i)
                    .getFirstName(), users.get(i).getLastName(), users.get(i).getEmail(), signingCertStep);
                BasicAuthentication ba = new BasicAuthentication();
                ba.setUserId(users.get(i).getUserId());
                ba.setPassword(users.get(i).getPassword());
                AuthenticationStep userAuth = new AuthenticationStep(serviceURL, sa, ba);
                steps.add(userAuth);
                GridCredentialRequestStep proxy = new GridCredentialRequestStep(serviceURL, userAuth,
                    new InvalidGridCredentialRequest("The account has been suspended.", PermissionDeniedFault.class));
                steps.add(proxy);

                steps
                    .add(new UpdateGridUserStatusStep(serviceURL, admin, userCredentials.get(i), GridUserStatus.Active));

                FindGridUserStep gridUser2 = new FindGridUserStep(serviceURL, admin, userCredentials.get(i));
                gridUser2.setExpectedEmail(users.get(i).getEmail());
                gridUser2.setExpectedFirstName(users.get(i).getFirstName());
                gridUser2.setExpectedLastName(users.get(i).getLastName());
                gridUser2.setExpectedLocalUserId(users.get(i).getUserId());
                gridUser2.setExpectedStatus(GridUserStatus.Active);
                steps.add(gridUser2);
            }

            // Test that the user can change there password

            for (int i = 0; i < users.size(); i++) {
                String newPassword = "K00lM0N##" + i;
                steps.add(new ChangeLocalUserPasswordStep(serviceURL, users.get(i), newPassword));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return steps;
    }

    protected boolean storySetUp() throws Throwable {
        this.tempService = new File("tmp/dorian");
        File asLocation = new File("../../../caGrid/projects/dorian");
        CopyServiceStep copyService = new CopyServiceStep(asLocation, tempService);
        copyService.runStep();
        // this.tempService = copyService.getServiceDirectory();
        return true;
    }

    protected void storyTearDown() throws Throwable {
        try {
            if (this.tempService != null) {
                new DeleteServiceStep(tempService).runStep();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        StopContainerStep step2 = new StopContainerStep(getContainer());
        try {
            step2.runStep();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        CleanupDorianStep cleanup = new CleanupDorianStep(getContainer(), trust);
        try {
            cleanup.runStep();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        DestroyContainerStep step3 = new DestroyContainerStep(getContainer());
        try {
            step3.runStep();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}