text:
import { Utility } from './utility';
import { AuthedAccount } from '../apiClasses/authedAccount';
import { FileUploadOptions, FileUploadResult } from '@ionic-native/transfer';
import { TootForm } from '../apiClasses/tootForm';
import { RequestOptionsArgs } from '@angular/http/src/interfaces';
import { Transfer } from '@ionic-native/transfer';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class APIProvider {
  currentAccount: AuthedAccount;

  mediaUploadsProgress:any = {};

  constructor(public http: Http, public utility: Utility, public transfer: Transfer) {
    this.currentAccount = utility.getCurrentAccount();
  }

  setCurrentAccount(currentAccount: AuthedAccount){
    this.currentAccount = currentAccount;
  }

  getHashtag(hashtag:string){
    return this.getRequest('/api/v1/timelines/tag/' + hashtag);
  }

  getTootThread(toot_id:string){
    return this.getRequest('/api/v1/statuses/' + toot_id + '/context');
  }

  getFollowersOfUser(account_id:string, last_id?:string){
    if(last_id){
      let requestOptions: RequestOptions = new RequestOptions();
      let params: URLSearchParams = new URLSearchParams();
      params.set('max_id',last_id)
      requestOptions.search  = params;
      return this.getRequest('/api/v1/accounts/' + account_id + "/followers", requestOptions);
    } else{
      return this.getRequest('/api/v1/accounts/' + account_id + "/followers");
    }
  }
  getFollowingOfUser(account_id:string, last_id?:string){
    if(last_id){
      let requestOptions: RequestOptions = new RequestOptions();
      let params: URLSearchParams = new URLSearchParams();
      params.set('max_id',last_id)
      requestOptions.search  = params;
      return this.getRequest('/api/v1/accounts/' + account_id + "/following", requestOptions);
    } else{
      return this.getRequest('/api/v1/accounts/' + account_id + "/following");
    }
  }

  blockUser(account_id: string){
    return this.postRequest('/api/v1/accounts/' + account_id + '/block', {})
  }

  unblockUser(account_id: string){
    return this.postRequest('/api/v1/accounts/' + account_id + '/unblock', {})
  }

  followUser(account_id: string){
    let data = {};
    return this.postRequest('/api/v1/accounts/'+ account_id + '/follow', data);
  }

  unfollowUser(account_id: string){
    let data = {};
    return this.postRequest('/api/v1/accounts/'+ account_id + '/unfollow', data);
  }

  getRelationshipOfAccount(account_id: string){
    let requestOptions: RequestOptions = new RequestOptions();
    let params: URLSearchParams = new URLSearchParams;
    params.set('id', account_id);
    requestOptions.search= params;
    return this.getRequest('/api/v1/accounts/relationships', requestOptions);
  }

  getAccount(account_id: string){
    return this.getRequest('/api/v1/accounts/'+account_id);
  }

  getTootsOfUser(account_id: string, max_id?: string, since_id?: string): Observable<Response>{
    if(max_id == undefined && since_id == undefined){
      return this.getRequest('/api/v1/accounts/'+account_id+'/statuses');
    } else {
      console.log('other params defined assigning max_id: '+max_id +' and since_id: '+ since_id)
      let requestOptions: RequestOptions = new RequestOptions();
      let params: URLSearchParams = new URLSearchParams();
      if(max_id){
        params.set('max_id', max_id)
      }
      if(since_id){
        params.set('since_id', since_id)
      }
      requestOptions.search = params;
      return this.getRequest('/api/v1/accounts/'+account_id+'/statuses',requestOptions);
    }
  }

  getNotifications(max_id?: string, since_id?: string): Observable<Response>{
    if(max_id == undefined && since_id == undefined){
      return this.getRequest('/api/v1/notifications')
    } else {
      let requestOptions: RequestOptions = new RequestOptions();
      let params: URLSearchParams = new URLSearchParams();
      if(max_id){
        params.set('max_id', max_id)
      }
      if(since_id){
        params.set('since_id', since_id)
      }
      requestOptions.search = params;
      return this.getRequest("/api/v1/notifications", requestOptions);
    }
  }

  uploadMedia(fileURL: string): Promise<FileUploadResult>{
    let fileTransfer = this.transfer.create();
    let options: any = {};
    let mediaType = fileURL.substring(fileURL.lastIndexOf('.'));
    //.GIF?BSDFH
    mediaType = mediaType.toLowerCase();
    let cutSymbolPosition = mediaType.indexOf('?');
    if(cutSymbolPosition != -1){
      mediaType = mediaType.substring(0,cutSymbolPosition);
    }
    console.log(mediaType);

    switch(mediaType){
      case('.jpg' || '.jpeg'):
        options.mimeType = "image/jpeg"
        options.fileName = "tootyFruity_image.jpg"
        break;
      case('.png'):
        options.mimeType = "image/png"
        options.fileName = "tootyFruity_image.png"
        break;
      case('.gif'):
        options.mimeType = "image/gif"
        options.fileName = "tootyFruity_image.gif"
        options.chunkedMode = false;
        break;
      default:
        return null;
    }
    options.headers = {'Authorization' : 'Bearer '+ this.currentAccount.accessToken}
    console.log(fileURL);
    console.log(JSON.stringify(options))
    let uploadOptions: FileUploadOptions;
    uploadOptions = options;
    console.log(uploadOptions)
    // this.fileTransfer.onProgress((progressEvent: ProgressEvent) : void => {
    //   if(progressEvent.lengthComputable){
    //     this.mediaUploadsProgress.maxValue = progressEvent.total;
    //     this.mediaUploadsProgress.loadedValue = progressEvent.loaded;
    //     console.log(JSON.stringify(this.mediaUploadsProgress))
    //   }
    // })
    return fileTransfer.upload(fileURL, this.currentAccount.instanceUrl + "/api/v1/media", uploadOptions);
  }

  getTimeline(type: string,  max_id?: string, since_id?: string): Observable<Response> {
    console.log(this.currentAccount.mastodonAccount.acct);
    if(max_id == undefined && since_id == undefined && type !='local'){
      return this.getRequest('/api/v1/timelines/' + type)
    } else {
      let requestOptions: RequestOptions = new RequestOptions();
      let params: URLSearchParams = new URLSearchParams();
      if(type == 'local'){
        params.set('local', 'true');
        var type='public';
      }
      if(max_id){
        params.set('max_id', max_id)
      }
      if(since_id){
        params.set('since_id', since_id)
      }
      requestOptions.search = params;
      return this.getRequest('/api/v1/timelines/' + type, requestOptions);
    }
  }

  postToot(newToot:TootForm): Observable<Response>{
    let body = {'status': newToot.status,
                'visibility': newToot.visibility};

    if(newToot.in_reply_to_id != null){
      body['in_reply_to_id'] = newToot.in_reply_to_id;
    }
    if(newToot.spoiler_text != null){
      body['spoiler_text'] = newToot.spoiler_text;
    }

    if(newToot.media_ids != null){
      if(newToot.sensitive) {
        body['sensitive'] = newToot.sensitive;
      }
      body['media_ids'] = newToot.media_ids;
    }
    return this.postRequest('/api/v1/statuses',body);
  }

  newLinesToHTML(val: string) : string{
    return '
' + val.replace(/[\r\n]+/g, '

') + '
';
  }

  unFavoriteStatus(tootID: string): Observable<Response>{
    let data = {};
    return this.postRequest('/api/v1/statuses/'+tootID+'/unfavourite', data);
  }

  favoriteStatus(tootID: string): Observable<Response>{
    let data = {};
    return this.postRequest('/api/v1/statuses/'+tootID+'/favourite', data);
  }

  boostStatus(tootID: string): Observable<Response>{
    let data = {};
    return this.postRequest('/api/v1/statuses/'+tootID+'/reblog', data);
  }

  getAuthenticatedUser(): Observable<Response> {
    return this.getRequest('/api/v1/accounts/verify_credentials');
  }

  unBoostStatus(tootID: string): Observable<Response>{
    let data = {};
    return this.postRequest('/api/v1/statuses/'+tootID+'/unreblog', data);
  }

  search(q: string, resolve:boolean = true){
    let requestOptions: RequestOptions = new RequestOptions();
    let params: URLSearchParams = new URLSearchParams();
    params.set('q', q)
    params.set('resolve', resolve.toString())
    requestOptions.search = params

    return this.getRequest('/api/v1/search/', requestOptions);
  }

  private getRequest(url: string, requestOptions?: RequestOptionsArgs): Observable<Response> {
    requestOptions = this.finalizeRequestOptions(requestOptions);
    console.log('GET REQUEST ' + url + " with params: " + requestOptions.search);
    return this.http.get(this.currentAccount.instanceUrl + url, requestOptions);
  }

  private postRequest(apiUrl:string, body:any): Observable<Response>{
    let requestOptions = this.finalizeRequestOptions();
    return this.http.post(this.currentAccount.instanceUrl + apiUrl, body, requestOptions);
  }

  preAuthPost(api_url: string, body: any): Observable<any>{
    let contentTypeHeaders = new Headers(['Content-type', 'application/json'])
    let request = new RequestOptions({ headers: contentTypeHeaders});
    console.log(api_url)
    return this.http.post(api_url, body, request)
      .map(this.extractData)
      .catch(err => {
        console.log(JSON.stringify(err));
        return Observable.throw(err); // observable needs to be returned or exception raised
      })
  }

  private finalizeRequestOptions(requestOptions?: RequestOptionsArgs){
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('Authorization', 'Bearer '+ this.currentAccount.accessToken);
    if(requestOptions){
      requestOptions.headers = headers;
    } else {
      requestOptions = new RequestOptions({ headers: headers });
    }
    return requestOptions;
  }

  private extractData(res: Response) {
    let body = res.json();
    if (body.data == undefined) return body
    else return body.data;
  }

}


text:
<?php
/**
 * Example of Music
 * @see	https://developers.google.com/search/docs/data-types/music
 */
require_once '../autoload.php';

$musicGroup = new \Org\Schema\Thing\Organization\PerformingGroup\MusicGroup();
$musicGroup->url = "http://www.example.com/artist/Katy-Perry/";
$musicGroup->image = [
	"https://example.com/photos/1x1/photo.jpg",
	"https://example.com/photos/4x3/photo.jpg",
	"https://example.com/photos/16x9/photo.jpg"
];
$musicGroup->name = "Katy Perry";
$musicGroup->sameAs = "http://www.katyperry.com";
$musicGroup->description = "Katy Perry is a pop music artist.";
$musicGroup->potentialAction = new \Org\Schema\Thing\Action\ConsumeAction\ListenAction();
$musicGroup->potentialAction->target = [];

$entyPoint = new \Org\Schema\Thing\Intangible\EntryPoint();
$entyPoint->urlTemplate = "http://www.example.com/artist/Katy-Perry/?autoplay=true";
$entyPoint->actionPlatform = [
	"http://schema.org/DesktopWebPlatform",
	"http://schema.org/IOSPlatform",
	"http://schema.org/AndroidPlatform"
];
$musicGroup->potentialAction->target[] = $entyPoint;
unset($entyPoint);

$entyPoint = new \Org\Schema\Thing\Intangible\EntryPoint();
$entyPoint->urlTemplate = "android-app://com.example.app/examplescheme/artist/Katy-Perry/?autoplay=true";
$entyPoint->actionPlatform = "http://schema.org/AndroidPlatform";

$musicGroup->potentialAction->target[] = $entyPoint;
unset($entyPoint);

$musicGroup->potentialAction->expectsAcceptanceOf = new \Org\Schema\Thing\Intangible\Offer();

$musicGroup->potentialAction->expectsAcceptanceOf->eligibleRegion = [];

$country = new \Org\Schema\Thing\Place\AdministrativeArea\Country();
$country->name = "US";

$musicGroup->potentialAction->expectsAcceptanceOf->eligibleRegion[] = $country;
unset($country);

$country = new \Org\Schema\Thing\Place\AdministrativeArea\Country();
$country->name = "BR";

$musicGroup->potentialAction->expectsAcceptanceOf->eligibleRegion[] = $country;
unset($country);

echo $musicGroup->toJson(JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);

?>

redpajama_set_name: RedPajamaGithub


text:
/* 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.
 */
package org.flowable.cmmn.engine.impl.persistence.entity;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.cmmn.engine.CmmnEngineConfiguration;
import org.flowable.common.engine.impl.context.Context;
import org.flowable.variable.service.impl.persistence.entity.HistoricVariableInitializingList;
import org.flowable.variable.service.impl.persistence.entity.HistoricVariableInstanceEntity;

/**
 * @author Joram Barrez
 */
public class HistoricCaseInstanceEntityImpl extends AbstractCmmnEngineEntity implements HistoricCaseInstanceEntity {

    protected String businessKey;
    protected String name;
    protected String parentId;
    protected String caseDefinitionId;
    protected String state;
    protected Date startTime;
    protected Date endTime;
    protected String startUserId;
    protected String callbackId;
    protected String callbackType;
    protected String referenceId;
    protected String referenceType;
    protected String tenantId = CmmnEngineConfiguration.NO_TENANT_ID;
    protected List<HistoricVariableInstanceEntity> queryVariables;

    // non persisted
    protected String caseDefinitionKey;
    protected String caseDefinitionName;
    protected Integer caseDefinitionVersion;
    protected String caseDefinitionDeploymentId;

    @Override
    public Object getPersistentState() {
        Map<String, Object> persistentState = new HashMap<>();
        persistentState.put("businessKey", businessKey);
        persistentState.put("name", name);
        persistentState.put("parentId", parentId);
        persistentState.put("caseDefinitionId", caseDefinitionId);
        persistentState.put("state", state);
        persistentState.put("startTime", startTime);
        persistentState.put("endTime", endTime);
        persistentState.put("startUserId", startUserId);
        persistentState.put("callbackId", callbackId);
        persistentState.put("callbackType", callbackType);
        persistentState.put("referenceId", referenceId);
        persistentState.put("referenceType", referenceType);
        persistentState.put("tenantId", tenantId);
        return persistentState;
    }

    @Override
    public String getBusinessKey() {
        return businessKey;
    }
    @Override
    public void setBusinessKey(String businessKey) {
        this.businessKey = businessKey;
    }
    @Override
    public String getName() {
        return name;
    }
    @Override
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String getParentId() {
        return parentId;
    }
    @Override
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    @Override
    public String getCaseDefinitionId() {
        return caseDefinitionId;
    }
    @Override
    public void setCaseDefinitionId(String caseDefinitionId) {
        this.caseDefinitionId = caseDefinitionId;
    }
    @Override
    public String getState() {
        return state;
    }
    @Override
    public void setState(String state) {
        this.state = state;
    }
    @Override
    public Date getStartTime() {
        return startTime;
    }
    @Override
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
    @Override
    public Date getEndTime() {
        return endTime;
    }
    @Override
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    @Override
    public String getStartUserId() {
        return startUserId;
    }
    @Override
    public void setStartUserId(String startUserId) {
        this.startUserId = startUserId;
    }
    @Override
    public String getCallbackId() {
        return callbackId;
    }
    @Override
    public void setCallbackId(String callbackId) {
        this.callbackId = callbackId;
    }
    @Override
    public String getCallbackType() {
        return callbackType;
    }
    @Override
    public void setCallbackType(String callbackType) {
        this.callbackType = callbackType;
    }
    @Override
    public String getReferenceId() {
        return referenceId;
    }
    @Override
    public void setReferenceId(String referenceId) {
        this.referenceId = referenceId;
    }
    @Override
    public String getReferenceType() {
        return referenceType;
    }
    @Override
    public void setReferenceType(String referenceType) {
        this.referenceType = referenceType;
    }
    @Override
    public String getTenantId() {
        return tenantId;
    }
    @Override
    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }

    @Override
    public Map<String, Object> getCaseVariables() {
        Map<String, Object> variables = new HashMap<>();
        if (queryVariables != null) {
            for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
                if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
                    variables.put(variableInstance.getName(), variableInstance.getValue());
                }
            }
        }
        return variables;
    }

    @Override
    public List<HistoricVariableInstanceEntity> getQueryVariables() {
        if (queryVariables == null && Context.getCommandContext() != null) {
            queryVariables = new HistoricVariableInitializingList();
        }
        return queryVariables;
    }

    public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
        this.queryVariables = queryVariables;
    }

    @Override
    public String getCaseDefinitionKey() {
        return caseDefinitionKey;
    }

    @Override
    public void setCaseDefinitionKey(String caseDefinitionKey) {
        this.caseDefinitionKey = caseDefinitionKey;
    }

    @Override
    public String getCaseDefinitionName() {
        return caseDefinitionName;
    }

    @Override
    public void setCaseDefinitionName(String caseDefinitionName) {
        this.caseDefinitionName = caseDefinitionName;
    }

    @Override
    public Integer getCaseDefinitionVersion() {
        return caseDefinitionVersion;
    }

    @Override
    public void setCaseDefinitionVersion(Integer caseDefinitionVersion) {
        this.caseDefinitionVersion = caseDefinitionVersion;
    }

    @Override
    public String getCaseDefinitionDeploymentId() {
        return caseDefinitionDeploymentId;
    }

    @Override
    public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) {
        this.caseDefinitionDeploymentId = caseDefinitionDeploymentId;
    }
}


text:
id: jest
title: Jest – Unit Testing
layout: docs
category: Complementary
permalink: http://facebook.github.io/jest/
---


text:
#include <stdio.h>
#include <sbml/SBMLTypes.h>

#include <sbml/xml/XMLNode.h>
#include <sbml/annotation/CVTerm.h>

int
main (int argc, char *argv[])
{

  SBMLDocument_t* d;
  Model_t* m;
  unsigned int  errors, n;
  Species_t *s;

  if (argc != 3)
  {
    printf("\n"
         "  usage: addCVTerms <input-filename> <output-filename>\n"
         "  Adds controlled vocabulary term to a species\n"
         "\n");
    return 2;
  }

  d      = readSBML(argv[1]);
  errors = SBMLDocument_getNumErrors(d);

  if (errors > 0)
  {
    printf("Read Error(s):\n");
    SBMLDocument_printErrors(d, stdout);
    printf("Correct the above and re-run.\n");
  }
  else
  {
    m = SBMLDocument_getModel(d);
    n =  Model_getNumSpecies(m);

    if (n <= 0)
    {
      printf( "Model has no species.\n Cannot add CV terms\n");
    }
    else
    {
      CVTerm_t *cv, *cv1, *cv2;
      s = Model_getSpecies(m ,0);

      cv = CVTerm_createWithQualifierType(BIOLOGICAL_QUALIFIER);
      CVTerm_setBiologicalQualifierType(cv, BQB_IS_VERSION_OF);
      CVTerm_addResource(cv, "http://www.geneontology.org/#GO:0005892");

      cv2 = CVTerm_createWithQualifierType(BIOLOGICAL_QUALIFIER);
      CVTerm_setBiologicalQualifierType(cv2, BQB_IS);
      CVTerm_addResource(cv2, "http://www.geneontology.org/#GO:0005895");

      cv1 = CVTerm_createWithQualifierType(BIOLOGICAL_QUALIFIER);
      CVTerm_setBiologicalQualifierType(cv1, BQB_IS_VERSION_OF);
      CVTerm_addResource(cv1, "http://www.ebi.ac.uk/interpro/#IPR002394");

      SBase_addCVTerm((SBase_t*)s, cv);
      SBase_addCVTerm((SBase_t*)s, cv2);
      SBase_addCVTerm((SBase_t*)s, cv1);

      writeSBML(d, argv[2]);
    }
  }

  SBMLDocument_free(d);
  return errors;
}


text:
CHANGELOG
=========

### 0.4.0 (2014-02-02)

  * Feature: Added ChildProcess to run async child processes within the event loop (@jmikola)
  * Feature: [EventLoop] Added `EventLoopInterface::nextTick()`, implemented in all event loops (@jmalloc)
  * Feature: [EventLoop] Added `EventLoopInterface::futureTick()`, implemented in all event loops (@jmalloc)
  * Feature: [EventLoop] Added `ExtEventLoop` implementation using pecl/event (@jmalloc)
  * BC break: [HttpClient] Drop unused `Response::getBody()`
  * BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks
  * BC break: Remove `$loop` argument from `HttpClient`: `Client`, `Request`, `Response`
  * BC break: Update to React/Promise 2.0
  * BC break: Update to Evenement 2.0
  * BC break: [EventLoop] New method: `EventLoopInterface::nextTick()`
  * BC break: [EventLoop] New method: `EventLoopInterface::futureTick()`
  * Bug fix: [Dns] Properly resolve CNAME aliases
  * Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0

### 0.3.3 (2013-07-08)

  * Bug fix: [EventLoop] No error on removing non-existent streams (@clue)
  * Bug fix: [EventLoop] Do not silently remove feof listeners in `LibEvLoop`
  * Bug fix: [Stream] Correctly detect closed connections

### 0.3.2 (2013-05-10)

  * Feature: [Dns] Support default port for IPv6 addresses (@clue)
  * Bug fix: [Stream] Make sure CompositeStream is closed properly

### 0.3.1 (2013-04-21)

  * Feature: [Socket] Support binding to IPv6 addresses (@clue)
  * Feature: [SocketClient] Support connecting to IPv6 addresses (@clue)
  * Bug fix: [Stream] Allow any `ReadableStreamInterface` on `BufferedSink::createPromise()`
  * Bug fix: [HttpClient] Correct requirement for socket-client

### 0.3.0 (2013-04-14)

  * BC break: [EventLoop] New timers API (@nrk)
  * BC break: [EventLoop] Remove check on return value from stream callbacks (@nrk)
  * BC break: [HttpClient] Socket connection handling moved to new SocketClient component
  * Feature: [SocketClient] New SocketClient component extracted from HttpClient (@clue)
  * Feature: [Stream] Factory method for BufferedSink

### 0.2.7 (2013-01-05)

  * Bug fix: [EventLoop] Fix libevent timers with PHP 5.3
  * Bug fix: [EventLoop] Fix libevent timer cancellation (@nrk)

### 0.2.6 (2012-12-26)

  * Feature: [Cache] New cache component, used by DNS
  * Bug fix: [Http] Emit end event when Response closes (@beaucollins)
  * Bug fix: [EventLoop] Plug memory issue in libevent timers (@cameronjacobson)
  * Bug fix: [EventLoop] Correctly pause LibEvLoop on stop()

### 0.2.5 (2012-11-26)

  * Feature: [Stream] Make BufferedSink trigger progress events on the promise (@jsor)
  * Feature: [HttpClient] Use a promise-based API internally
  * Bug fix: [HttpClient] Use DNS resolver correctly

### 0.2.4 (2012-11-18)

  * Feature: [Stream] Added ThroughStream, CompositeStream, ReadableStream and WritableStream
  * Feature: [Stream] Added BufferedSink
  * Feature: [Dns] Change to promise-based API (@jsor)

### 0.2.3 (2012-11-14)

  * Feature: LibEvLoop, integration of `php-libev`
  * Bug fix: Forward drain events from HTTP response (@cs278)
  * Dependency: Updated guzzle deps to `3.0.*`

### 0.2.2 (2012-10-28)

  * Major: Dropped Espresso as a core component now available as `react/espresso` only
  * Feature: DNS executor timeout handling (@arnaud-lb)
  * Feature: DNS retry executor (@arnaud-lb)
  * Feature: HTTP client (@arnaud-lb)

### 0.2.1 (2012-10-14)

  * Feature: Support HTTP 1.1 continue
  * Bug fix: Check for EOF in `Buffer::write()`
  * Bug fix: Make `Espresso\Stack` work with invokables (such as `Espresso\Application`)
  * Minor adjustments to DNS parser

### 0.2.0 (2012-09-10)

  * Feature: DNS resolver

### 0.1.1 (2012-07-12)

  * Bug fix: Testing and functional against PHP >= 5.3.3 and <= 5.3.8

### 0.1.0 (2012-07-11)

  * First tagged release


text:
package exampleutil

import (
	"go.uber.org/yarpc/api/transport"
	"go.uber.org/yarpc/encoding/protobuf"
	"go.uber.org/yarpc/internal/examples/protobuf/examplepb"
	"go.uber.org/yarpc/internal/grpcctx"
	"go.uber.org/yarpc/internal/testutils"
	"go.uber.org/zap"
)

// Clients holds all clients.
type Clients struct {
	KeyValueYARPCClient     examplepb.KeyValueYARPCClient
	FooYARPCClient          examplepb.FooYARPCClient
	KeyValueYARPCJSONClient examplepb.KeyValueYARPCClient
	FooYARPCJSONClient      examplepb.FooYARPCClient
	KeyValueGRPCClient      examplepb.KeyValueClient
	FooGRPCClient           examplepb.FooClient
	ContextWrapper          *grpcctx.ContextWrapper
}

// WithClients calls f on the Clients.
func WithClients(
	transportType testutils.TransportType,
	keyValueYARPCServer examplepb.KeyValueYARPCServer,
	fooYARPCServer examplepb.FooYARPCServer,
	logger *zap.Logger,
	f func(*Clients) error,
) error {
	var procedures []transport.Procedure
	if keyValueYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildKeyValueYARPCProcedures(keyValueYARPCServer)...)
	}
	if fooYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildFooYARPCProcedures(fooYARPCServer)...)
	}
	return testutils.WithClientInfo(
		"example",
		procedures,
		transportType,
		logger,
		func(clientInfo *testutils.ClientInfo) error {
			return f(
				&Clients{
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig),
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewKeyValueClient(clientInfo.GRPCClientConn),
					examplepb.NewFooClient(clientInfo.GRPCClientConn),
					clientInfo.ContextWrapper,
				},
			)
		},
	)
}


text:
using System;
using System.Collections.Generic;
using System.Web;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Settings;

namespace Vandelay.Industries.Test.Stubs {
    public class StubWorkContextAccessor : IWorkContextAccessor {
        private readonly WorkContext _workContext;

        public StubWorkContextAccessor(string baseUrl) {
            _workContext = new WorkContextImpl(baseUrl);
        }

        public class WorkContextImpl : WorkContext {
            private readonly Dictionary<string, object> _contextDictonary;

            public delegate void MyInitMethod(WorkContextImpl workContextImpl);

            public WorkContextImpl(string baseUrl) {
                _contextDictonary = new Dictionary<string, object>();
                var ci = new ContentItem();
                ci.Weld(new StubSite(baseUrl));
                CurrentSite = ci.As<ISite>();
            }

            public class StubSite : ContentPart, ISite {
                private string _baseUrl;

                public StubSite(string baseUrl) {
                    _baseUrl = baseUrl;
                }

                public string PageTitleSeparator {
                    get { throw new NotImplementedException(); }
                }

                public string SiteName {
                    get { throw new NotImplementedException(); }
                }

                public string SiteSalt {
                    get { throw new NotImplementedException(); }
                }

                public string SuperUser {
                    get { throw new NotImplementedException(); }
                }

                public string HomePage {
                    get { throw new NotImplementedException(); }
                    set { throw new NotImplementedException(); }
                }

                public string SiteCulture {
                    get { throw new NotImplementedException(); }
                    set { throw new NotImplementedException(); }
                }

                public ResourceDebugMode ResourceDebugMode {
                    get { throw new NotImplementedException(); }
                    set { throw new NotImplementedException(); }
                }

                public int PageSize{
                    get { throw new NotImplementedException(); }
                    set { throw new NotImplementedException(); }
                }

                public string BaseUrl { get { return _baseUrl; } }

                public string SiteTimeZone { get; set; }
            }

            public override T Resolve<T>() {
                throw new NotImplementedException();
            }

            public override bool TryResolve<T>(out T service) {
                throw new NotImplementedException();
            }

            public override T GetState<T>(string name) {
                return (T) _contextDictonary[name];
            }

            public override void SetState<T>(string name, T value) {
                _contextDictonary[name] = value;
            }
        }

        public WorkContext GetContext(HttpContextBase httpContext) {
            return _workContext;
        }

        public IWorkContextScope CreateWorkContextScope(HttpContextBase httpContext) {
            throw new NotSupportedException();
        }

        public WorkContext GetContext() {
            return _workContext;
        }

        public IWorkContextScope CreateWorkContextScope() {
            throw new NotSupportedException();
        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal class WithLambdaParametersBinder : LocalScopeBinder
    {
        protected readonly LambdaSymbol lambdaSymbol;
        protected readonly MultiDictionary<string, ParameterSymbol> parameterMap;
        private SmallDictionary<string, ParameterSymbol> _definitionMap;

        public WithLambdaParametersBinder(LambdaSymbol lambdaSymbol, Binder enclosing)
            : base(enclosing)
        {
            this.lambdaSymbol = lambdaSymbol;
            this.parameterMap = new MultiDictionary<string, ParameterSymbol>();

            var parameters = lambdaSymbol.Parameters;
            if (!parameters.IsDefaultOrEmpty)
            {
                RecordDefinitions(parameters);
                foreach (var parameter in lambdaSymbol.Parameters)
                {
                    this.parameterMap.Add(parameter.Name, parameter);
                }
            }
        }

        private void RecordDefinitions(ImmutableArray<ParameterSymbol> definitions)
        {
            var declarationMap = _definitionMap ?? (_definitionMap = new SmallDictionary<string, ParameterSymbol>());
            foreach (var s in definitions)
            {
                if (!declarationMap.ContainsKey(s.Name))
                {
                    declarationMap.Add(s.Name, s);
                }
            }
        }

        protected override TypeSymbol GetCurrentReturnType(out RefKind refKind)
        {
            refKind = lambdaSymbol.RefKind;
            return lambdaSymbol.ReturnType.TypeSymbol;
        }

        internal override Symbol ContainingMemberOrLambda
        {
            get
            {
                return this.lambdaSymbol;
            }
        }

        internal override bool IsNestedFunctionBinder => true;

        internal override bool IsDirectlyInIterator
        {
            get
            {
                return false;
            }
        }

        // NOTE: Specifically not overriding IsIndirectlyInIterator.

        internal override TypeSymbol GetIteratorElementType(YieldStatementSyntax node, DiagnosticBag diagnostics)
        {
            if (node != null)
            {
                diagnostics.Add(ErrorCode.ERR_YieldInAnonMeth, node.YieldKeyword.GetLocation());
            }
            return CreateErrorType();
        }

        internal override void LookupSymbolsInSingleBinder(
            LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(result.IsClear);

            if ((options & LookupOptions.NamespaceAliasesOnly) != 0)
            {
                return;
            }

            foreach (var parameterSymbol in parameterMap[name])
            {
                result.MergeEqual(originalBinder.CheckViability(parameterSymbol, arity, options, null, diagnose, ref useSiteDiagnostics));
            }
        }

        protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
        {
            if (options.CanConsiderMembers())
            {
                foreach (var parameter in lambdaSymbol.Parameters)
                {
                    if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null))
                    {
                        result.AddSymbol(parameter, parameter.Name, 0);
                    }
                }
            }
        }

        private static bool ReportConflictWithParameter(ParameterSymbol parameter, Symbol newSymbol, string name, Location newLocation, DiagnosticBag diagnostics)
        {
            var oldLocation = parameter.Locations[0];
            if (oldLocation == newLocation)
            {
                // a query variable and its corresponding lambda parameter, for example
                return false;
            }

            // Quirk of the way we represent lambda parameters.
            SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind;

            switch (newSymbolKind)
            {
                case SymbolKind.ErrorType:
                    return true;

                case SymbolKind.Parameter:
                case SymbolKind.Local:
                    // Error: A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                    diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name);
                    return true;

                case SymbolKind.Method:
                    // Local function declaration name conflicts are not reported, for backwards compatibility.
                    return false;

                case SymbolKind.TypeParameter:
                    // Type parameter declaration name conflicts are not reported, for backwards compatibility.
                    return false;

                case SymbolKind.RangeVariable:
                    // The range variable '{0}' conflicts with a previous declaration of '{0}'
                    diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name);
                    return true;
            }

            Debug.Assert(false, "what else could be defined in a lambda?");
            return false;
        }

        internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, DiagnosticBag diagnostics)
        {
            ParameterSymbol existingDeclaration;
            var map = _definitionMap;
            if (map != null && map.TryGetValue(name, out existingDeclaration))
            {
                return ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics);
            }

            return false;
        }

        internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
        {
            throw ExceptionUtilities.Unreachable;
        }

        internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
        {
            throw ExceptionUtilities.Unreachable;
        }

        internal override uint LocalScopeDepth => Binder.TopLevelScope;
    }
}


text:
import datetime
import json
import os
import pandas
import subprocess
import sys
import time
import traceback

from svviz import demo
from svviz import testIssues
from svviz import rendertest
from svviz import testDemos
from svviz import testCounts

# USAGE = """
# python runTests.py run|reset [hg19.ref.fa]

# run         - run all svviz tests
# reset       - removes then regenerates all values stored for each test;
#               use only after verifying that svviz behavior has changed
#               and that the new behavior is correct
# hg19.ref.fa - path to reference genome; must be defined here or using
#               the environmental variable SVVIZ_HG19_FASTA
# """

# reset ...

def reset():
    print("resetting test values...")

    previousSummaryPath = "countsTest.previousSummary.txt"
    os.remove(previousSummaryPath)

    raise Exception("not yet implemented: reset for demos and for render test")

# run ...

def _runTest(fn, description):
    print("\n\n -- running {} --\n\n".format(description))
    try:
        t0 = time.time()
        result = fn()
        t1 = time.time()
        result = [result[0], result[1], t1-t0]
    except Exception as e:
        print(" ** error running {}: {} **".format(description, e))
        print(traceback.print_exc())
        result = [False, str(e), -1]

    return result

def getHG19Ref(path=None):
    if path is not None:
        os.environ["SVVIZ_HG19_FASTA"] = path
        return path

    path = os.environ.get("SVVIZ_HG19_FASTA", None)
    assert os.path.exists(path), "Can't find hg19 reference fasta at path '{}'".format(path)

    return path

def getCountsData():
    path = "svviz-examples/countsTest"
    if not os.path.exists(path):
        result = demo.downloadDemo("countsTest")
        if not result:
            raise Exception("Couldn't download the countsTest data.")

def runTestCounts():
    getCountsData()

    genome = getHG19Ref()
    vcfs = ["svviz-examples/countsTest/na12878_test_deletions.vcf"]
    bams = ["svviz-examples/countsTest/reads.sorted.bam"]
    previousSummaryPath = "countsTest.previousSummary.txt"

    return testCounts.run(genome, vcfs, bams, previousSummaryPath)

def runTestIssues():
    genome = getHG19Ref()

    return testIssues.run(genome)

def saveTimingInfo(summary):
    timingsPath = "test_timings.csv"
    git_version = subprocess.check_output(["git", "describe"]).strip()

    new_row = summary[["timing"]].T
    new_row["date"] = [datetime.datetime.now()]
    new_row["version"] = git_version

    if os.path.exists(timingsPath):
        timings = pandas.read_csv(timingsPath, index_col=0)
        timings = pandas.concat([timings, new_row])
    else:
        timings = new_row

    timings.to_csv(timingsPath)

    print(timings)

def run(which):
    print("running all tests...")
    summary = pandas.DataFrame(columns=["pass", "info", "timing"])

    # Test chromosome ends
    if len(which)==0 or "chrom_ends" in which:
        summary.loc["chrom_ends"] = _runTest(runTestIssues, "issues")

    # Run the demos
    if len(which)==0 or "demos" in which:
        summary.loc["demos"] = _runTest(testDemos.run, "demos")

    # Run regression testing on ref/alt/amb counts
    if len(which)==0 or "counts" in which:
        summary.loc["counts"] = _runTest(runTestCounts, "counts")

    # Run the render regression tests
    if len(which)==0 or "rendering" in which:
        summary.loc["rendering"] = _runTest(rendertest.run, "rendering")

    summary["timing"] = summary["timing"].apply(lambda x: "{}".format(datetime.timedelta(seconds=int(x))))
    print(summary)

    saveTimingInfo(summary)

def main():
    # don't ask me why I rolled my own regression testing code instead of using one of the
    # gazillion existing frameworks...

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--reference", help="path for hg19 reference fasta; must be defined here or "
        "using the environmental variable SVVIZ_HG19_FASTA")

    parser.add_argument("mode", help="run|reset")
    parser.add_argument("which", nargs="*", help="which analyses to run (default all)")

    args = parser.parse_args()

    print(args.which)

    # if len(sys.argv) < 2:
    #     print USAGE
    #     return

    if args.mode == "run":
        if getHG19Ref(args.reference) is None:
            parser.print_help()
            print("ERROR: Must provide path for hg19 reference fasta")
            sys.exit(1)
        run(args.which)
    elif args.mode == "reset":
        reset()
    else:
        parser.print_help()

if __name__ == '__main__':
    main()


text:
package il.ac.tau.jsfuzzer.JST.Enums;

public enum JSTNodes
{
	JSTNode,
	AbsStatement,
	AbsExpression,
	ArrayExp,
	Call,
	FunctionExp,
	Identifier,
	Literal,
	LiteralNumber,
	LiteralString,
	MemberExp,
	ObjectExp,
	OperationExp,
	This,
	AbsLoop,
	AbsWhileLoop,
	DoWhile,
	While,
	For,
	Assignment,
	Break,
	CompoundAssignment,
	Continue,
	ForEach,
	FunctionDef,
	If,
	OutputStatement,
	Return,
	StatementsBlock,
	Switch,
	VarDecleration,
	VarDeclerator,
	Case,
	CaseBlock,
	Comment,
	Default,
	Program,
	RawCode,
	VarDecleratoryes;
}


text:
package org.apache.sqoop.connector.mainframe;

import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.sqoop.connector.mainframe.configuration.FromJobConfiguration;
import org.apache.sqoop.connector.mainframe.configuration.LinkConfiguration;
import org.apache.sqoop.job.etl.Initializer;
import org.apache.sqoop.job.etl.InitializerContext;
import org.apache.sqoop.schema.Schema;

public class MainframeDatasetFromInitializer extends Initializer<LinkConfiguration, FromJobConfiguration> {

  private static final Logger LOG =
    Logger.getLogger(MainframeDatasetFromInitializer.class);

  @Override
  public void initialize(InitializerContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig) {
  }

  @Override
  public Set<String> getJars(InitializerContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig) {
    Set<String> jars = super.getJars(context, linkConfig, fromJobConfig);
    return jars;
  }

  @Override
  public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig, FromJobConfiguration fromJobConfig) {
    return null;
  }

}


text:
<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('username')
            ->add('agreeTerms', CheckboxType::class, [
                'mapped' => false,
                'constraints' => [
                    new IsTrue([
                        'message' => 'You should agree to our terms.',
                    ]),
                ],
            ])
            ->add('plainPassword', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'mapped' => false,
                'attr' => ['autocomplete' => 'new-password'],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'Your password should be at least {{ limit }} characters',
                        // max length allowed by Symfony for security reasons
                        'max' => 4096,
                    ]),
                ],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/logger"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="Press the fab to scan a code\n"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:clickable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@android:drawable/ic_menu_camera" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
#ifndef GRPC_INTERNAL_CORE_STATISTICS_HASH_TABLE_H
#define GRPC_INTERNAL_CORE_STATISTICS_HASH_TABLE_H

#include <stddef.h>

#include <grpc/support/port_platform.h>

/* A chain based hash table with fixed number of buckets.
   Your probably shouldn't use this code directly. It is implemented for the
   use case in census trace store and stats store, where number of entries in
   the table is in the scale of upto several thousands, entries are added and
   removed from the table very frequently (~100k/s), the frequency of find()
   operations is roughly several times of the frequency of insert() and erase()
   Comparing to find(), the insert(), erase() and get_all_entries() operations
   are much less freqent (<1/s).

   Per bucket memory overhead is about (8 + sizeof(intptr_t) bytes.
   Per entry memory overhead is about (8 + 2 * sizeof(intptr_t) bytes.

   All functions are not thread-safe. Synchronization will be provided in the
   upper layer (in trace store and stats store).
*/

/* Opaque hash table struct */
typedef struct unresizable_hash_table census_ht;

/* Currently, the hash_table can take two types of keys. (uint64 for trace
   store and const char* for stats store). */
typedef union {
  gpr_uint64 val;
  void* ptr;
} census_ht_key;

typedef enum census_ht_key_type {
  CENSUS_HT_UINT64 = 0,
  CENSUS_HT_POINTER = 1
} census_ht_key_type;

typedef struct census_ht_option {
  /* Type of hash key */
  census_ht_key_type key_type;
  /* Desired number of buckets, preferably a prime number */
  gpr_int32 num_buckets;
  /* Fucntion to calculate uint64 hash value of the key. Only takes effect if
     key_type is POINTER. */
  gpr_uint64 (*hash)(const void*);
  /* Function to compare two keys, returns 0 iff equal. Only takes effect if
     key_type is POINTER */
  int (*compare_keys)(const void* k1, const void* k2);
  /* Value deleter. NULL if no specialized delete function is needed. */
  void (*delete_data)(void*);
  /* Key deleter. NULL if table does not own the key. (e.g. key is part of the
     value or key is not owned by the table.) */
  void (*delete_key)(void*);
} census_ht_option;

/* Creates a hashtable with fixed number of buckets according to the settings
   specified in 'options' arg. Function pointers "hash" and "compare_keys" must
   be provided if key_type is POINTER. Asserts if fail to create. */
census_ht* census_ht_create(const census_ht_option* options);

/* Deletes hash table instance. Frees all dynamic memory owned by ht.*/
void census_ht_destroy(census_ht* ht);

/* Inserts the input key-val pair into hash_table. If an entry with the same key
   exists in the table, the corresponding value will be overwritten by the input
   val. */
void census_ht_insert(census_ht* ht, census_ht_key key, void* val);

/* Returns pointer to data, returns NULL if not found. */
void* census_ht_find(const census_ht* ht, census_ht_key key);

/* Erase hash table entry with input key. Noop if key is not found. */
void census_ht_erase(census_ht* ht, census_ht_key key);

typedef struct census_ht_kv {
  census_ht_key k;
  void* v;
} census_ht_kv;

/* Returns an array of pointers to all values in the hash table. Order of the
   elements can be arbitrary. Sets 'num' to the size of returned array. Caller
   owns returned array. */
census_ht_kv* census_ht_get_all_elements(const census_ht* ht, size_t* num);

/* Returns number of elements kept. */
size_t census_ht_get_size(const census_ht* ht);

/* Functor applied on each key-value pair while iterating through entries in the
   table. The functor should not mutate data. */
typedef void (*census_ht_itr_cb)(census_ht_key key, const void* val_ptr,
                                 void* state);

/* Iterates through all key-value pairs in the hash_table. The callback function
   should not invalidate data entries. */
gpr_uint64 census_ht_for_all(const census_ht* ht, census_ht_itr_cb);

#endif  /* GRPC_INTERNAL_CORE_STATISTICS_HASH_TABLE_H */


text:
class UsersController < ApplicationController

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to root_url, notice: "Thank you for signing up!"
    else
      render "new"
    end
  end

  private

  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
  end
end


text:
package easycriteria;

import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;

@Entity
@Table(name = "homeanimal_tbl")
public class HomeAnimal extends Animal {

	private String owner;

	@Embedded
	private PetAddress petAddress;

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}

	public PetAddress getPetAddress() {
		return petAddress;
	}

	public void setPetAddress(PetAddress petAddress) {
		this.petAddress = petAddress;
	}

	@Override
	public String toString() {
		return "HomeAnimal [owner=" + owner + ", petAddress=" + petAddress + "]";
	}
}


text:
<?php

/**
 *  @see OffAmazonPaymentsService_Model
 */
require_once 'OffAmazonPaymentsService/Model.php';

/**
 * OffAmazonPaymentsService_Model_ErrorResponse
 *
 * Properties:
 *

 *
 *
Error: OffAmazonPaymentsService_Model_Error

 *
RequestId: string

 *
 *

 */
class OffAmazonPaymentsService_Model_ErrorResponse extends OffAmazonPaymentsService_Model
{

    /**
     * Construct new OffAmazonPaymentsService_Model_ErrorResponse
     *
     * @param mixed $data DOMElement or Associative Array to construct from.
     *
     * Valid properties:
     *

     *
     *
Error: OffAmazonPaymentsService_Model_Error

     *
RequestId: string

     *
     *

     */
    public function __construct($data = null)
    {
        $this->_fields = array(
            'Error' => array(
                'FieldValue' => array(),
                'FieldType' => array(
                    'OffAmazonPaymentsService_Model_Error'
                )
            ),
            'RequestId' => array(
                'FieldValue' => null,
                'FieldType' => 'string'
            )
        );
        parent::__construct($data);
    }

    /**
     * Construct OffAmazonPaymentsService_Model_ErrorResponse from XML string
     *
     * @param string $xml XML string to construct from
     * @return OffAmazonPaymentsService_Model_ErrorResponse
     */
    public static function fromXML($xml)
    {
        $dom = new DOMDocument();
        $dom->loadXML($xml);
        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace('a', 'http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01');
        $response = $xpath->query('//a:ErrorResponse');
        if ($response->length == 1) {
            return new OffAmazonPaymentsService_Model_ErrorResponse(($response->item(0)));
        } else {
            throw new Exception("Unable to construct OffAmazonPaymentsService_Model_ErrorResponse from provided XML.
                                  Make sure that ErrorResponse is a root element");
        }

    }

    /**
     * Gets the value of the Error.
     *
     * @return array of Error Error
     */
    public function getError()
    {
        return $this->_fields['Error']['FieldValue'];
    }

    /**
     * Sets the value of the Error.
     *
     * @param mixed Error or an array of Error Error
     * @return this instance
     */
    public function setError($error)
    {
        if (!$this->_isNumericArray($error)) {
            $error = array(
                $error
            );
        }
        $this->_fields['Error']['FieldValue'] = $error;
        return $this;
    }

    /**
     * Sets single or multiple values of Error list via variable number of arguments.
     * For example, to set the list with two elements, simply pass two values as arguments to this function
     * withError($error1, $error2)
     *
     * @param Error  $errorArgs one or more Error
     * @return OffAmazonPaymentsService_Model_ErrorResponse  instance
     */
    public function withError($errorArgs)
    {
        foreach (func_get_args() as $error) {
            $this->_fields['Error']['FieldValue'][] = $error;
        }
        return $this;
    }

    /**
     * Checks if Error list is non-empty
     *
     * @return bool true if Error list is non-empty
     */
    public function isSetError()
    {
        return count($this->_fields['Error']['FieldValue']) > 0;
    }

    /**
     * Gets the value of the RequestId property.
     *
     * @return string RequestId
     */
    public function getRequestId()
    {
        return $this->_fields['RequestId']['FieldValue'];
    }

    /**
     * Sets the value of the RequestId property.
     *
     * @param string RequestId
     * @return this instance
     */
    public function setRequestId($value)
    {
        $this->_fields['RequestId']['FieldValue'] = $value;
        return $this;
    }

    /**
     * Sets the value of the RequestId and returns this instance
     *
     * @param string $value RequestId
     * @return OffAmazonPaymentsService_Model_ErrorResponse instance
     */
    public function withRequestId($value)
    {
        $this->setRequestId($value);
        return $this;
    }

    /**
     * Checks if RequestId is set
     *
     * @return bool true if RequestId  is set
     */
    public function isSetRequestId()
    {
        return !is_null($this->_fields['RequestId']['FieldValue']);
    }

    /**
     * XML Representation for this object
     *
     * @return string XML for this object
     */
    public function toXML()
    {
        $xml = "";
        $xml .= "<ErrorResponse xmlns=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\">";
        $xml .= $this->_toXMLFragment();
        $xml .= "</ErrorResponse>";
        return $xml;
    }

    private $_responseHeaderMetadata = null;

    public function getResponseHeaderMetadata()
    {
        return $this->_responseHeaderMetadata;
    }

    public function setResponseHeaderMetadata($responseHeaderMetadata)
    {
        return $this->_responseHeaderMetadata = $responseHeaderMetadata;
    }
}


text:
"use strict";
let assert = require("assert");
let $http = require("http-client-promise");
let users = require("../../mongodb/users");
let $request = require("request-promise");
let request = require("request");

describe("session API", function () {
  it("should login a user", function () {
    let options = {
      hostname: "localhost",
      port: global.port,
      method: "POST",
      path: "/api/login/",
      headers: {
        "Content-Type": "application/json"
      }
    };

    let obj = {
      username: global.username,
      password: global.password
    };

    return $http.request(options, JSON.stringify(obj)).then(function (res) {
      return res.getData().then(function (body) {
        assert.equal(res.statusCode, 200, body);
        let obj = JSON.parse(body);
        assert.equal(obj.username, global.username);
        assert(obj.success, "login success");
      });
    });
  });

  it("should get the user profile", function () {
    let options = {
      hostname: "localhost",
      port: global.port,
      method: "GET",
      path: "/api/profile/",
      headers: {
        Cookie: global.cookie
      }
    };

    return $http.request(options).then(function (res) {
      return res.getData().then(function (body) {
        assert.equal(res.statusCode, 200, body);
        let obj = JSON.parse(body);
        assert.equal(obj.username, global.username);
        assert.equal(obj.email, global.email);
        assert.equal(obj.emailVerify, false);
        assert(obj.joined, "joined");
      });
    });
  });

  it("should update the user password", function () {
    let options = {
      uri: "http://localhost:3000/api/profile/",
      body: {
        email: global.email,
        password: global.password + "2"
      },
      headers: {
        Cookie: global.cookie
      },
      json: true
    };
    return $request.post(options).then(function (body) {
      assert(!body.checkEmail, "!checkEmail");
    });
  });

  it("should update the user email", function () {
    let options = {
      uri: "http://localhost:3000/api/profile/",
      body: {
        email: "apiuser@me2.com",
        password: global.password
      },
      headers: {
        Cookie: global.cookie
      },
      json: true
    };
    return $request.post(options).then(function (body) {
      assert(body.checkEmail, "checkEmail");
    });
  });

});


text:
package com.liangmayong.base.widget.basic;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.liangmayong.base.support.utils.DimenUtils;
import com.liangmayong.base.widget.basic.interfaces.BasicViewDrawer;
import com.liangmayong.base.widget.basic.interfaces.BasicViewHandler;
import com.liangmayong.base.widget.basic.interfaces.BasicViewInterface;
import com.liangmayong.base.widget.iconfont.FontView;

/**
 * Created by LiangMaYong on 2016/9/27.
 */
public class BasicFontView extends FontView implements BasicViewInterface {

    private BasicViewDrawer basicViewDrawer = null;
    private BasicViewHandler basicViewHandler = null;

    public BasicFontView(Context context) {
        this(context, null);
    }

    public BasicFontView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttributeSet(context, attrs);
    }

    public BasicFontView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttributeSet(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public BasicFontView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttributeSet(context, attrs);
    }

    protected void initAttributeSet(final Context context, final AttributeSet attrs) {
        basicViewDrawer = new BasicViewDrawer(context, attrs, SHAPE_TYPE_TRANSPARENT, DimenUtils.dip2px(context, 2), DimenUtils.dip2px(context, 1.4f));
        basicViewHandler = new BasicViewHandler(context, attrs);
        this.setWillNotDraw(false);
        this.setDrawingCacheEnabled(true);
        this.eraseOriginalBackgroundColor();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        basicViewDrawer.setWidth(w);
        basicViewDrawer.setHeight(h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        basicViewDrawer.onBackgroundDraw(canvas, basicViewHandler.getUnpressedPaint(), basicViewHandler.isUnpressedTransparent());
        basicViewDrawer.onBackgroundDraw(canvas, basicViewHandler.getUnpressedCoverPaint(), false);
        basicViewDrawer.onPressedDraw(canvas, basicViewHandler.getPressedPaint());
        super.onDraw(canvas);
    }

    @Override
    public void setBackgroundColor(int color) {
        eraseOriginalBackgroundColor();
    }

    protected void eraseOriginalBackgroundColor() {
        super.setBackgroundColor(Color.TRANSPARENT);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isClickable()) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    basicViewHandler.setClickable(true);
                    invalidate();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    basicViewHandler.setClickable(false);
                    invalidate();
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public int getPressedColor() {
        return basicViewHandler.getPressedColor();
    }

    @Override
    public void setPressedColor(int pressedColor) {
        basicViewHandler.setPressedColor(pressedColor);
        invalidate();
    }

    @Override
    public int getUnpressedColor() {
        return basicViewHandler.getUnpressedColor();
    }

    @Override
    public void setUnpressedColor(int color) {
        basicViewHandler.setUnpressedColor(color);
        invalidate();
    }

    @Override
    public int getUnpressedCoverColor() {
        return basicViewHandler.getUnpressedCoverColor();
    }

    @Override
    public void setUnpressedCoverColor(int color) {
        basicViewHandler.setUnpressedCoverColor(color);
        invalidate();
    }

    @Override
    public int getShapeType() {
        return basicViewDrawer.getShapeType();
    }

    @Override
    public void setShapeType(int shapeType) {
        basicViewDrawer.setShapeType(shapeType);
        invalidate();
    }

    @Override
    public int getRadius() {
        return basicViewDrawer.getRadius();
    }

    @Override
    public int getStrokeWidth() {
        return basicViewDrawer.getStrokeWidth();
    }

    @Override
    public void setRadius(int radius) {
        basicViewDrawer.setRadius(radius);
        invalidate();
    }

    @Override
    public void setStrokeWidth(int mStrokeWidth) {
        basicViewDrawer.setStrokeWidth(mStrokeWidth);
        invalidate();
    }
}


text:
"use strict";

export class V1Error {
    public faultCode = "AMFPHP_RUNTIME_ERROR";
    public faultString: string;
    public faultDetail = "";

    constructor(message: string) {
        this.faultString = message;
    }
}