text:
[instagram-private-api](../../README.md) / [responses](../../modules/responses.md) / UserFeedResponseItemsItem

# Interface: UserFeedResponseItemsItem

[responses](../../modules/responses.md).UserFeedResponseItemsItem

## Table of contents

### Properties

- [can\_see\_insights\_as\_brand](UserFeedResponseItemsItem.md#can_see_insights_as_brand)
- [can\_view\_more\_preview\_comments](UserFeedResponseItemsItem.md#can_view_more_preview_comments)
- [can\_viewer\_reshare](UserFeedResponseItemsItem.md#can_viewer_reshare)
- [can\_viewer\_save](UserFeedResponseItemsItem.md#can_viewer_save)
- [caption](UserFeedResponseItemsItem.md#caption)
- [caption\_is\_edited](UserFeedResponseItemsItem.md#caption_is_edited)
- [carousel\_media](UserFeedResponseItemsItem.md#carousel_media)
- [carousel\_media\_count](UserFeedResponseItemsItem.md#carousel_media_count)
- [client\_cache\_key](UserFeedResponseItemsItem.md#client_cache_key)
- [code](UserFeedResponseItemsItem.md#code)
- [comment\_count](UserFeedResponseItemsItem.md#comment_count)
- [comment\_likes\_enabled](UserFeedResponseItemsItem.md#comment_likes_enabled)
- [comment\_threading\_enabled](UserFeedResponseItemsItem.md#comment_threading_enabled)
- [device\_timestamp](UserFeedResponseItemsItem.md#device_timestamp)
- [direct\_reply\_to\_author\_enabled](UserFeedResponseItemsItem.md#direct_reply_to_author_enabled)
- [facepile\_top\_likers](UserFeedResponseItemsItem.md#facepile_top_likers)
- [fb\_user\_tags](UserFeedResponseItemsItem.md#fb_user_tags)
- [filter\_type](UserFeedResponseItemsItem.md#filter_type)
- [has\_audio](UserFeedResponseItemsItem.md#has_audio)
- [has\_liked](UserFeedResponseItemsItem.md#has_liked)
- [has\_more\_comments](UserFeedResponseItemsItem.md#has_more_comments)
- [id](UserFeedResponseItemsItem.md#id)
- [image\_versions2](UserFeedResponseItemsItem.md#image_versions2)
- [inline\_composer\_display\_condition](UserFeedResponseItemsItem.md#inline_composer_display_condition)
- [inline\_composer\_imp\_trigger\_time](UserFeedResponseItemsItem.md#inline_composer_imp_trigger_time)
- [is\_dash\_eligible](UserFeedResponseItemsItem.md#is_dash_eligible)
- [like\_count](UserFeedResponseItemsItem.md#like_count)
- [max\_num\_visible\_preview\_comments](UserFeedResponseItemsItem.md#max_num_visible_preview_comments)
- [media\_type](UserFeedResponseItemsItem.md#media_type)
- [next\_max\_id](UserFeedResponseItemsItem.md#next_max_id)
- [number\_of\_qualities](UserFeedResponseItemsItem.md#number_of_qualities)
- [organic\_tracking\_token](UserFeedResponseItemsItem.md#organic_tracking_token)
- [original\_height](UserFeedResponseItemsItem.md#original_height)
- [original\_width](UserFeedResponseItemsItem.md#original_width)
- [photo\_of\_you](UserFeedResponseItemsItem.md#photo_of_you)
- [pk](UserFeedResponseItemsItem.md#pk)
- [preview\_comments](UserFeedResponseItemsItem.md#preview_comments)
- [taken\_at](UserFeedResponseItemsItem.md#taken_at)
- [top\_likers](UserFeedResponseItemsItem.md#top_likers)
- [user](UserFeedResponseItemsItem.md#user)
- [video\_codec](UserFeedResponseItemsItem.md#video_codec)
- [video\_dash\_manifest](UserFeedResponseItemsItem.md#video_dash_manifest)
- [video\_duration](UserFeedResponseItemsItem.md#video_duration)
- [video\_versions](UserFeedResponseItemsItem.md#video_versions)
- [view\_count](UserFeedResponseItemsItem.md#view_count)

## Properties

### can\_see\_insights\_as\_brand

• `Optional` **can\_see\_insights\_as\_brand**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:46](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L46)

___

### can\_view\_more\_preview\_comments

• **can\_view\_more\_preview\_comments**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:23](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L23)

___

### can\_viewer\_reshare

• **can\_viewer\_reshare**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:31](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L31)

___

### can\_viewer\_save

• **can\_viewer\_save**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:41](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L41)

___

### caption

• **caption**: [`UserFeedResponseCaption`](UserFeedResponseCaption.md)

#### Defined in

[src/responses/user.feed.response.ts:32](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L32)

___

### caption\_is\_edited

• **caption\_is\_edited**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:33](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L33)

___

### carousel\_media

• `Optional` **carousel\_media**: [`UserFeedResponseCarouselMediaItem`](UserFeedResponseCarouselMediaItem.md)[]

#### Defined in

[src/responses/user.feed.response.ts:45](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L45)

___

### carousel\_media\_count

• `Optional` **carousel\_media\_count**: `number`

#### Defined in

[src/responses/user.feed.response.ts:44](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L44)

___

### client\_cache\_key

• **client\_cache\_key**: `string`

#### Defined in

[src/responses/user.feed.response.ts:16](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L16)

___

### code

• **code**: `string`

#### Defined in

[src/responses/user.feed.response.ts:15](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L15)

___

### comment\_count

• **comment\_count**: `number`

#### Defined in

[src/responses/user.feed.response.ts:24](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L24)

___

### comment\_likes\_enabled

• **comment\_likes\_enabled**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:18](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L18)

___

### comment\_threading\_enabled

• **comment\_threading\_enabled**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:19](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L19)

___

### device\_timestamp

• **device\_timestamp**: `string` \| `number`

#### Defined in

[src/responses/user.feed.response.ts:13](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L13)

___

### direct\_reply\_to\_author\_enabled

• **direct\_reply\_to\_author\_enabled**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:38](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L38)

___

### facepile\_top\_likers

• `Optional` **facepile\_top\_likers**: [`UserFeedResponseFacepileTopLikersItem`](UserFeedResponseFacepileTopLikersItem.md)[]

#### Defined in

[src/responses/user.feed.response.ts:37](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L37)

___

### fb\_user\_tags

• `Optional` **fb\_user\_tags**: [`UserFeedResponseFb_user_tags`](UserFeedResponseFb_user_tags.md)

#### Defined in

[src/responses/user.feed.response.ts:40](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L40)

___

### filter\_type

• **filter\_type**: `number`

#### Defined in

[src/responses/user.feed.response.ts:17](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L17)

___

### has\_audio

• `Optional` **has\_audio**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:52](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L52)

___

### has\_liked

• **has\_liked**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:35](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L35)

___

### has\_more\_comments

• **has\_more\_comments**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:20](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L20)

___

### id

• **id**: `string`

#### Defined in

[src/responses/user.feed.response.ts:12](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L12)

___

### image\_versions2

• **image\_versions2**: [`UserFeedResponseImage_versions2`](UserFeedResponseImage_versions2.md)

#### Defined in

[src/responses/user.feed.response.ts:27](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L27)

___

### inline\_composer\_display\_condition

• **inline\_composer\_display\_condition**: `string`

#### Defined in

[src/responses/user.feed.response.ts:25](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L25)

___

### inline\_composer\_imp\_trigger\_time

• **inline\_composer\_imp\_trigger\_time**: `number`

#### Defined in

[src/responses/user.feed.response.ts:26](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L26)

___

### is\_dash\_eligible

• `Optional` **is\_dash\_eligible**: `number`

#### Defined in

[src/responses/user.feed.response.ts:47](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L47)

___

### like\_count

• **like\_count**: `number`

#### Defined in

[src/responses/user.feed.response.ts:34](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L34)

___

### max\_num\_visible\_preview\_comments

• **max\_num\_visible\_preview\_comments**: `number`

#### Defined in

[src/responses/user.feed.response.ts:21](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L21)

___

### media\_type

• **media\_type**: `number`

#### Defined in

[src/responses/user.feed.response.ts:14](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L14)

___

### next\_max\_id

• `Optional` **next\_max\_id**: `string`

#### Defined in

[src/responses/user.feed.response.ts:43](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L43)

___

### number\_of\_qualities

• `Optional` **number\_of\_qualities**: `number`

#### Defined in

[src/responses/user.feed.response.ts:50](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L50)

___

### organic\_tracking\_token

• **organic\_tracking\_token**: `string`

#### Defined in

[src/responses/user.feed.response.ts:42](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L42)

___

### original\_height

• **original\_height**: `number`

#### Defined in

[src/responses/user.feed.response.ts:29](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L29)

___

### original\_width

• **original\_width**: `number`

#### Defined in

[src/responses/user.feed.response.ts:28](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L28)

___

### photo\_of\_you

• **photo\_of\_you**: `boolean`

#### Defined in

[src/responses/user.feed.response.ts:39](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L39)

___

### pk

• **pk**: `string`

#### Defined in

[src/responses/user.feed.response.ts:11](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L11)

___

### preview\_comments

• **preview\_comments**: [`UserFeedResponsePreviewCommentsItem`](UserFeedResponsePreviewCommentsItem.md)[]

#### Defined in

[src/responses/user.feed.response.ts:22](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L22)

___

### taken\_at

• **taken\_at**: `number`

#### Defined in

[src/responses/user.feed.response.ts:10](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L10)

___

### top\_likers

• **top\_likers**: `string`[]

#### Defined in

[src/responses/user.feed.response.ts:36](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L36)

___

### user

• **user**: [`UserFeedResponseUser`](UserFeedResponseUser.md)

#### Defined in

[src/responses/user.feed.response.ts:30](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L30)

___

### video\_codec

• `Optional` **video\_codec**: `string`

#### Defined in

[src/responses/user.feed.response.ts:49](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L49)

___

### video\_dash\_manifest

• `Optional` **video\_dash\_manifest**: `string`

#### Defined in

[src/responses/user.feed.response.ts:48](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L48)

___

### video\_duration

• `Optional` **video\_duration**: `number`

#### Defined in

[src/responses/user.feed.response.ts:53](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L53)

___

### video\_versions

• `Optional` **video\_versions**: [`UserFeedResponseVideoVersionsItem`](UserFeedResponseVideoVersionsItem.md)[]

#### Defined in

[src/responses/user.feed.response.ts:51](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L51)

___

### view\_count

• `Optional` **view\_count**: `number`

#### Defined in

[src/responses/user.feed.response.ts:54](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/user.feed.response.ts#L54)


text:
@implementation Character

- (id)initWithCharacterDetailData:(NSDictionary *)data
{
    self = [super init];
    if (self)
    {
        _name = data[@"name"];
        _level = data[@"level"];
        _race = [WoWUtils raceFromRaceType:[data[@"race"] intValue]];
        _classType = [WoWUtils classFromCharacterType:[data[@"class"] intValue]];
        _achievementPoints = data[@"achievementPoints"];
        _realm = data[@"realm"];
        _thumbnail = data[@"thumbnail"];
        _battleGroup = data[@"battlegroup"];
        _averageItemLevelEquipped = data[@"items"][@"averageItemLevelEquipped"];
        _averageItemLevel = data[@"items"][@"averageItemLevel"];

        BOOL genderVal = [data[@"gender"] boolValue];
        if (genderVal) {
            _gender = @"Female";
        } else {
            _gender = @"Male";
        }

        // find selected spec
        _selectedSpec = [self selectedSpecFromTalents:data[@"talents"]];

        _neckItem = [Item initWithData:data[@"items"][@"neck"]];
        _wristItem = [Item initWithData:data[@"items"][@"wrist"]];
        _waistItem = [Item initWithData:data[@"items"][@"wrist"]];
        _handsItem = [Item initWithData:data[@"items"][@"hands"]];
        _shoulderItem = [Item initWithData:data[@"items"][@"shoulder"]];
        _chestItem = [Item initWithData:data[@"items"][@"chest"]];
        _fingerItem1 = [Item initWithData:data[@"items"][@"finger1"]];
        _fingerItem2 = [Item initWithData:data[@"items"][@"finger2"]];
        _shirtItem = [Item initWithData:data[@"items"][@"shirt"]];
        _tabardItem = [Item initWithData:data[@"items"][@"tabard"]];
        _headItem = [Item initWithData:data[@"items"][@"head"]];
        _backItem = [Item initWithData:data[@"items"][@"back"]];
        _legsItem = [Item initWithData:data[@"items"][@"legs"]];
        _feetItem = [Item initWithData:data[@"items"][@"feet"]];
        _mainHandItem = [Item initWithData:data[@"items"][@"mainHand"]];
        _offHandItem = [Item initWithData:data[@"items"][@"offHand"]];
        _trinketItem1 = [Item initWithData:data[@"items"][@"trinket1"]];
        _trinketItem2 = [Item initWithData:data[@"items"][@"trinket2"]];
        _rangedItem = [Item initWithData:data[@"items"][@"ranged"]];
        _title = [self selectedTitle:data[@"titles"]];
    }
    return self;
}

// Given an array of talents (which are NSDictionaries) return the one with a key
// selected value = true
-(NSString *)selectedSpecFromTalents:(NSArray *)talents
{
    __block NSString *selectedTalentName;
    [talents enumerateObjectsUsingBlock:^(NSDictionary *talentTree, NSUInteger idx, BOOL *stop) {
        if ([talentTree[@"selected"] boolValue]) {
            selectedTalentName = talentTree[@"name"];
            *stop = YES;
        }
    }];
    return selectedTalentName;
}

-(NSString *)selectedTitle:(NSArray *)titles
{
    __block NSString *selectedTitle;
    [titles enumerateObjectsUsingBlock:^(NSDictionary *title, NSUInteger idx, BOOL *stop) {
        if ([title[@"selected"] boolValue]) {
            selectedTitle = title[@"name"];
            *stop = YES;
        }
    }];
    return selectedTitle;
}

-(NSString *)profileImageUrl
{
    // only supporting US for now..
    NSString *baseUrl = @"http://us.battle.net/static-render/us/";
    NSString *profileMain = [_thumbnail stringByReplacingOccurrencesOfString:@"-avatar.jpg" withString:@"-profilemain.jpg"];
    NSString *profileImageUrl = [NSString stringWithFormat:@"%@%@",baseUrl,profileMain];
    return [profileImageUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

-(NSString *)profileBackgroundImageUrl
{
    return @"http://us.battle.net/wow/static/images/character/summary/backgrounds/race/1.jpg";

}

- (NSString *)thumbnailUrl
{
    NSString *baseUrl = @"http://us.battle.net/static-render/us/";
    NSString *url = [baseUrl stringByAppendingString:_thumbnail];
    return [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

// sort by level, then acheivement points
- (NSComparisonResult)compare:(Character *)other
{
    NSComparisonResult order;

    // first compare level in descending
    order = [other.level compare:self.level];

    // if same level sort by achievement points
    if (order == NSOrderedSame) {
        order = [other.achievementPoints compare:self.achievementPoints];
    }
    return order;
}

-(NSString *)description
{
    return [NSString stringWithFormat:@"%@ - %@ - %@ - %@", _name, _classType, _level, _achievementPoints];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package runner

import (
	"testing"

	"github.com/mgutz/dat/v1"
)

// These benchmarks compare the total cost of interpolating the SQL then
// executing the query on the same connection using a transaction.
// Both database/sql and jmoiron/sqlx can take advantage of a prepared
// statements.

func BenchmarkTransactedDat2(b *testing.B) {
	benchmarkTransactedDatN(b, 1, 2)
}

func BenchmarkTransactedSql2(b *testing.B) {
	benchmarkTransactedSqlN(b, 1, 2)
}

func BenchmarkTransactedDat4(b *testing.B) {
	benchmarkTransactedDatN(b, 1, 4)
}

func BenchmarkTransactedSql4(b *testing.B) {
	benchmarkTransactedSqlN(b, 1, 4)
}

func BenchmarkTransactedDat8(b *testing.B) {
	benchmarkTransactedDatN(b, 2, 4)
}

func BenchmarkTransactedSql8(b *testing.B) {
	benchmarkTransactedSqlN(b, 2, 4)
}

func BenchmarkTransactedDat64(b *testing.B) {
	benchmarkTransactedDatN(b, 16, 4)
}

func BenchmarkTransactedSql64(b *testing.B) {
	benchmarkTransactedSqlN(b, 16, 4)
}

func benchmarkTransactedDatN(b *testing.B, rows int, argc int) {
	benchReset()
	builder, err := benchInsertBuilder(rows, argc)
	if err != nil {
		b.Fatal(err)
	}
	sql, args := builder.ToSQL()

	tx, err := conn.Begin()
	if err != nil {
		b.Fatal(err)
	}
	defer tx.Commit()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		sql2, args2, err := dat.Interpolate(sql, args)
		if err != nil {
			b.Fatal(err)
		}
		_, err = tx.Exec(sql2, args2...)
		if err != nil {
			//fmt.Println(builder)
			b.Fatal(err)
		}
	}
}

func benchmarkTransactedSqlN(b *testing.B, rows int, argc int) {
	benchReset()
	builder, err := benchInsertBuilder(rows, argc)
	if err != nil {
		b.Fatal(err)
	}

	sql, args := builder.ToSQL()

	tx, err := db.Begin()
	if err != nil {
		panic(err)
	}
	defer tx.Commit()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := tx.Exec(sql, args...)
		if err != nil {
			b.Error(err.Error())
		}
	}
}

func benchmarkTransactedSqlxN(b *testing.B, rows int, argc int) {
	benchReset()
	builder, err := benchInsertBuilder(rows, argc)
	if err != nil {
		b.Fatal(err)
	}

	sql, args := builder.ToSQL()

	tx, err := conn.DB.Beginx()
	if err != nil {
		panic(err)
	}
	defer tx.Commit()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := tx.Exec(sql, args...)
		if err != nil {
			b.Error(err.Error())
		}
	}
}


text:
package com.vivint.ceph

import akka.actor.{ Actor, ActorContext, ActorLogging, ActorRef, Cancellable, FSM, Kill, Props, Stash }
import akka.pattern.pipe
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ Flow, Keep, Sink }
import java.util.UUID
import java.util.concurrent.TimeoutException
import lib.FutureHelpers.tSequence
import mesosphere.marathon.state.{ PersistentVolume, PersistentVolumeInfo, DiskSource }
import mesosphere.mesos.matcher._
import mesosphere.mesos.protos
import org.apache.mesos.Protos._
import scala.collection.immutable.Seq
import scala.concurrent.Future
import mesosphere.mesos.protos.Resource.DISK
import scaldi.Injector
import scaldi.Injectable._

class OfferOperations(implicit inj: Injector) {
  private val config = inject[AppConfiguration]
  import ProtoHelpers._
  /** Destroy the disks associated with this offer
    */
  def unreserveOffer(resources: Iterable[Resource]): Seq[Offer.Operation] = {
    val volumesToDestroy = resources.
      filter { r => r.hasDisk && r.getDisk.hasPersistence }

    val offersToRelease = resources.
      filter(_.hasReservation)

    Seq(
      newOfferOperation(newDestroyOperation(volumesToDestroy)),
      newOfferOperation(newUnreserveOperation(resources)))
  }

  def volId(reservationId: UUID, containerPath: String): String =
    reservationId + "#" + containerPath

  /** Adapated from Marathon code.
    * TODO - put appropriate copyright information
    */
  def createVolumes(
    frameworkId: FrameworkID,
    jobId: UUID,
    reservationId: UUID,
    localVolumes: Iterable[(DiskSource, PersistentVolume)]): Offer.Operation = {
    import scala.collection.JavaConverters._

    val volumes: Iterable[Resource] = localVolumes.map {
      case (source, vol) =>
        val disk = {
          val persistence = Resource.DiskInfo.Persistence.newBuilder().
            setId(volId(reservationId = reservationId, containerPath = vol.containerPath)).
            setPrincipal(config.principal)

          val volume = Volume.newBuilder.
            setContainerPath(vol.containerPath).
            setMode(vol.mode)

          val builder = Resource.DiskInfo.newBuilder.
            setPersistence(persistence).
            setVolume(volume)
          source.asMesos.foreach(builder.setSource)
          builder
        }

        val reservation = Resource.ReservationInfo.newBuilder.
          setLabels(newLabels(
            Constants.FrameworkIdLabel -> frameworkId.getValue,
            Constants.ReservationIdLabel -> reservationId.toString,
            Constants.JobIdLabel -> jobId.toString)).
          setPrincipal(config.principal)

        Resource.newBuilder.
          setName(DISK).
          setType(Value.Type.SCALAR).
          setScalar(newScalar(vol.persistent.size.toDouble)).
          setRole(config.role).
          setReservation(reservation).
          setDisk(disk).
          build()
    }

    val create = Offer.Operation.Create.newBuilder().
      addAllVolumes(volumes.asJava)

    newOfferOperation(create.build)
  }

  /** Adapated from Marathon code.
    * TODO - put appropriate copyright information */
  def reserve(frameworkId: FrameworkID, jobId: UUID, reservationId: UUID, resources: Iterable[Resource]):
      Offer.Operation = {
    import scala.collection.JavaConverters._
    val reservedResources = resources.map { resource =>

      val reservation = Resource.ReservationInfo.newBuilder().
        setLabels(newLabels(
            Constants.FrameworkIdLabel -> frameworkId.getValue,
            Constants.ReservationIdLabel -> reservationId.toString,
            Constants.JobIdLabel -> jobId.toString)).
        setPrincipal(config.principal)

      Resource.newBuilder(resource).
        setRole(config.role).
        setReservation(reservation).
        build()
    }

    val reserve = Offer.Operation.Reserve.newBuilder().
      addAllResources(reservedResources.asJava).
      build()

    newOfferOperation(reserve)
  }

  def reserveAndCreateVolumes(
    frameworkId: FrameworkID,
    jobId: UUID,
    reservationId: UUID,
    resourceMatch: ResourceMatcher.ResourceMatch): List[Offer.Operation] = {

    val localVolumes = resourceMatch.matches.
      collect { case r: DiskResourceMatch =>
        r.consumed
      }.
      flatten.
      collect {
        case DiskResourceMatch.Consumption(_, _, _, source, Some(volume)) =>
          (source, volume)
      }.
      toList.
      distinct

    List(
      reserve(
        frameworkId,
        jobId = jobId,
        reservationId = reservationId,
        resources = resourceMatch.resources),
      createVolumes(
        frameworkId,
        jobId = jobId,
        reservationId = reservationId,
        localVolumes = localVolumes))
  }
}


text:
<?php

namespace Symfony\Component\HttpClient\Chunk;

use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Contracts\HttpClient\ChunkInterface;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
class ErrorChunk implements ChunkInterface
{
    private $didThrow = false;
    private $offset;
    private $errorMessage;
    private $error;

    /**
     * @param \Throwable|string $error
     */
    public function __construct(int $offset, $error)
    {
        $this->offset = $offset;

        if (\is_string($error)) {
            $this->errorMessage = $error;
        } else {
            $this->error = $error;
            $this->errorMessage = $error->getMessage();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isTimeout(): bool
    {
        $this->didThrow = true;

        if (null !== $this->error) {
            throw new TransportException($this->errorMessage, 0, $this->error);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isFirst(): bool
    {
        $this->didThrow = true;
        throw new TransportException($this->errorMessage, 0, $this->error);
    }

    /**
     * {@inheritdoc}
     */
    public function isLast(): bool
    {
        $this->didThrow = true;
        throw new TransportException($this->errorMessage, 0, $this->error);
    }

    /**
     * {@inheritdoc}
     */
    public function getInformationalStatus(): ?array
    {
        $this->didThrow = true;
        throw new TransportException($this->errorMessage, 0, $this->error);
    }

    /**
     * {@inheritdoc}
     */
    public function getContent(): string
    {
        $this->didThrow = true;
        throw new TransportException($this->errorMessage, 0, $this->error);
    }

    /**
     * {@inheritdoc}
     */
    public function getOffset(): int
    {
        return $this->offset;
    }

    /**
     * {@inheritdoc}
     */
    public function getError(): ?string
    {
        return $this->errorMessage;
    }

    /**
     * @return bool Whether the wrapped error has been thrown or not
     */
    public function didThrow(): bool
    {
        return $this->didThrow;
    }

    /**
     * @return array
     */
    public function __sleep()
    {
        throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
    }

    public function __wakeup()
    {
        throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
    }

    public function __destruct()
    {
        if (!$this->didThrow) {
            $this->didThrow = true;
            throw new TransportException($this->errorMessage, 0, $this->error);
        }
    }
}


text:
title: "Cool Ubuntu know how"
excerpt: "The difference between Red Hat's and Ubuntu's configuration utility and how to fix sound issues in Quake III Arena and Pidgin running on Ubuntu."
header:
  teaser: /images/ubuntu.png
  og_image: /images/ubuntu.png
tags:
  - linux
  - howto
---

![Ubuntu](/images/ubntu.png){: .align-center}

One interesting thing is that in Red Hat based distributions the "run levels" configuration utility is **chkconfig** but in Ubuntu (Debian) the utility is **sysv-rc-conf**.

## Quake III Arena
If you have mute sound problems in **Quake III Arena**, try using these commands as root, this one before playing the game:

{% highlight bash %}
echo "quake3.x86 0 0 direct" > /proc/asound/card0/pcm0p/oss
{% endhighlight %}

After exiting the game:

{% highlight bash %}
echo "quake3.x86 0 0 disable" > /proc/asound/card0/pcm0c/oss
{% endhighlight %}

## Pidgin
Sound issues with **Pidgin**? In the [ Preferences > Sounds > Method ] choose *command* and write on the *Sound command* text box:

{% highlight bash %}
aplay %s
{% endhighlight %}

That's it, try it now!


text:
import unittest

from nose.tools import eq_

from mtglib.constants import base_url

class DescribeConstants(unittest.TestCase):

    def should_have_base_url(self):
        url = ('http://gatherer.wizards.com/Pages/Search/Default.aspx'
               '?action=advanced&')
        eq_(base_url, url)


text:
drop index ACT_IDX_EXEC_BUSKEY on ACT_RU_EXECUTION;
drop index ACT_IDX_TASK_CREATE on ACT_RU_TASK;
drop index ACT_IDX_IDENT_LNK_USER on ACT_RU_IDENTITYLINK;
drop index ACT_IDX_IDENT_LNK_GROUP on ACT_RU_IDENTITYLINK;

alter table ACT_GE_BYTEARRAY
    drop FOREIGN KEY ACT_FK_BYTEARR_DEPL;

alter table ACT_RU_EXECUTION
    drop FOREIGN KEY ACT_FK_EXE_PROCINST;

alter table ACT_RU_EXECUTION
    drop FOREIGN KEY ACT_FK_EXE_PARENT;

alter table ACT_RU_EXECUTION
    drop FOREIGN KEY ACT_FK_EXE_SUPER;

alter table ACT_RU_IDENTITYLINK
    drop FOREIGN KEY ACT_FK_TSKASS_TASK;

alter table ACT_RU_TASK
	drop FOREIGN KEY ACT_FK_TASK_EXE;

alter table ACT_RU_TASK
	drop FOREIGN KEY ACT_FK_TASK_PROCINST;

alter table ACT_RU_TASK
	drop FOREIGN KEY ACT_FK_TASK_PROCDEF;

alter table ACT_RU_VARIABLE
    drop FOREIGN KEY ACT_FK_VAR_EXE;

alter table ACT_RU_VARIABLE
	drop FOREIGN KEY ACT_FK_VAR_PROCINST;

alter table ACT_RU_VARIABLE
    drop FOREIGN KEY ACT_FK_VAR_BYTEARRAY;

alter table ACT_RU_JOB
    drop FOREIGN KEY ACT_FK_JOB_EXCEPTION;

alter table ACT_RU_EVENT_SUBSCR
    drop FOREIGN KEY ACT_FK_EVENT_EXEC;

drop table if exists ACT_GE_PROPERTY;
drop table if exists ACT_RU_VARIABLE;
drop table if exists ACT_GE_BYTEARRAY;
drop table if exists ACT_RE_DEPLOYMENT;
drop table if exists ACT_RU_IDENTITYLINK;
drop table if exists ACT_RU_TASK;
drop table if exists ACT_RE_PROCDEF;
drop table if exists ACT_RU_EXECUTION;
drop table if exists ACT_RU_JOB;
drop table if exists ACT_RU_EVENT_SUBSCR;


text:
package org.fusesource.amqp.blocking;

import org.fusesource.amqp.AMQPException;
import org.fusesource.amqp.callback.AMQPDelivery;
import org.fusesource.amqp.types.Envelope;

/**
 * @author Hiram Chirino
 */
public interface AMQPReceiver extends AMQPEndpoint {

    void addCredit(int value);
    AMQPDelivery peek();
    AMQPDelivery poll();

    Envelope receive() throws AMQPException;
}


text:
/*
	JSON-to-Go
	by Matt Holt

	https://github.com/mholt/json-to-go

	A simple utility to translate JSON into a Go type definition.
*/

function jsonToGo(json, typename, flatten = true, example = false, allOmitempty = false)
{
	let data;
	let scope;
	let go = "";
	let tabs = 0;

	const seen = {};
	const stack = [];
	let accumulator = "";
	let innerTabs = 0;
	let parent = "";

	try
	{
		data = JSON.parse(json.replace(/:(\s*\d*)\.0/g, ":$1.1")); // hack that forces floats to stay as floats
		scope = data;
	}
	catch (e)
	{
		return {
			go: "",
			error: e.message
		};
	}

	typename = format(typename || "AutoGenerated");
	append(`type ${typename} `);

	parseScope(scope);

	return {
		go: flatten
			? go += accumulator
			: go
	};

	function parseScope(scope, depth = 0)
	{
		if (typeof scope === "object" && scope !== null)
		{
			if (Array.isArray(scope))
			{
				let sliceType;
				const scopeLength = scope.length;

				for (let i = 0; i < scopeLength; i++)
				{
					const thisType = goType(scope[i]);
					if (!sliceType)
						sliceType = thisType;
					else if (sliceType != thisType)
					{
						sliceType = mostSpecificPossibleGoType(thisType, sliceType);
						if (sliceType == "any")
							break;
					}
				}

				const slice = flatten && ["struct", "slice"].includes(sliceType)
					? `[]${parent}`
					: `[]`;

				if (flatten && depth >= 2)
					appender(slice);
				else
					append(slice)
				if (sliceType == "struct") {
					const allFields = {};

					// for each field counts how many times appears
					for (let i = 0; i < scopeLength; i++)
					{
						const keys = Object.keys(scope[i])
						for (let k in keys)
						{
							let keyname = keys[k];
							if (!(keyname in allFields)) {
								allFields[keyname] = {
									value: scope[i][keyname],
									count: 0
								}
							}
							else {
								const existingValue = allFields[keyname].value;
								const currentValue = scope[i][keyname];

								if (compareObjects(existingValue, currentValue)) {
									const comparisonResult = compareObjectKeys(
										Object.keys(currentValue),
										Object.keys(existingValue)
									)
									if (!comparisonResult) {
										keyname = `${keyname}_${uuidv4()}`;
										allFields[keyname] = {
											value: currentValue,
											count: 0
										};
									}
								}
							}
							allFields[keyname].count++;
						}
					}

					// create a common struct with all fields found in the current array
					// omitempty dict indicates if a field is optional
					const keys = Object.keys(allFields), struct = {}, omitempty = {};
					for (let k in keys)
					{
						const keyname = keys[k], elem = allFields[keyname];

						struct[keyname] = elem.value;
						omitempty[keyname] = elem.count != scopeLength;
					}
					parseStruct(depth + 1, innerTabs, struct, omitempty); // finally parse the struct !!
				}
				else if (sliceType == "slice") {
					parseScope(scope[0], depth)
				}
				else {
					if (flatten && depth >= 2) {
						appender(sliceType || "any");
					} else {
						append(sliceType || "any");
					}
				}
			}
			else
			{
				if (flatten) {
					if (depth >= 2){
						appender(parent)
					}
					else {
						append(parent)
					}
				}
				parseStruct(depth + 1, innerTabs, scope);
			}
		}
		else {
			if (flatten && depth >= 2){
				appender(goType(scope));
			}
			else {
				append(goType(scope));
			}
		}
	}

	function parseStruct(depth, innerTabs, scope, omitempty)
	{
		if (flatten) {
			stack.push(
				depth >= 2
				? "\n"
				: ""
			)
		}

		const seenTypeNames = [];

		if (flatten && depth >= 2)
		{
			const parentType = `type ${parent}`;
			const scopeKeys = formatScopeKeys(Object.keys(scope));

			// this can only handle two duplicate items
			// future improvement will handle the case where there could
			// three or more duplicate keys with different values
			if (parent in seen && compareObjectKeys(scopeKeys, seen[parent])) {
				stack.pop();
				return
			}
			seen[parent] = scopeKeys;

			appender(`${parentType} struct {\n`);
			++innerTabs;
			const keys = Object.keys(scope);
			for (let i in keys)
			{
				const keyname = getOriginalName(keys[i]);
				indenter(innerTabs)
				const typename = uniqueTypeName(format(keyname), seenTypeNames)
				seenTypeNames.push(typename)

				appender(typename+" ");
				parent = typename
				parseScope(scope[keys[i]], depth);
				appender(' `json:"'+keyname);
				if (allOmitempty || (omitempty && omitempty[keys[i]] === true))
				{
					appender(',omitempty');
				}
				appender('"`\n');
			}
			indenter(--innerTabs);
			appender("}");
		}
		else
		{
			append("struct {\n");
			++tabs;
			const keys = Object.keys(scope);
			for (let i in keys)
			{
				const keyname = getOriginalName(keys[i]);
				indent(tabs);
				const typename = uniqueTypeName(format(keyname), seenTypeNames)
				seenTypeNames.push(typename)
				append(typename+" ");
				parent = typename
				parseScope(scope[keys[i]], depth);
				append(' `json:"'+keyname);
				if (allOmitempty || (omitempty && omitempty[keys[i]] === true))
				{
					append(',omitempty');
				}
				if (example && scope[keys[i]] !== "" && typeof scope[keys[i]] !== "object")
				{
					append('" example:"'+scope[keys[i]])
				}
				append('"`\n');
			}
			indent(--tabs);
			append("}");
		}
		if (flatten)
			accumulator += stack.pop();
	}

	function indent(tabs)
	{
		for (let i = 0; i < tabs; i++)
			go += '\t';
	}

	function append(str)
	{
		go += str;
	}

	function indenter(tabs)
	{
		for (let i = 0; i < tabs; i++)
			stack[stack.length - 1] += '\t';
	}

	function appender(str)
	{
		stack[stack.length - 1] += str;
	}

	// Generate a unique name to avoid duplicate struct field names.
	// This function appends a number at the end of the field name.
	function uniqueTypeName(name, seen) {
		if (seen.indexOf(name) === -1) {
			return name;
		}

		let i = 0;
		while (true) {
			let newName = name + i.toString();
			if (seen.indexOf(newName) === -1) {
				return newName;
			}

			i++;
		}
	}

	// Sanitizes and formats a string to make an appropriate identifier in Go
	function format(str)
	{
		str = formatNumber(str);

		let sanitized = toProperCase(str).replace(/[^a-z0-9]/ig, "")
		if (!sanitized) {
			return "NAMING_FAILED";
		}

		// After sanitizing the remaining characters can start with a number.
		// Run the sanitized string again trough formatNumber to make sure the identifier is Num[0-9] or Zero_... instead of 1.
		return formatNumber(sanitized)
	}

	// Adds a prefix to a number to make an appropriate identifier in Go
	function formatNumber(str) {
		if (!str)
			return "";
		else if (str.match(/^\d+$/))
			str = "Num" + str;
		else if (str.charAt(0).match(/\d/))
		{
			const numbers = {'0': "Zero_", '1': "One_", '2': "Two_", '3': "Three_",
				'4': "Four_", '5': "Five_", '6': "Six_", '7': "Seven_",
				'8': "Eight_", '9': "Nine_"};
			str = numbers[str.charAt(0)] + str.substr(1);
		}

		return str;
	}

	// Determines the most appropriate Go type
	function goType(val)
	{
		if (val === null)
			return "any";

		switch (typeof val)
		{
			case "string":
				if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
					return "time.Time";
				else
					return "string";
			case "number":
				if (val % 1 === 0)
				{
					if (val > -2147483648 && val < 2147483647)
						return "int";
					else
						return "int64";
				}
				else
					return "float64";
			case "boolean":
				return "bool";
			case "object":
				if (Array.isArray(val))
					return "slice";
				return "struct";
			default:
				return "any";
		}
	}

	// Given two types, returns the more specific of the two
	function mostSpecificPossibleGoType(typ1, typ2)
	{
		if (typ1.substr(0, 5) == "float"
				&& typ2.substr(0, 3) == "int")
			return typ1;
		else if (typ1.substr(0, 3) == "int"
				&& typ2.substr(0, 5) == "float")
			return typ2;
		else
			return "any";
	}

	// Proper cases a string according to Go conventions
	function toProperCase(str)
	{
		// ensure that the SCREAMING_SNAKE_CASE is converted to snake_case
		if (str.match(/^[_A-Z0-9]+$/)) {
			str = str.toLowerCase();
		}

		// https://github.com/golang/lint/blob/5614ed5bae6fb75893070bdc0996a68765fdd275/lint.go#L771-L810
		const commonInitialisms = [
			"ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP",
			"HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA",
			"SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "UID", "UUID",
			"URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS"
		];

		return str.replace(/(^|[^a-zA-Z])([a-z]+)/g, function(unused, sep, frag)
		{
			if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
				return sep + frag.toUpperCase();
			else
				return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase();
		}).replace(/([A-Z])([a-z]+)/g, function(unused, sep, frag)
		{
			if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0)
				return (sep + frag).toUpperCase();
			else
				return sep + frag;
		});
	}

	function uuidv4() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		  var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
		  return v.toString(16);
		});
	}

	function getOriginalName(unique) {
		const reLiteralUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
		const uuidLength = 36;

		if (unique.length >= uuidLength) {
			const tail = unique.substr(-uuidLength);
			if (reLiteralUUID.test(tail)) {
				return unique.slice(0, -1 * (uuidLength + 1))
			}
		}
		return unique
	}

	function compareObjects(objectA, objectB) {
		const object = "[object Object]";
		return Object.prototype.toString.call(objectA) === object
			&& Object.prototype.toString.call(objectB) === object;
	}

	function compareObjectKeys(itemAKeys, itemBKeys) {
		const lengthA = itemAKeys.length;
		const lengthB = itemBKeys.length;

		// nothing to compare, probably identical
		if (lengthA == 0 && lengthB == 0)
			return true;

		// duh
		if (lengthA != lengthB)
			return false;

		for (let item of itemAKeys) {
			if (!itemBKeys.includes(item))
				return false;
		}
		return true;
	}

	function formatScopeKeys(keys) {
		for (let i in keys) {
			keys[i] = format(keys[i]);
		}
		return keys
	}
}

if (typeof module != 'undefined') {
    if (!module.parent) {
        if (process.argv.length > 2 && process.argv[2] === '-big') {
            bufs = []
            process.stdin.on('data', function(buf) {
                bufs.push(buf)
            })
            process.stdin.on('end', function() {
                const json = Buffer.concat(bufs).toString('utf8')
                console.log(jsonToGo(json).go)
            })
        } else {
            process.stdin.on('data', function(buf) {
                const json = buf.toString('utf8')
                console.log(jsonToGo(json).go)
            })
        }
    } else {
        module.exports = jsonToGo
    }
}


text:
use strict;

use Getopt::Long qw(:config pass_through);
use XrefParser::BaseParser;

my ( $host,             $port,          $dbname,
     $user,             $pass,          $species,
     $sources,          $checkdownload, $create,
     $release,          $cleanup,       $drop_existing_db,
     $deletedownloaded, $dl_path,       $notsource,
     $unzip, $stats, $notverbose );

my $options = join(" ",@ARGV);

print "Options: ".join(" ",@ARGV)."\n";

$unzip = 0;    # Do not decompress gzipped files by default

$notverbose = 0;

GetOptions(
    'dbuser|user=s'  => \$user,
    'dbpass|pass=s'  => \$pass,
    'dbhost|host=s'  => \$host,
    'dbport|port=i'  => \$port,
    'dbname=s'       => \$dbname,
    'species=s'      => \$species,
    'source=s'       => \$sources,
    'download_dir=s' => \$dl_path,
    'checkdownload!' => \$checkdownload,    # Don't download if exists
    'create'         => \$create,
    'setrelease=s'   => \$release,
    'cleanup'        => \$cleanup,
    'stats'          => \$stats,
    'notverbose'     => \$notverbose,
    'notsource=s'    => \$notsource,
    'drop_db|dropdb!' =>
      \$drop_existing_db,    # Drop xref db without user interaction
    'delete_downloaded' => \$deletedownloaded,
    'download_path=s'   => \$dl_path,
    'unzip' => \$unzip,                   # Force decompression of files
    'help'  => sub { usage(); exit(0); } );

if($ARGV[0]){
  print STDERR "Unknown command line arguments:-\n";
  foreach my $a (@ARGV){
    print STDERR "\t".$a."\n";
  }
  print STDERR "Stopping script. Please fix the command line.\n";
  print STDERR "use -help for full list of command line options.\n";;
  exit(1);
}

my @species = split(/,/,join(',',$species));
my @sources  = split(/,/,join(',',$sources));
my @notsource  = split(/,/,join(',',$notsource));

$| = 1;

if ( !$user || !$host || !$dbname ) {
    usage();
    exit(1);
}

print "host os $host\n";

my $base_parser = XrefParser::BaseParser->new();

#
# If any sources are missing then we need to calculate the display xrefs from the core.
# As the xref database will not have all the data. Using the core is much slower!!
#

$base_parser->run(
               $host, ( defined $port ? $port : '3306' ),
               $dbname,           $user,
               $pass,             \@species,
               \@sources,         $checkdownload,
               $create,           $release,
               $cleanup,          $drop_existing_db,
               $deletedownloaded, $dl_path,
               \@notsource,       $unzip, $stats, !($notverbose) );

$base_parser->add_meta_pair("options",$options);

if($options =~ /source/ ){
  $base_parser->add_meta_pair("fullmode","no");
}
else{
  $base_parser->add_meta_pair("fullmode","yes");
}

$base_parser->parsing_finished_store_data();

# --------------------------------------------------------------------------------

sub usage {

  print << "EOF";

  xref_parser.pl -user {user} -pass {password} -host {host} \\
    -port {port} -dbname {database} -species {species1,species2} \\
    -source {source1,source2} -notsource {source1,source2} \\
    -create -setrelease -deletedownloaded -checkdownload -stats -verbose \\
    -cleanup -drop_db -download_path -unzip

  -user             User name to access database. Must allow writing.

  -pass             Password for user.

  -host             Database host.

  -port             Database port.

  -dbname           Name of xref database to use/create.

  -species          Which species to import. Multiple -species arguments
                    and/or comma, separated lists of species are
                    allowed. Species may be referred to by genus/species
                    (e.g. homo_sapiens) or common aliases (e.g. human).
                    Specifying an unknown species will cause a list
                    of valid species to be printed.  Not specifying a
                    -species argument will result in all species being
                    used.

  -source           Which sources to import. Multiple -source arguments
                    and/or comma, separated lists of sources are
                    allowed.  Specifying an unknown source will cause a
                    list of valid sources to be printed.  Not specifying
                    a -source argument will result in all species being
                    used.

  -notsource        Which source to skip.

  -create           If specified, cause dbname to be deleted and
                    re-created if it already exists.  The user is
                    prompted before the database is dropped to
                    prevent disasters arising from dropping the wrong
                    database.  If needed, this switch will also make
                    the script ask the user whether it should run the
                    'xref_config2sql.pl' script for him/her to renew
                    'sql/populate_metadata.sql' from 'xref_config.ini'.

  -checkdownload    Check if file exists, otherwise downloads the file.

  -deletedownloaded Delete any existing downloaded files first.

  -setrelease       Set the release version for ALL the sources specified.

  -cleanup          Delete the downloaded source files after parsing.

  -drop_db          Drop the xref-database without user interaction.

  -download_path    Directory into which to download files (default is
                    the current directory).

  -unzip            Decompress gzipped files (default is to use compressed
                    files).

  -notverbose       Do not output messages about the parsing. (NOT recomended)

  -stats            Generate the stats for the number of types of xrefs added.

EOF

}

#--------------------------------------------------------------------------------


text:
package com.intellij.util.ui;

import com.intellij.openapi.keymap.impl.KeymapImpl;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.FixedComboBoxEditor;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.MutableCollectionComboBoxModel;
import com.intellij.ui.SimpleListCellRenderer;
import org.jetbrains.annotations.NotNull;

import javax.swing.event.DocumentEvent;

public final class ComboBoxModelEditor<T> extends ListModelEditorBase<T> {
  private final ComboBox<T> comboBox;

  public ComboBoxModelEditor(@NotNull ListItemEditor<T> itemEditor) {
    super(itemEditor);

    comboBox = new ComboBox<>(model);
    comboBox.setEditor(new NameEditor());
    comboBox.setRenderer(SimpleListCellRenderer.create("", value -> itemEditor.getName(value)));
  }

  @NotNull
  @Override
  public MutableCollectionComboBoxModel<T> getModel() {
    return model;
  }

  @NotNull
  public ComboBox getComboBox() {
    return comboBox;
  }

  private class NameEditor extends FixedComboBoxEditor {
    private T item = null;
    private boolean mutated;

    NameEditor() {
      getField().getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(@NotNull DocumentEvent e) {
          if (item != null && itemEditor.isEditable(item)) {
            String newName = getField().getText();
            if (newName.equals(itemEditor.getName(item))) {
              return;
            }

            if (!mutated) {
              mutated = true;
              item = getMutable(item);
            }
            ((KeymapImpl)item).setName(newName);
          }
        }
      });
    }

    @Override
    public void setItem(Object newItem) {
      if (newItem != null && newItem != item) {
        //noinspection unchecked
        item = (T)newItem;
        mutated = false;
        getField().setText(itemEditor.getName(item));
      }
    }

    @Override
    public Object getItem() {
      return item;
    }
  }
}


text:
package org.apache.felix.dm.test.bundle.annotation.publisher;

import java.util.HashMap;
import java.util.Map;

import org.apache.felix.dm.annotation.api.AdapterService;
import org.apache.felix.dm.annotation.api.Component;
import org.apache.felix.dm.annotation.api.Init;
import org.apache.felix.dm.annotation.api.LifecycleController;
import org.apache.felix.dm.annotation.api.Property;
import org.apache.felix.dm.annotation.api.ServiceDependency;
import org.apache.felix.dm.annotation.api.Start;
import org.apache.felix.dm.test.bundle.annotation.sequencer.Sequencer;

/**
 * Test an AdapterService which provides its interface using a @ServiceLifecycle.
 */
public class AdapterServiceTestWithPublisher
{
    public interface Provider
    {
    }

    public interface Provider2
    {
    }

    @Component
    public static class Consumer
    {
        @ServiceDependency(filter="(name=AdapterServiceTestWithPublisher)")
        Sequencer m_sequencer;

        @ServiceDependency(required=false, removed = "unbind")
        void bind(Map properties, Provider2 provider)
        {
            m_sequencer.step(1);
            // check ProviderImpl properties
            if ("bar".equals(properties.get("foo")))
            {
                m_sequencer.step(2);
            }
            // check extra ProviderImpl properties (returned by start method)
            if ("bar2".equals(properties.get("foo2")))
            {
                m_sequencer.step(3);
            }
            // check Provider2Impl properties
            if ("bar3".equals(properties.get("foo3")))
            {
                m_sequencer.step(4);
            }
            // check extra Provider2Impl properties (returned by start method)
            if ("bar4".equals(properties.get("foo4")))
            {
                m_sequencer.step(5);
            }

        }

        void unbind(Provider2 provider)
        {
            m_sequencer.step(6);
        }
    }

    @Component(properties={@Property(name="foo", value="bar")})
    public static class ProviderImpl implements Provider
    {
        @Start
        Map start()
        {
            // Add some extra service properties ... they will be appended to the one we have defined
            // in the @Service annotation.
            return new HashMap() {{ put("foo2", "bar2"); }};
        }
    }

    @AdapterService(properties={@Property(name="foo3", value="bar3")}, adapteeService=Provider.class)
    public static class Provider2Impl implements Provider2
    {
        @LifecycleController
        Runnable m_publisher; // injected and used to register our service

        @LifecycleController(start=false)
        Runnable m_unpublisher; // injected and used to unregister our service

        @ServiceDependency(filter="(name=AdapterServiceTestWithPublisher)")
        Sequencer m_sequencer;

        @Init
        void init()
        {
            // register service in 1 second
            Utils.schedule(m_publisher, 1000);
            // unregister the service in 2 seconds
            Utils.schedule(m_unpublisher, 2000);
        }

        @Start
        Map start()
        {
            // Add some extra service properties ... they will be appended to the one we have defined
            // in the @Service annotation.
            return new HashMap() {{ put("foo4", "bar4"); }};
        }
    }
}


text:
class Profiles::KeysController < ApplicationController
  layout "profile"

  before_filter :reject_guest!

  def index
    @keys = current_user.keys.order('id DESC').all
  end

  def show
    @key = current_user.keys.find(params[:id])
  end

  def new
    @key = current_user.keys.new
  end

  def create
    @key = current_user.keys.new(params[:key])

    if @key.save
      redirect_to profile_key_path(@key)
    else
      render 'new'
    end
  end

  def destroy
    @key = current_user.keys.find(params[:id])
    @key.destroy

    respond_to do |format|
      format.html { redirect_to profile_keys_url }
      format.js { render nothing: true }
    end
  end
end


text:
app.service("UserMessagesService", function($http, MessageService) {

    console.log("UserMessagesService ready");

    const PATH = "/messages";
    var that = this;

    this.validateRecipient = function(recipient, callback) {

        var params = {
            "recipient" : recipient
        };
        var result = $http.get(PATH+"/validate", {
            params:params
        });

        result.success(function() {
            callback();
        });

        result.error(function(data, status) {
            if (status === 404) {
                MessageService.danger("Recipient not found");
            }
            else {
                console.error(data, status);
                MessageService.danger("Error during recipient validation");
            }
        });
    };

    this.getMessages = function(callback) {
        var result = $http.get(PATH);

        result.success(function(data) {
            callback(data);
        });

        result.error(function(data) {
            console.log("UserMessagesService", "getMessages", data);
            MessageService.warning("Unable to get messages");
        });
    };

    this.send = function(message, callback) {
        var result = $http.post(PATH, message);

        result.success(function(data) {
            callback();
        });

        result.error(function(data) {
            MessageService.danger("Unable to send message");
        });
    };

});


text:
from warnings import warnpy3k
warnpy3k("the GLWS module has been removed in Python 3.0", stacklevel=2)
del warnpy3k

NOERROR = 0
NOCONTEXT = -1
NODISPLAY = -2
NOWINDOW = -3
NOGRAPHICS = -4
NOTTOP = -5
NOVISUAL = -6
BUFSIZE = -7
BADWINDOW = -8
ALREADYBOUND = -100
BINDFAILED = -101
SETFAILED = -102


text:
require 'vagrant'

require "vagrant-destroyer/version"
require "vagrant-destroyer/plugin"


text:
<?php

/**
 * Created by IntelliJ IDEA.
 * User: martindilger
 * Date: 16.10.12
 * Time: 15:33
 * To change this template use File | Settings | File Templates.
 */
class CSSWebResource extends DefaultWebResource
{

    public function CSSWebResource($resource,ComponentStub $packageResource,$identifier){
        $this->DefaultWebResource(DefaultWebResource::toComponentPackagePath($packageResource,$resource),new CSSResourceRenderer(),$identifier);
    }
}


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

<TITLE>
NonLeafPosition (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.layoutmgr

Class NonLeafPosition

java.lang.Object
  org.apache.fop.layoutmgr.Position
      org.apache.fop.layoutmgr.NonLeafPosition

public class NonLeafPosition
extends Position

A non-leaf position.

Constructor Summary

NonLeafPosition(LayoutManager lm,
                Position sub)

          Construct a leaf position.

Method Summary

 boolean
generatesAreas()

 Position
getPosition()

          Overridden by NonLeafPosition to return the Position of its child LM.

 java.lang.String
toString()

Methods inherited from class org.apache.fop.layoutmgr.Position

getIndex, getLM, getLM, getPosition, getShortLMName, setIndex

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NonLeafPosition

public NonLeafPosition(LayoutManager lm,
                       Position sub)

Construct a leaf position.

Parameters:
lm - the associated layout manager
sub - the position

Method Detail

getPosition

public Position getPosition()

Description copied from class: Position

Overridden by NonLeafPosition to return the Position of its child LM.

Overrides:
getPosition in class Position

Returns:
the sub position

generatesAreas

public boolean generatesAreas()

Overrides:
generatesAreas in class Position

Returns:
true if generates areas

toString

public java.lang.String toString()

Overrides:
toString in class Position

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.57
 * Generated at: 2015-10-25 15:43:21 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.views;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class login_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
Welcome!
\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
Login
\r\n");
      out.write("            <form name=\"loginForm\" ng-controller=\"LoginFormController as loginFormCtrl\"\r\n");
      out.write("                  ng-submit=\"loginForm.$valid && loginFormCtrl.login()\" novalidate>\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("                  <md-input-container class=\"p-0 m-b-15\">\r\n");
      out.write("                    User name\r\n");
      out.write("                    <input name=\"userName\" ng-model=\"loginFormCtrl.userName\" required>\r\n");
      out.write("
\r\n");
      out.write("
This is required!
\r\n");
      out.write("
\r\n");
      out.write("                  </md-input-container>\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("                  <md-input-container class=\"p-0 m-b-15\">\r\n");
      out.write("                    Password\r\n");
      out.write("                    <input type=\"password\" name=\"password\" ng-model=\"loginFormCtrl.password\" required>\r\n");
      out.write("
\r\n");
      out.write("
This is required!
\r\n");
      out.write("
\r\n");
      out.write("                  </md-input-container>\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("                  <md-button type=\"submit\" class=\"md-raised border-button\">Login</md-button>\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("            </form>\r\n");
      out.write("\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
\r\n");
      out.write("
");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
package in.nerdworks.browserapp;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class SWTLoader {
    private static final String BASE_URL = "https://github.com/avranju/swt-browser-app/blob/master/lib/swt/";
    private static final String BROWSER_UTIL_JAR_URL = "https://github.com/avranju/swt-browser-app/blob/master/out/artifacts/swt_browser_app_jar/browser-util.jar?raw=true";
    private static final String SWT_JAR_NAME = "swt.jar";
    private static final String BROWSER_UTIL_JAR_NAME = "browser-util.jar";
    private static FileCache filesCache;
    private static String jarName;

    static {
        // swt-4.4-win32-win32-x86/swt.jar?raw=true
        String osName = System.getProperty("os.name").toLowerCase();
        boolean isWindows = osName.contains("win");
        boolean isMac = osName.contains("mac");
        boolean isLinux = osName.contains("linux");
        boolean isx64 = System.getProperty("os.arch").toLowerCase().contains("64");

        jarName = "swt-4.4-" +
                (isWindows ? "win32-win32-" :
                        isMac ? "cocoa-macosx-" :
                                isLinux ? "gtk-linux-" : "") +
                (isx64 ? "x86_x64" : "x86") +
                "/swt.jar?raw=true";
    }

    public static File[] loadJars() throws ExecutionException, MalformedURLException {
        if(filesCache == null) {
            filesCache = new FileCache(new FileSource[] {
                    new FileSource(SWT_JAR_NAME, new URL(BASE_URL + jarName)),
                    new FileSource(BROWSER_UTIL_JAR_NAME, new URL(BROWSER_UTIL_JAR_URL))
            });
        }

        return new File[] {
                filesCache.getFile(SWT_JAR_NAME),
                filesCache.getFile(BROWSER_UTIL_JAR_NAME)
        };
    }
}


text:
/*
 * These authors would like to acknowledge the Spanish Ministry of Industry,
 * Tourism and Trade, for the support in the project TSI020301-2008-2
 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled
 * Mobile Dynamic Environments", led by Treelogic
 * ( http://www.treelogic.com/ ):
 *
 *   http://www.piramidepse.com/
 */

package com.google.zxing.oned.rss.expanded;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import junit.framework.TestCase;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitArray;
import com.google.zxing.common.GlobalHistogramBinarizer;

/**
 * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es)
 * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es)
 */
public final class RSSExpandedImage2stringTestCase extends TestCase {

  public void testDecodeRow2string_1() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/1.jpg";
    String expected = "(11)100224(17)110224(3102)000100";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_2() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/2.jpg";
    String expected = "(01)90012345678908(3103)001750";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_3() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/3.jpg";
    String expected = "(10)12A";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_4() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/4.jpg";
    String expected = "(01)98898765432106(3202)012345(15)991231";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_5() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/5.jpg";
    String expected = "(01)90614141000015(3202)000150";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_7() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/7.png";
    String expected = "(10)567(11)010101";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_10() throws Exception{
    String path = "test/data/blackbox/rssexpanded-1/10.png";
    String expected = "(01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456(423)012345678901";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_11() throws Exception{
    String expected = "(01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456";
    String path = "test/data/blackbox/rssexpanded-1/11.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_12() throws Exception{
    String expected = "(01)98898765432106(3103)001750";
    String path = "test/data/blackbox/rssexpanded-1/12.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_13() throws Exception{
    String expected = "(01)90012345678908(3922)795";
    String path = "test/data/blackbox/rssexpanded-1/13.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_14() throws Exception{
    String expected = "(01)90012345678908(3932)0401234";
    String path = "test/data/blackbox/rssexpanded-1/14.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_15() throws Exception{
    String expected = "(01)90012345678908(3102)001750(11)100312";
    String path = "test/data/blackbox/rssexpanded-1/15.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_16() throws Exception{
    String expected = "(01)90012345678908(3202)001750(11)100312";
    String path = "test/data/blackbox/rssexpanded-1/16.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_17() throws Exception{
    String expected = "(01)90012345678908(3102)001750(13)100312";
    String path = "test/data/blackbox/rssexpanded-1/17.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_18() throws Exception{
    String expected = "(01)90012345678908(3202)001750(13)100312";
    String path = "test/data/blackbox/rssexpanded-1/18.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_19() throws Exception{
    String expected = "(01)90012345678908(3102)001750(15)100312";
    String path = "test/data/blackbox/rssexpanded-1/19.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_20() throws Exception{
    String expected = "(01)90012345678908(3202)001750(15)100312";
    String path = "test/data/blackbox/rssexpanded-1/20.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_21() throws Exception{
    String expected = "(01)90012345678908(3102)001750(17)100312";
    String path = "test/data/blackbox/rssexpanded-1/21.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_22() throws Exception{
    String expected = "(01)90012345678908(3202)001750(17)100312";
    String path = "test/data/blackbox/rssexpanded-1/22.jpg";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_25() throws Exception{
    String expected = "(10)123";
    String path = "test/data/blackbox/rssexpanded-1/25.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_26() throws Exception{
    String expected = "(10)5678(11)010101";
    String path = "test/data/blackbox/rssexpanded-1/26.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_27() throws Exception{
    String expected = "(10)1098-1234";
    String path = "test/data/blackbox/rssexpanded-1/27.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_28() throws Exception{
    String expected = "(10)1098/1234";
    String path = "test/data/blackbox/rssexpanded-1/28.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_29() throws Exception{
    String expected = "(10)1098.1234";
    String path = "test/data/blackbox/rssexpanded-1/29.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_30() throws Exception{
    String expected = "(10)1098*1234";
    String path = "test/data/blackbox/rssexpanded-1/30.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_31() throws Exception{
    String expected = "(10)1098,1234";
    String path = "test/data/blackbox/rssexpanded-1/31.png";

    assertCorrectImage2string(path, expected);
  }

  public void testDecodeRow2string_32() throws Exception{
    String expected = "(15)991231(3103)001750(10)12A(422)123(21)123456(423)0123456789012";
    String path = "test/data/blackbox/rssexpanded-1/32.png";

    assertCorrectImage2string(path, expected);
  }

  private static void assertCorrectImage2string(String path, String expected) throws Exception {
    RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

    BufferedImage image = ImageIO.read(new File(path));
    BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
    int rowNumber = binaryMap.getHeight() / 2;
    BitArray row = binaryMap.getBlackRow(rowNumber, null);

    Result result = rssExpandedReader.decodeRow(rowNumber, row, new Hashtable());

    assertEquals(BarcodeFormat.RSS_EXPANDED, result.getBarcodeFormat());
    assertEquals(expected, result.getText());
  }

}


text:
using Microsoft.Xna.Framework;
using SharpDX.Mathematics.Interop;
using SharpDX.X3DAudio;
using SharpDX.XAudio2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Spectrum.Framework.Audio
{
    public class AudioManager
    {
        internal static RawVector3 V3ToV3(Vector3 vector)
        {
            return new RawVector3(vector.X, vector.Y, vector.Z);
        }
        internal static Vector3 V3ToV3(RawVector3 vector)
        {
            return new Vector3(vector.X, vector.Y, vector.Z);
        }
        internal static Listener Listener;
        internal static readonly XAudio2 _xaudio2 = new XAudio2();
        internal static readonly X3DAudio X3DAudio = new X3DAudio(SharpDX.Multimedia.Speakers.Stereo);
        internal static MasteringVoice MasteringVoice = new MasteringVoice(_xaudio2);
        public static int DestinationChannels { get { return 2; } }

        public static Vector3 ListenerPosition
        {
            get => V3ToV3(Listener.Position);
            set => Listener.Position = V3ToV3(value);
        }
        public static Vector3 ListenerForward
        {
            get => V3ToV3(Listener.OrientFront);
            set => Listener.OrientFront = V3ToV3(value);
        }
        public static Vector3 ListenerUp
        {
            get => V3ToV3(Listener.OrientTop);
            set => Listener.OrientTop = V3ToV3(value);
        }

        public static void Init()
        {
            Listener = new Listener()
            {
                Position = new RawVector3(0, 0, 0),
                OrientFront = new RawVector3(0, 0, 1),
                OrientTop = new RawVector3(0, 1, 0),
                Velocity = new RawVector3(0, 0, 0)
            };
        }

        public static void Shutdown()
        {
            _xaudio2.Dispose();
        }
    }
}


text:
require 'spec_helper'
require 'timecop'
require 'vcr'

describe Deadwood::Katello::Product do
  let(:org_id) { 'ACME_Corporation' }
  it "should create and read products for ACME_Corporation then delete them" do
    VCR.use_cassette 'read_products' do
      provider = Deadwood::Katello::Provider.new(:organization_id => org_id, :provider_type => 'Custom', :repository_url => 'http://repo.example.com', :name => 'test_provider_name', :description => 'Test provider description')
      provider.save
      product = Deadwood::Katello::Product.new(:provider_id => provider.id, :name => 'Test_product', :description => 'Test description')
      product.save
      products = Deadwood::Katello::Product.find(:all, :from => "/katello/api/organizations/#{org_id}/products")
      products.nil?.should be_false
      products.empty?.should be_false
      products[0].name.include?('Test_product').should be_true
      product.organization_id = org_id
      product.destroy
      provider.destroy
      products = Deadwood::Katello::Product.find(:all, :from => "/katello/api/organizations/#{org_id}/products")
      products.empty?.should be_true

    end
  end

end


text:
void  protobuf_AddDesc_CLogin_2eproto();
void protobuf_AssignDesc_CLogin_2eproto();
void protobuf_ShutdownFile_CLogin_2eproto();

class CLogin;

// ===================================================================

class CLogin : public ::google::protobuf::Message {
 public:
  CLogin();
  virtual ~CLogin();

  CLogin(const CLogin& from);

  inline CLogin& operator=(const CLogin& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const CLogin& default_instance();

  void Swap(CLogin* other);

  // implements Message ----------------------------------------------

  CLogin* New() const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const CLogin& from);
  void MergeFrom(const CLogin& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  public:
  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // required string password = 2;
  inline bool has_password() const;
  inline void clear_password();
  static const int kPasswordFieldNumber = 2;
  inline const ::std::string& password() const;
  inline void set_password(const ::std::string& value);
  inline void set_password(const char* value);
  inline void set_password(const char* value, size_t size);
  inline ::std::string* mutable_password();
  inline ::std::string* release_password();
  inline void set_allocated_password(::std::string* password);

  // required string number = 3;
  inline bool has_number() const;
  inline void clear_number();
  static const int kNumberFieldNumber = 3;
  inline const ::std::string& number() const;
  inline void set_number(const ::std::string& value);
  inline void set_number(const char* value);
  inline void set_number(const char* value, size_t size);
  inline ::std::string* mutable_number();
  inline ::std::string* release_number();
  inline void set_allocated_number(::std::string* number);

  // @@protoc_insertion_point(class_scope:CLogin)
 private:
  inline void set_has_password();
  inline void clear_has_password();
  inline void set_has_number();
  inline void clear_has_number();

  ::google::protobuf::UnknownFieldSet _unknown_fields_;

  ::google::protobuf::uint32 _has_bits_[1];
  mutable int _cached_size_;
  ::std::string* password_;
  ::std::string* number_;
  friend void  protobuf_AddDesc_CLogin_2eproto();
  friend void protobuf_AssignDesc_CLogin_2eproto();
  friend void protobuf_ShutdownFile_CLogin_2eproto();

  void InitAsDefaultInstance();
  static CLogin* default_instance_;
};
// ===================================================================

// ===================================================================

// CLogin

// required string password = 2;
inline bool CLogin::has_password() const {
  return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void CLogin::set_has_password() {
  _has_bits_[0] |= 0x00000001u;
}
inline void CLogin::clear_has_password() {
  _has_bits_[0] &= ~0x00000001u;
}
inline void CLogin::clear_password() {
  if (password_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    password_->clear();
  }
  clear_has_password();
}
inline const ::std::string& CLogin::password() const {
  // @@protoc_insertion_point(field_get:CLogin.password)
  return *password_;
}
inline void CLogin::set_password(const ::std::string& value) {
  set_has_password();
  if (password_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    password_ = new ::std::string;
  }
  password_->assign(value);
  // @@protoc_insertion_point(field_set:CLogin.password)
}
inline void CLogin::set_password(const char* value) {
  set_has_password();
  if (password_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    password_ = new ::std::string;
  }
  password_->assign(value);
  // @@protoc_insertion_point(field_set_char:CLogin.password)
}
inline void CLogin::set_password(const char* value, size_t size) {
  set_has_password();
  if (password_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    password_ = new ::std::string;
  }
  password_->assign(reinterpret_cast<const char*>(value), size);
  // @@protoc_insertion_point(field_set_pointer:CLogin.password)
}
inline ::std::string* CLogin::mutable_password() {
  set_has_password();
  if (password_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    password_ = new ::std::string;
  }
  // @@protoc_insertion_point(field_mutable:CLogin.password)
  return password_;
}
inline ::std::string* CLogin::release_password() {
  clear_has_password();
  if (password_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    return NULL;
  } else {
    ::std::string* temp = password_;
    password_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
    return temp;
  }
}
inline void CLogin::set_allocated_password(::std::string* password) {
  if (password_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete password_;
  }
  if (password) {
    set_has_password();
    password_ = password;
  } else {
    clear_has_password();
    password_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  }
  // @@protoc_insertion_point(field_set_allocated:CLogin.password)
}

// required string number = 3;
inline bool CLogin::has_number() const {
  return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void CLogin::set_has_number() {
  _has_bits_[0] |= 0x00000002u;
}
inline void CLogin::clear_has_number() {
  _has_bits_[0] &= ~0x00000002u;
}
inline void CLogin::clear_number() {
  if (number_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_->clear();
  }
  clear_has_number();
}
inline const ::std::string& CLogin::number() const {
  // @@protoc_insertion_point(field_get:CLogin.number)
  return *number_;
}
inline void CLogin::set_number(const ::std::string& value) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(value);
  // @@protoc_insertion_point(field_set:CLogin.number)
}
inline void CLogin::set_number(const char* value) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(value);
  // @@protoc_insertion_point(field_set_char:CLogin.number)
}
inline void CLogin::set_number(const char* value, size_t size) {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  number_->assign(reinterpret_cast<const char*>(value), size);
  // @@protoc_insertion_point(field_set_pointer:CLogin.number)
}
inline ::std::string* CLogin::mutable_number() {
  set_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    number_ = new ::std::string;
  }
  // @@protoc_insertion_point(field_mutable:CLogin.number)
  return number_;
}
inline ::std::string* CLogin::release_number() {
  clear_has_number();
  if (number_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    return NULL;
  } else {
    ::std::string* temp = number_;
    number_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
    return temp;
  }
}
inline void CLogin::set_allocated_number(::std::string* number) {
  if (number_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
    delete number_;
  }
  if (number) {
    set_has_number();
    number_ = number;
  } else {
    clear_has_number();
    number_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
  }
  // @@protoc_insertion_point(field_set_allocated:CLogin.number)
}

// @@protoc_insertion_point(namespace_scope)

#ifndef SWIG
namespace google {
namespace protobuf {

}  // namespace google
}  // namespace protobuf
#endif  // SWIG

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_CLogin_2eproto__INCLUDED


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //UIView之所以能够显示,使用为它内部有一个层layer。层是通过渲染的额方式绘制到上下文的
    [self.view.layer renderInContext:ctx];

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //如何把一个图片转化至二进制流
//    NSData * data = UIImageJPEGRepresentation(image, 1);
//    [data writeToFile:@"/Users/mac/Desktop/abc.jpg" atomically:YES];

    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:@"/Users/mac/Desktop/abc.png" atomically:YES];

}

@end


text:
package ar.com.circuloodontochaco.co.dao;

import ar.com.circuloodontochaco.co.model.CabeceraAsiento;

/**
 * @author Jorge E. Villaverde
 *
 */
public interface CabeceraAsientoRepository extends CoRepository<CabeceraAsiento> {

}


text:
using JetBrains.Annotations;
using System;
using System.Diagnostics.CodeAnalysis;

namespace BenchmarkDotNet.Attributes
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class GenericTypeArgumentsAttribute : Attribute
    {
        public Type[] GenericTypeArguments { get; }

        // CLS-Compliant Code requires a constructor without an array in the argument list
        [PublicAPI] public GenericTypeArgumentsAttribute() => GenericTypeArguments = new Type[0];

        public GenericTypeArgumentsAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type)
            => GenericTypeArguments = new Type[] { type };

        public GenericTypeArgumentsAttribute(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type1,
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type2)
            => GenericTypeArguments = new Type[] { type1, type2 };

        public GenericTypeArgumentsAttribute(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type1,
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type2,
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type3)
            => GenericTypeArguments = new Type[] { type1, type2, type3 };
    }
}


text:
export const setHousing = (housing) => {
  return { type: 'SET_HOUSING', payload: housing };
};

export const setCol = (col) => {
  return { type: 'SET_COL', payload: col };
};

export const setHealthcare = (health_care) => {
  return { type: 'SET_HEALTH_CARE', payload: health_care };
};

export const setEnvironmentalQuality = (environmental_quality) => {
  return { type: 'SET_ENVIRONMENTAL_QUALITY', payload: environmental_quality };
};

export const setEconomy = (economy) => {
  return { type: 'SET_ECONOMY', payload: economy };
};

export const setLeisure = (leisure) => {
  return { type: 'SET_LEISURE', payload: leisure };
};

export const setCommute = (commute) => {
  return { type: 'SET_COMMUTE', payload: commute };
};

export const setSafety = (safety) => {
  return { type: 'SET_SAFETY', payload: safety };
};

export const setEducation = (education) => {
  return { type: 'SET_EDUCATION', payload: education };
};

export const setSummary = (summary) => {
  return { type: 'SET_SUMMARY', payload: summary };
};

export const setTravelConnectivity = (travel_connectivity) => {
  return { type: 'SET_TRAVEL_CONNECTIVITY', payload: travel_connectivity };
};

export const setInternetAccess = (internet_access) => {
  return { type: 'SET_INTERNET_ACCESS', payload: internet_access };
};

export const setTolerance = (tolerance) => {
  return { type: 'SET_TOLERANCE', payload: tolerance };
};

export const setOutdoors = (outdoors) => {
  return { type: 'SET_OUTDOORS', payload: outdoors };
};

export const setTaxation = (taxation) => {
  return { type: 'SET_TAXATION', payload: taxation };
};

export const setBusinessFreedom = (business_freedom) => {
  return { type: 'SET_BUSINESS_FREEDOM', payload: business_freedom };
};

export const setStartUps = (startups) => {
  return { type: 'SET_STARTUPS', payload: startups };
};

export const setVentureCapital = (venture_capital) => {
  return { type: 'SET_VENTURE_CAPITAL', payload: venture_capital };
};

export const setPhotoURL = (photoURL) => {
  return { type: 'SET_PHOTO_URL', payload: photoURL };
};

export const setCity = (city) => {
  return { type: 'SET_CITY', payload: city };
};

export const setScore = (score) => {
  return { type: 'SET_SCORE', payload: score };
};