text:
<?php

namespace PW\UserBundle\Command;

use PW\UserBundle\Document\User,
    Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,
    Symfony\Component\Console\Input\InputArgument,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface;

/**
 * SeedBrandInfoCommand
 */
class SeedBrandInfoCommand extends ContainerAwareCommand
{
    /**
     * document manager placeholder instance
     */
    protected $dm;

    protected $info = array(
    "littlebird" => array (
    	 "hash" => "abac355adae436e7b03b6d4b271d3f0652dec4f5",
    	"about" => "LittleBird Philosophy\n
    If you don't own it...make it\n
    If it's you...rock it\n\n
    If you imagine it...create it\n
    If you dig it...live it\n
    If you don't know it...learn it",
    	"site" => "http://www.littlebirdstyle.com/"
    ),
    "gorjana" => array (
    	 "hash" => "e6e0eca6629e9487cf1c54f1a4a59d38b382afd3",
    	"about" => "Gorjana jewelry and handbags are designed to effortlessly collaborate with the chic, modern woman's wardrobe.",
    	"site" => "http://www.gorjana.com/"
    ),
    "Estee Lauder" => array (
    	 "hash" => "c30b86083a9b319f45609461c9f8e83ef83126f1",
    	"about" => "Estée Lauder is one of the world's most renowned beauty companies. Our skincare, makeup and fragrance products are innovative, technologically advanced and proven effective.",
    	"site" => "http://www.esteelauder.com/index.tmpl"
    ),
    "Lancome" => array (
    	 "hash" => "1301141e8d08f8763d10318f298fb444909e5582",
    	"about" => "undefined",
    	"site" => "http://www.lancome-usa.com/"
    ),
    "Clinique" => array (
    	 "hash" => "d72eb12e0189b716d1722d518782afaef7f4fe61",
    	"about" => "undefined",
    	"site" => "http://www.clinique.com/index.tmpl"
    ),
    "Unique Vintage" => array (
    	 "hash" => "e93915b47af820ff3370c7379d0bf4dffdd7e05c",
    	"about" => "undefined",
    	"site" => "http://www.unique-vintage.com"
    ),
    "Zac Posen" => array (
    	 "hash" => "917d4614b1ed36a8bb903106c769db2eae50ce12",
    	"about" => "undefined",
    	"site" => "http://www.zacposen.com/"
    ),
    "Yves Saint Laurent" => array (
    	 "hash" => "03511c1f302e605232f0d8762815d04c0d0388d8",
    	"about" => "The exceptional legacy of Yves Saint Laurent has a contemporary identity  forged through innovative collections that marry elegance, refinement, French chic and timeless style.",
    	"site" => "http://www.ysl.com/en_US"
    ),
    "Revlon" => array (
    	 "hash" => "13a62766109e9c0bdcab5d0bc17e0749f90fe407",
    	"about" => "Revlon is a world leader in cosmetics, fragrance and personal care and is a leading mass market cosmetics brand.\n
    \n
    Vision: Glamour, Excitement, and Innovation through High-quality Products at Affordable Prices.",
    	"site" => "http://www.revlon.com/#/5"
    ),
    "Tory Burch" => array (
    	 "hash" => "c328c9e4a391118eb0ebe9970ef5d2170cb85b81",
    	"about" => "Tory Burch is an attainable, luxury lifestyle brand defined by classic American sportswear with an eclectic sensibility. It embodies the personal style and spirit of its CEO, Tory Burch.",
    	"site" => "http://www.toryburch.com"
    ),
    "Wet Seal" => array (
    	 "hash" => "8a19c5b93641ee4baaf0922ea65c6f7ac44c80b1",
    	"about" => "Wet Seal is a leading specialty retail brand offering current, wear-now fashion. The merchandise assortment, crossing several categories including apparel, accessories, shoes and home goods, is trendy, aspirational and sexy.",
    	"site" => "http://wetseal.com/home.jsp"
    ),
    "L'Oreal" => array (
    	 "hash" => "65cfb3a2b98ff5ed22538e39a3d6b630bb299cf2",
    	"about" => "Our signature phrase, "Because I'm Worth It", is meant to inspire each and every woman to embrace her own unique beauty and reinforce her sense of self-worth.\n
    \n
    We believe that everyone should have the ability to express themselves. That's why we are committed to creating the most groundbreaking, high-quality, yet inexpensive beauty products for all ages and ethnicities.",
    	"site" => "http://www.lorealparisusa.com/_us/_en/default.aspx"
    ),
    "Theory" => array (
    	 "hash" => "3e96732953d05ea77b143eaa595481da34c0cb38",
    	"about" => "Theory 1. Theory is a company, a concept, a philosophy, an aesthetic, a style, and a product 2. Theory is a phenomenon that spun out of great fitting pants 3. Theory is a brand that doesn't look to the future- Theory creates the future",
    	"site" => "http://www.theory.com/"
    ),
    "Sonia Rykiel" => array (
    	 "hash" => "9dc8d09194f559b2c6d8d314ba6dadc037b93374",
    	"about" => "Rykiel… Six letters that are as snappy as a slogan spelled out in strass. It is the emblem of a love story begun in the whirlwind of an extraordinary Spring, which continues to this day. In May 1968, Sonia Rykiel founded her label and opened a first boutique on the rue de Grenelle, in Paris.",
    	"site" => "http://soniarykiel.com/en.html"
    ),
    "Rachel Roy" => array (
    	 "hash" => "0933049be6c593d7f0f68b26c20bc0fcf199aad8",
    	"about" => "undefined",
    	"site" => "http://www.rachelroy.com/"
    ),
    "Ralph Lauren" => array (
    	 "hash" => "c8e07102fff99531c26ad3fee3a8f5ad8d1ce11e",
    	"about" => "Since 1967, Ralph Lauren has defined the essence of American style while elevating it to new heights of luxury. Striking a balance between "timeless" and "modern," Ralph Lauren creates collections that express a unique sense of personal style inspired by the rich visual imagery around him: the rustic beauty of the American West, the golden age of Hollywood glamour, the sleek innovation of automotive design or an authentic equestrian heritage.",
    	"site" => "http://www.RalphLauren.com"
    ),
    "Max & Cleo" => array (
    	 "hash" => "80a5336a522b0973bdf0fb2c3655b5c0991469cb",
    	"about" => "undefined",
    	"site" => "http://www.maxandcleousa.com/"
    ),
    "Hanky Panky" => array (
    	 "hash" => "6b96f53d99757289863f009070cd5ac4919ddee3",
    	"about" => "Blending traditional with modern glam looks, Hanky Panky regularly appears in magazines and is a fashion favorite of countless celebrities.\n
    \n
    Hanky Panky continues its dedication to comfort, fit and quality. "Feel how comfortable sexy can be!®"",
    	"site" => "http://www.hankypanky.com/"
    ),
    "Elizabeth and James" => array (
    	 "hash" => "e1c236bca641c0563cfb3b5d4b633f51054d7e4b",
    	"about" => "Elizabeth and James is a modern lifestyle brand for a new generation. Co-designers Ashley Olsen and Mary-Kate Olsen seek to narrow the gap between designer and contemporary fashion. Encompassing women's wear, shoes, jewelry and eyewear, Elizabeth and James embodies an eclectic lifestyle by blending uptown and downtown elements with casual and traditional styles.",
    	"site" => "http://elizabethandjames.us/"
    ),
    "Elie Tahari" => array (
    	 "hash" => "bf53eab481ebf7a390abc97c41abeef97981a630",
    	"about" => "Our mission is to produce clothing of the finest quality and attention to detail for customers looking for fashion and value in luxury ready-to-wear.",
    	"site" => "http://www.elietahari.com/"
    ),
    "Calvin Klein" => array (
    	 "hash" => "aaa8d6c3c524335381102df180c09e552a61faf5",
    	"about" => "undefined",
    	"site" => "http://www.calvinklein.com/home/index.jsp"
    ),
    "BCBGMAXAZRIA" => array (
    	 "hash" => "673c541f4c9a02318019ce780cc8e3649c3493c4",
    	"about" => "Always on the forefront of fashion, BCBGMAXAZRIA is the premier lifestyle collection for the modern woman. Reconciling creativity with accessibility and desirability with wearability, BCBGMAXAZRIA occupies a unique position in American fashion, offering sophisticated, confident designs that take consumers from work to weekend in style.",
    	"site" => "http://www.bcbg.com"
    ),
    "Shoshanna" => array (
    	 "hash" => "8f6b54fdd600ff9e97122595f2c2ffc6cc428ce1",
    	"about" => "Inspired by Shoshanna's own frustration bikini-shopping for her shapelier figure, this revolutionary system accommodates all different body types and proportions.",
    	"site" => "http://shoshanna.com/"
    ),
    "French Connection" => array (
    	 "hash" => "b16f4f3e8772d5cddc6290c72c98395ee2676a39",
    	"about" => "Founded in 1972 by Stephen Marks, French Connection set out to create well-designed fashionable clothing that appealed to a broad market.",
    	"site" => "http://usa.frenchconnection.com/index.aspx?mscsmigrated=true"
    ),
    "Rampage" => array (
    	 "hash" => "9c1a6701dc5136a52ff239b94ebdce4a541b621d",
    	"about" => "Fashion-forward young women have chosen the Rampage brand to fill their wardrobes, keeping them looking sexy while remaining price-conscious. Rampage appeals to the women who can go from work to the club, as it successfully straddles the line between both work-appropriate and nightclub-ready apparel.",
    	"site" => "http://rampage.com/"
    ),
    "The North Face" => array (
    	 "hash" => "7c58fcf7b7ff08bafafa513af48f9d9d9632e810",
    	"about" => "Never stop exploring. We are named for the coldest, most unforgiving side of a mountain. We have helped explorers reach the most unfathomable heights of the Himalayas. But The North Face® legend begins, ironically, on a beach. More precisely, San Francisco's North Beach neighborhood, at an altitude of only 150 feet above sea level. It was here in 1966 that two hiking enthusiasts resolved to follow their passions and founded a small mountaineering retail store.",
    	"site" => "http://www.thenorthface.com/en_US/"
    ),
    "Betsey Johnson" => array (
    	 "hash" => "c1da88e782f31d00c61264164a161183f2e3b75b",
    	"about" => "\"Making clothes involves what I like…color, pattern, shape and movement…I like the everyday process…the people, the pressure, the surprise of seeing the work come alive walking and dancing around on strangers. Like red lipstick on the mouth, my products wake up and brighten and bring the wearer to life…drawing attention to her beauty and specialness…her moods and movements…her dreams and fantasies.\" Betsey Johnson",
    	"site" => "http://www.betseyjohnson.com/home/index.jsp"
    ),
    "Citizens of Humanity" => array (
    	 "hash" => "7c59dc84e250b1208464b1d44346ab36764e2a9d",
    	"about" => "undefined",
    	"site" => "http://citizensofhumanity.com/"
    ),
    "Torrid.com" => array (
    	 "hash" => "a86271bff476d4d6958caccd66f74041263ec89f",
    	"about" => "Our mission is to provide FASHION for our curvy fashionistas!  Torrid is the Destination for trendy plus-size fashion and accessories.",
    	"site" => "http://www.torrid.com/torrid/Homepage.jsp"
    ),
    "Lacoste" => array (
    	 "hash" => "7bceab14f03e687b5b82eb1b1ce821cb7af9b3dd",
    	"about" => "Lacoste is a lifestyle brand, born of the inventiveness of a tennis champion, René Lacoste, who created the first polo shirt ever, initially for himself and for his friends, to be both relaxed and elegant on and off the tennis courts.",
    	"site" => "http://www.lacoste.com/"
    ),
    "Hard Tail" => array (
    	 "hash" => "de92c18b18218528ba2871abba6aea22c6066e9f",
    	"about" => "Founded in Santa Monica, California, in 1991, by Dick Cantrell, this premium sportswear and denim fashion house stands out in the crowd because of its delicious color palette and signature design elements.  Hard Tail was conceived on the notion of premium tee-shirts with tattoo-inspired designs evoking that inner rockstar. The evolution of mobility, spirit and color had begun. In 2004, the company began manufacturing a high-end denim line built on the same tenants of quality, style and comfort—you really want to live in these jeans.",
    	"site" => "http://www.hardtailforever.com/"
    ),
    "Rebecca Minkoff" => array (
    	 "hash" => "6c801c0ecceef1cbef1aae11b16e3603082cf40d",
    	"about" => "An industry leader in casual luxury handbags, accessories, and apparel, Rebecca Minkoff's playful and subtly edgy designs can be spotted on girls everywhere from downtown to uptown, in the US and abroad.",
    	"site" => "http://rebeccaminkoff.com/"
    ),
    "Adidas" => array (
    	 "hash" => "f33acb080c43f9cf87ee5cec1ae3a9953b9d1e9d",
    	"about" => "In 2012, the brand with the 3-Stripes shows its unwavering love for the game. From the World Cup pitches to the Olympic bobsleigh ice tracks, from the swagger of the sidewalk to the strut of the catwalk, from the NBA All Stars to the concert stages, adidas supports and encourages the love of the game – no matter the game.",
    	"site" => "http://www.adidas.com/us/homepage.asp"
    ),
    "Paige Denim" => array (
    	 "hash" => "c148656272218a197fe5541e33c42d6597c529ee",
    	"about" => "Known for its considered and unexpected details, Paige has grown into a denim powerhouse offering styles that reflect the brand's sex appeal and passion for the craft. Paige uses only the finest fabrics and materials while each design is infused with thought out and considered elements. As the expert on fit, Paige promises that every style delivers a drop dead fit.",
    	"site" => "http://www.paigeusa.com/"
    ),
    "Wildfox" => array (
    	 "hash" => "d3e33ec72408bd8355f131bf50b4bd41de3f8089",
    	"about" => "Musician Jimmy Sommers and co-designers Kimberley Gordon and Emily Faulstich established Wildfox Couture in Los Angeles in 2007. Known for its soft fabrics and unique designs, the line has progressed into a full knit range of tops, bottoms, dresses, scarves, socks, and denim.",
    	"site" => "http://www.wildfoxcouture.com/"
    ),
    "Jessica Simpson" => array (
    	 "hash" => "f16020251436e6ea9cefab432b5555556c981a80",
    	"about" => "The collection is inspired and designed in collaboration with Jessica Simpson. The products celebrate her iconic, American image that is fashion-forward, accessible, comfortable and timeless\n
    \n
    American and feminine, forward but classically familiar, approachable yet aspirational, sexy yet sweet, flirtatious and whimsical, vintage at times, but always of the moment.",
    	"site" => "http://www.jessicasimpsoncollection.com/"
    ),
    "Nine West" => array (
    	 "hash" => "5453f4b5ebaa550c49d094fe256a9befda46f630",
    	"about" => "Nine West is a world-renowned fashion leader offering the must-have trends of the season. Affordable chic.",
    	"site" => "http://www.ninewest.com/"
    ),
    "Rebecca Taylor" => array (
    	 "hash" => "0710619b77b98000fff88e94b1c8a5f87d0dfef0",
    	"about" => "Rebecca Taylor is not just a lifestyle... but a state of mind.  Urban, feminine, bold, kittenish, modern, chic, sexy, cool... with a touch of sparkle. Rebecca Taylor's flirty, modern designs have inspired legions of loyal customers and celebrity clients to indulge their feminine wiles.",
    	"site" => "http://www.rebeccataylor.com/"
    ),
    "Nanette Lepore" => array (
    	 "hash" => "f795417a80f3cb2045945533a7292f5514ad3b62",
    	"about" => "Nanette Lepore - fashion designer known for chic and casual women's collections. since 1992.",
    	"site" => "http://www.nanettelepore.com/"
    ),
    "Michael Kors" => array (
    	 "hash" => "4162d9d71c035bfffb34fd5e75c7ac747624c6bf",
    	"about" => "Michael Kors is a world-renowned, award-winning designer of luxury accessories and ready to wear.",
    	"site" => "http://www.michaelkors.com/"
    ),
    "Cole Haan" => array (
    	 "hash" => "b1727f495a20e714023d3a28d05d11b06a98f3e1",
    	"about" => "Shaped by over a century of craftsmanship, innovation and style, the Cole Haan collection offers something for everyone: premium footwear, accessories and outerwear for men and women.",
    	"site" => "http://www.colehaan.com"
    ),
    "Chinese Laundry" => array (
    	 "hash" => "76bd7682365ce524d39825b7cc3dc6eb67992852",
    	"about" => "Chinese Laundry is the perfect expression of its signature combination of outstanding quality and value with a unique and inspired point of view. From stylish daytime looks in innovative fabrics and leathers to evening collections in eye-catching metallics and satins, Chinese Laundry consistently provides a mix of styles and trends that are ideal for today's fashion landscape.",
    	"site" => "http://www.chineselaundry.com"
    ),
    "Rachel Zoe" => array (
    	 "hash" => "49f562500b52de55ede044c15b4cd7fadada6fab",
    	"about" => "undefined",
    	"site" => "http://www.thezoereport.com/"
    ),
    "Trina Turk" => array (
    	 "hash" => "6ace6390d77845212a13470b9e6ba9d9ec447977",
    	"about" => "Trina Turk is a lifestyle brand, inspired by the multicultural mix, architecture and landscape of Los Angeles and California. Trina's philosophy is to create wearable, optimistic fashion that incorporates the best aspects of classic American sportswear.",
    	"site" => "http://www.trinaturk.com/index.aspx"
    ),
    "Caparros" => array (
    	 "hash" => "1392554c39ccddf641e67acaa9fa3c1cf8e43d45",
    	"about" => "Caparros has built a reputation for designing unique, captivating dress shoes full of vibrant color and embellishment for everything from weddings and chic proms, to evening events and life-defining occasions. Along the way, Caparros has attracted a loyal following of women who appreciate styles that easily transition from day-into-nightlife.",
    	"site" => "http://www.caparrosshoes.com/home.aspx"
    ),
    "Ella Moss" => array (
    	 "hash" => "4eca7c8650a7640b661eeda0ae94e81d4b607d02",
    	"about" => "Known for bright color palettes, simple shapes, soft, wearable cottons and tonal stripes, Ella Moss strikes a delicate balance of being edgy and vintage, without being over-the-top trendy.",
    	"site" => "http://www.ellamoss.com/"
    ),
    "J Brand" => array (
    	 "hash" => "05a0e21c6ca65ba14099b7fd2d489b17c218e861",
    	"about" => "J BRAND set out to create classic and sophisticated jeans with the emphasis on fit — and one mandate: create timeless products.  Fashion leaders making a difference - we create style that excites your life.",
    	"site" => "http://www.jbrandjeans.com/"
    ),
    "Hot Topic" => array (
    	 "hash" => "ff4c220ce478a4dceaa573225fe252e04ee66c1d",
    	"about" => "At Hot Topic, you'll find a passion for music and pop culture in everything we do, and you'll see that our customers share that same passion.",
    	"site" => "http://www.hottopic.com/hottopic/Homepage.jsp"
    ),
    "Joie" => array (
    	 "hash" => "1f4f4a9cd89ccddd4e70c484be4508ae1380f0c2",
    	"about" => "The JOIE collection is understatedly chic. Constantly inspired by Southern California, its casual yet sophisticated way of life is translated directly into JOIE designs. The JOIE girl enjoys wearing casual, comfortable clothes accented by luxurious fabrics and details inspired by her travel throughout the world. Both modern and timeless in its appeal, the JOIE aesthetic draws its influence from vintage creations while successfully maintaining a fresh approach to fashion.",
    	"site" => "http://www.joie.com"
    ),
    "Juicy Couture" => array (
    	 "hash" => "2d8c3ac0e617796546716aee53f07bf6e8b10817",
    	"about" => "Juicy Couture is a glamorous, irreverent and fun lifestyle brand for the decidedly fashionable.  Known for ascending the track suit to its status as a casual luxury icon, Juicy Couture continues to evolve, bringing the same confident, whimsical and feminine attitude to all its designs.",
    	"site" => "http://www.juicycouture.com"
    ),
    "Frye" => array (
    	 "hash" => "1efa4e209ec73c889c0c0cf8a4d19a8342fcae8f",
    	"about" => "The Frye brand remains true to its heritage and vintage American roots with finely crafted, fashionable boots, shoes, and leather goods featuring rich leathers and quality hardware.",
    	"site" => "http://www.thefryecompany.com/"
    ),
    "Joe's Jeans" => array (
    	 "hash" => "a709b18469721c631cc4c0f34c4113cbf4904576",
    	"about" => "Celebrating over a decade as a leader in the premium denim market, Joe's is best known for pioneering the concept of fits catered to specific body types. Joe's innovative take on denim fits has garnered the brand a loyal fan following of women and celebrity fans alike.",
    	"site" => "http://www.joesjeans.com"
    ),
    "True Religion" => array (
    	 "hash" => "942aa13b968de20b345f62d4374d3375b2733800",
    	"about" => "True Religion offers a wide range of styles in nearly every category and embraces the motto: "It's all about the fit." True Religion clothing is made for and by people who don't follow trends, they set them.",
    	"site" => "http://www.truereligionbrandjeans.com/"
    ),
    "Kate Spade" => array (
    	 "hash" => "424faee86b927bbf22b91cc9c214a558cfff31d4",
    	"about" => "Utility, wit and playful sophistication are the hallmarks of Kate Spade New York. As our world expands, our graceful, exuberant approach to the everyday is evident in every category we enter, from handbags and clothing to jewelry, shoes, stationery, glasses, baby and home.",
    	"site" => "http://www.katespade.com/"
    ),
    "Michael Stars" => array (
    	 "hash" => "a4ffb199dda03c10540dd3c2cac413777cf4a997",
    	"about" => "Los Angeles-based Michael Stars has come a long way since it founded the \"original tee\". The California-chic brand now offers contemporary women a complete collection of head-to-toe looks including: tees, casual sportswear, dresses, twill, linen, sweaters and accessories. From top fashion magazines to celebrity closets, Michael Stars is spreading \"Casual Luxury\" around the world.",
    	"site" => "http://www.michaelstars.com"
    ),
    "Splendid" => array (
    	 "hash" => "a1842fee6a1e1dc5e61043a3ded0444f8cea1e36",
    	"about" => "Founded in 2002, Splendid is the culmination of a ten year tireless search to find the softest fabric and most color absorbing yarns in the world in order to create the ultimate t-shirt.",
    	"site" => "http://www.splendid.com"
    ),
    "Steve Madden" => array (
    	 "hash" => "7a8a3af2f0adc00d314427085c39a4e6660939ba",
    	"about" => "Steve Madden's vision is to give young, fashion-forward women a unique way to express their individuality through style.",
    	"site" => "http://www.stevemadden.com/"
    ),
    "James Jeans" => array (
    	 "hash" => "8aa250f57af266937027a163b85f1207258c9b4f",
    	"about" => "Cult favorite denim for its most amazing fit with a strong focus on providing a fit that complements all body types and all ways of life.",
    	"site" => "http://www.jamesjeans.us/"
    ),
    "Lucky Brand" => array (
    	 "hash" => "bdfb4fece7706d43d3fdbb535545cf0cd0f821d0",
    	"about" => "We crafted our first jeans in Los Angeles in 1990 with this philosophy in mind. And we've been making vintage-inspired, great fitting denim for expressive, independent types ever since.",
    	"site" => "http://www.luckybrand.com"
    ),
    "Gap" => array (
    	 "hash" => "8230532c8c2fd99f0903ec4390b94a9718e2940c",
    	"about" => "Gap was founded in 1969 with a single store in San Francisco. Now we have thousands of stores across the world and we are committed to bringing you accessible style.",
    	"site" => "http://www.gap.com/"
    ),
    "Old Navy" => array (
    	 "hash" => "b24ddf78e50648da9c37f395e573b4844cf081f4",
    	"about" => "Old Navy brings serious fashion fun to the whole family. We've got it all, from trendy threads to barely-basic basics, for everyone from newborns to adults. At prices that are oh-so-right!",
    	"site" => "http://www.oldnavy.com"
    ),
    "Free People" => array (
    	 "hash" => "bde6ad8c449af05ef53b55a8e2e5f1b0edcaf96c",
    	"about" => "She is a free spirit...wakes up to see the sun shine.  Stays up to catch a falling star...she is our free people girl.  And she is the reason we do what we do.",
    	"site" => "http://www.freepeople.com/"
    ),
    "Dolce Vita" => array (
    	 "hash" => "f465d0a074c75c7f67b79a9fb57d6cc444394e4d",
    	"about" => "Dolce Vita's nonchalant attitude towards fashion resulted in footwear and clothing lines that are effortlessly stylish yet delightfully flirty.",
    	"site" => "http://www.dolcevita.com/"
    ),
    "American Eagle Outfitters" => array (
    	 "hash" => "efad132b264c01ea1b99cbc4084a6921517b9e54",
    	"about" => "American Eagle Outfitters is the crossroads where American prep meets current fashion. While our heritage is based in denim, we also offer other high-quality, on-trend clothing and accessories at affordable prices. American Eagle style is eternal. Live your life.",
    	"site" => "http://www.ae.com/web/index.jsp"
    ),
    "Nike" => array (
    	 "hash" => "157c47f78a863f4d3eca39baba6d0a8a4a428f91",
    	"about" => "Our Mission: To bring inspiration and innovation to every athlete in the world. If you have a body, you are an athlete.",
    	"site" => "http://store.nike.com/us/en_us/?sitesrc=uslp"
    ),
    "Vans" => array (
    	 "hash" => "42201ca1e9882959d75d4904b62f5d4a5829653e",
    	"about" => "Vans was founded in 1966 by Paul and James Van Doren, Serge Delia, and Gordon Lee. It has stood for authenticity in youth lifestyle, music and action sports since day one.",
    	"site" => "http://www.vans.com/"
    ),
    "dELiA*s" => array (
    	 "hash" => "d616563aca66d18e4fd7359b52cfa1541b7f52b2",
    	"about" => "dELiA*s offers hip fashion for the teen girl who loves to look pretty. We are the denim destination, known for having a perfect fit and offering the latest styles in tons of sizes and lengths. Our girl wants to be herself—genuine and upbeat—and we couldn't agree more.",
    	"site" => "http://store.delias.com"
    ),
    "Aeropostale" => array (
    	 "hash" => "5bc3eeaf746f21fca1703f9dae6d05eab14df5e3",
    	"about" => "Aéropostale , Inc. is a mall-based, specialty retailer of casual apparel and accessories, principally targeting 14 to 17 year-old young women and men.",
    	"site" => "http://www.aeropostale.com/shop/index.jsp?categoryId=3534619"
    ),
    "Bebe" => array (
    	 "hash" => "7230540cbf5ea9e04e80722891d3a7932f715a54",
    	"about" => "Modern. Feminine. Sophisticated. With its distinct line of contemporary women's apparel and accessories, bebe is the brand for women who seek trend-forward and expressive style. It's for those who are defined by a confident and discerning attitude—and who seek fashion that mirrors this mindset.",
    	"site" => "http://www.bebe.com"
    ),
    "XOXO" => array (
    	 "hash" => "0bc235ed00d8ef683579caf8d99d224d80530727",
    	"about" => "XOXO sets the latest trends and is willing to take fashion risks in order to do so. XOXO appeals to women who are "in the know" and who seek runway looks to compliment their lifestyle at a compelling value.",
    	"site" => "http://www.xoxo.com/home.html"
    ),
    "Pacific Sunwear" => array (
    	 "hash" => "2d5731186616298cfefeec82e81f67c7ad049ee5",
    	"about" => "We started as a little surf shop in Newport Beach in 1980, and we're now one of the top names in teen fashion with over 800 stores in 50 states and Puerto Rico. As we've grown, our focus has remained: stay true to our roots in youth culture and offer what's next now.",
    	"site" => "http://shop.pacsun.com/home.jsp"
    )

    );

    /**
     * repo
     */
    protected $repo;

    /**
     * configure
     */
    protected function configure()
    {
        $this
            ->setName('seed:brand:info')
            ->setDescription('Give brand/merchant users our already-uploaded avatars, about and site data')
            ->setDefinition(array(
            ));
    }

    /**
     * execute
     *
     * @param InputInterface  $input  instance
     * @param OutputInterface $output instance
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $this->dm = $this->getContainer()
            ->get('doctrine_mongodb.odm.document_manager');

        $assetProvider = $this->getContainer()->get('pw.asset');
        $assetRepo = $this->dm->getRepository('PWAssetBundle:Asset');
        $userRepo = $this->dm->getRepository('PWUserBundle:User');

        $missingNames = $missingAssets = array();
        foreach ($this->info as $name => $details) {
            $hash = $details['hash'];
            $site = $details['site'];
            $about = $details['about'];

            $user = $userRepo->createQueryBuilder()
                ->field('name')->equals($name)
                ->getQuery()->execute()->getSingleResult();
            if (!$user) {
                $missingNames[] = $name;
                continue;
            }

            $asset = $assetRepo->findOneBy(array('hash' => $hash));
            if (!$asset) {
                $asset = $assetProvider->addImageFromUrl("http://i.plumwillow.com/assets/$hash.jpg");
                if (!$asset) {
                    $missingAssets[] = $name;
                    continue;
                }
                $asset->setUrl($asset->getSourceUrl());
                $this->dm->persist($asset);
            }

            $user->setIcon($asset);

            $user->setAbout($about);
            $user->setWebsiteUrl($site);

            $this->dm->persist($user);
            $output->write("\t$name\n");
        }
        $this->dm->flush();

        if ($missingNames) {
            $output->write("\nThe following users were not found\n");
            $output->write("\t" . implode($missingNames, "\n\t") . "\n");
        }

        if ($missingAssets) {
            $output->write("\nThe following had missing assets\n");
            $output->write("\t" . implode($missingAssets, "\n\t") . "\n");
        }
    }
}


text:
package teams.migration;

import org.hibernate.engine.spi.CacheImplementor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import teams.provision.UserDetailsManager;
import teams.repository.PersonRepository;
import teams.repository.TeamRepository;

import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

@RestController
public class MigrationService {

  private static final Logger LOG = LoggerFactory.getLogger(MigrationService.class);
  public static final String UNKNOWN = "UNKNOWN_ATTRIBUTE";

  private final JdbcMigrationDao migrationDao;
  private final TeamRepository teamRepository;
  private final PersonRepository personRepository;
  private final UserDetailsManager userDetailsManager;
  private final String secretKey;
  private final JdbcTemplate jdbcTemplate;

  @Autowired
  public MigrationService(JdbcMigrationDao migrationDao,
                          TeamRepository teamRepository,
                          PersonRepository personRepository,
                          UserDetailsManager userDetailsManager,
                          @Value("${migration.secret_key}") String secretKey,
                          @Qualifier("teamsDataSource") DataSource teamsDataSource) {
    this.migrationDao = migrationDao;
    this.teamRepository = teamRepository;
    this.personRepository = personRepository;
    this.userDetailsManager = userDetailsManager;
    this.secretKey = secretKey;
    this.jdbcTemplate = new JdbcTemplate(teamsDataSource);
  }

  @GetMapping("migrate")
  @Transactional
  public ResponseEntity migrate(@RequestParam(name = "key") String key) {
    if (!secretKey.equals(key)) {
      return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
    long start = System.currentTimeMillis();
    LOG.info("Starting migration");

    //idempotent
    deleteFromTable("memberships");
    deleteFromTable("persons");
    deleteFromTable("teams");

    long startDao = System.currentTimeMillis();
    LOG.info("migrationDao.findAllTeamsAndMemberships starting ");

    //all non-persistent teams fully populated with memberships and persons
    Collection<Team> teams = migrationDao.findAllTeamsAndMemberships();

    Set<Person> persons = teams.stream().map(team -> team.getMemberships().stream().map(membership -> membership.getPerson()))
      .flatMap(Function.identity())
      .collect(toSet());

    LOG.info("migrationDao.findAllTeamsAndMemberships found {} teams with total {} members", teams.size(), persons.size());
    LOG.info("migrationDao.findAllTeamsAndMemberships ended in {} ms", System.currentTimeMillis() - startDao);

    //now fetch all the details from the LDAP and enrich the person references
    long startLdap = System.currentTimeMillis();
    LOG.info("migrationDao.addingLdapDetails starting ");

    persons.forEach(this::addDetails);

    Map<Boolean, List<Person>> grouped = persons.stream().collect(Collectors.groupingBy(person -> person.getEmail() != null && person.getName() != null));
    List<Person> personsPresentInLdap = grouped.get(true);

    LOG.info("migrationDao.addingLdapDetails ended in {} ms", System.currentTimeMillis() - startLdap);

    long startDatabase = System.currentTimeMillis();
    LOG.info("migrationDao.saving all persons and teams starting ");

    personsPresentInLdap.forEach(person -> {
      LOG.info("Saving person {} {} {}", person.getId(), person.getEmail(), person.getName());
      personRepository.save(person);
      LOG.info("Saved person {} {} {}", person.getId(), person.getEmail(), person.getName());
    });

    teams.forEach(team -> {
      LOG.info("Saving team {} {} {}", team.getId(), team.getName(), team.getMemberships().stream().map(membership -> membership.getPerson()).collect(toList()));
      teamRepository.save(team);
      LOG.info("Saved team {} {} {}", team.getId(), team.getName(), team.getMemberships().stream().map(membership -> membership.getPerson()).collect(toList()));
    });

    LOG.info("migrationDao.saving all persons and teams ended in {} ms", System.currentTimeMillis() - startDatabase);

    LOG.info("total migration took {} ms", System.currentTimeMillis() - start);

    return ResponseEntity.ok(grouped.get(false));
  }

  private void addDetails(Person person) {
    Optional<Person> personOptional = userDetailsManager.findPersonById(person.getUrn());
    if (personOptional.isPresent()) {
      fillDetailsPerson(person, personOptional);
    } else {
      person.setGuest(true);
      person.setName(UNKNOWN);
      person.setEmail(UNKNOWN);
    }
  }

  private void fillDetailsPerson(Person person, Optional<Person> personOptional) {
    Person details = personOptional.get();
    String email = details.getEmail();
    person.setEmail(email == null ? UNKNOWN : email);
    person.setGuest(details.isGuest());
    String name = details.getName();
    person.setName(name == null ? UNKNOWN : name);
    person.setCreated(details.getCreated());
  }

  private void deleteFromTable(String table) {
    LOG.info("Deleting from table " + table);
    jdbcTemplate.execute("DELETE FROM " + table);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package core.framework.log;

import core.framework.internal.log.marker.ErrorCodeMarker;
import org.slf4j.Marker;

/**
 * @author neo
 */
public final class Markers {
    public static Marker errorCode(String code) {
        return new ErrorCodeMarker(code);
    }
}


text:
class LogicalModel
  module RESTActions

    def self.included(base)
      base.send(:include, InstanceMethods)
      base.send(:extend, ClassMethods)
    end

    module InstanceMethods

      def create(params={})
        run_callbacks :save do
          run_callbacks :create do
            _create(params)
          end
        end
      end

      def save
        run_callbacks :save do
          run_callbacks new_record?? :create : :update do
            _save
          end
        end
      end

      def destroy(params={})
        run_callbacks :destroy do
          _destroy(params)
        end
      end

      # @param params [Hash] parameters to be sent to service
      def update(params)
        run_callbacks :save do
          run_callbacks :update do
            _update(params)
          end
        end

      end

      #
      # creates model.
      #
      # returns:
      # @return false if model invalid
      # @return nil if there was a connection problem
      # @return created model ID if successfull
      #
      # @example Usage:
      #   @person = Person.new(params[:person])
      #   @person.create( non_attribute_param: "value" )
      def _create(params = {})
        unless params[:ignore_validation]
          return false unless valid?
        end

        params = { self.json_root => self.attributes }.merge(params)
        params = self.class.merge_key(params)

        response = Typhoeus::Request.post( self.class.resource_uri, body: params, timeout: self.class.timeout )
        self.last_response_code = response.code
        if response.code == 201 || response.code == 202
          log_ok(response)
          if self.respond_to?('id=')
            self.id = ActiveSupport::JSON.decode(response.body)["id"]
          else
            true
          end
        elsif response.code == 400
          log_failed(response)
          ws_errors = ActiveSupport::JSON.decode(response.body)["errors"]
          ws_errors.each_key do |k|
            self.errors.add k, ws_errors[k]
          end
          return false
        else
          log_failed(response)
          return nil
        end
      end

      # Updates Objects attributes, this will only send attributes passed as arguments
      #
      #
      # Returns false if Object#valid? is false.
      # Returns updated object if successfull.
      # Returns nil if update failed
      #
      # Usage:
      #   @person.update(params[:person])
      def _update(params)

        self.attributes = params[self.json_root]

        unless params[:ignore_validation]
          return false unless valid?
        end

        params = self.class.merge_key(params)

        response = Typhoeus::Request.put( self.class.resource_uri(id),
                                          params: params,
                                          timeout: self.class.timeout )

        if response.code == 200
          log_ok(response)
          return self
        else
          log_failed(response)
          return nil
        end
      end

      # Saves Objects attributes
      #
      #
      # Returns false if Object#valid? is false.
      # Returns updated object if successfull.
      # Returns nil if update failed
      #
      # Usage:
      #   @person.save
      def _save
        self.attributes = attributes

        return false unless valid?

        sending_params = self.attributes
        sending_params.delete(:id)

        params = { self.json_root => sending_params }
        params = self.class.merge_key(params)
        response = Typhoeus::Request.put( self.class.resource_uri(id), params: params, timeout: self.class.timeout )
        if response.code == 200
          log_ok(response)
          return self
        else
          log_failed(response)
          return nil
        end
      end

      # Destroy object
      #
      # Usage:
      #   @person.destroy
      def _destroy(params={})
        self.class.delete(self.id,params)
      end

    end

    module ClassMethods

      attr_accessor :enable_delete_multiple

      # @param header [Hash]
      def set_default_headers(header)
        @headers = header
      end

      # User specified default headers
      # @return [Hash]
      def default_headers
        @headers
      end

      #  ============================================================================================================
      #  Following methods are API specific.
      #  They assume we are using a RESTfull API.
      #  for get, put, delete :id is expected
      #  for post, put attributes are excepted under class_name directly.
      #    eg. put( {:id => 1, :class_name => {:attr => "new value for attr"}} )
      #
      #  On error (400) a "errors" key is expected in response
      #  ============================================================================================================

      # @param options [Hash] will be forwarded to API
      def async_all(options={})
        options = self.merge_key(options)
        request = Typhoeus::Request.new(resource_uri, params: options, headers: default_headers)
        request.on_complete do |response|
          if response.code >= 200 && response.code < 400
            log_ok(response)

            result_set = self.from_json(response.body)
            collection = result_set[:collection]

            yield collection
          else
            log_failed(response)
          end
        end
        self.hydra.queue(request)
      end

      def all(options={})
        result = nil
        self.retries.times do
          begin
            async_all(options){|i| result = i}
            self.hydra.run
            break unless result.nil?
          end
        end
        result
      end

      # Asynchronic Pagination
      #  This pagination won't block excecution waiting for result, pagination will be enqueued in Objectr#hydra.
      #
      # Parameters:
      #   @param options [Hash].
      #   Valid options are:
      #   * :page - indicated what page to return. Defaults to 1.
      #   * :per_page - indicates how many records to be returned per page. Defauls to 20
      #   * all other options will be sent in :params to WebService
      #
      # Usage:
      #   Person.async_paginate(:page => params[:page]){|i| result = i}
      def async_paginate(options={})
        options[:page] ||= 1
        options[:per_page] ||= 20

        options = self.merge_key(options)

        request = Typhoeus::Request.new(resource_uri, params: options, headers: default_headers)
        request.on_complete do |response|
          if response.code >= 200 && response.code < 400
            log_ok(response)

            result_set = self.from_json(response.body)

            # this paginate is will_paginate's Array pagination
            collection = Kaminari.paginate_array(
                result_set[:collection],
                {
                    :total_count=>result_set[:total],
                    :limit => options[:per_page],
                    :offset => options[:per_page] * ([options[:page], 1].max - 1)
                }
            )

            yield collection
          else
            log_failed(response)
          end
        end
        self.hydra.queue(request)
      end

      #synchronic pagination
      def paginate(options={})
        result = nil
        self.retries.times do
          begin
            async_paginate(options){|i| result = i}
            self.hydra.run
            break unless result.nil?
          end
        end
        result
      end

      # Asynchronic Count
      #  This count won't block excecution waiting for result, count will be enqueued in Objectr#hydra.
      #
      # Parameters:
      #   @param options [Hash].
      #   Valid options are:
      #   @option options [Integer] :page - indicated what page to return. Defaults to 1.
      #   @option options [Integer] :per_page - indicates how many records to be returned per page. Defauls to 20
      #   @option options [Hash] all other options will be forwarded in :params to WebService
      #
      # @example 'Count bobs'
      #   Person.async_count(:when => {:name => 'bob'}}){|i| result = i}
      def async_count(options={})
        options[:page] = 1
        options[:per_page] = 1

        options = self.merge_key(options)

        request = Typhoeus::Request.new(resource_uri, params: options, headers: default_headers)
        request.on_complete do |response|
          if response.code >= 200 && response.code < 400
            log_ok(response)

            result_set = self.from_json(response.body)

            yield result_set[:total]
          else
            log_failed(response)
          end
        end
        self.hydra.queue(request)
      end

      # synchronic count
      def count(options={})
        result = nil
        async_count(options){|i| result = i}
        self.hydra.run
        result
      end

      # Asynchronic Find
      #  This find won't block excecution waiting for result, excecution will be enqueued in Objectr#hydra.
      #
      # Parameters:
      #   - id, id of object to find
      # @param [String/Integer] id
      # @param [Hash] params
      #
      # Usage:
      #   Person.async_find(params[:id])
      def async_find(id, params = {})
        params = self.merge_key(params)
        request = Typhoeus::Request.new( resource_uri(id), :params => params )

        request.on_complete do |response|
          if response.code >= 200 && response.code < 400
            log_ok(response)
            yield async_find_response(id, params, response.body), response.code
          else
            log_failed(response)
            yield nil, response.code
          end
        end

        self.hydra.queue(request)
      end

      def async_find_response(id, params, body)
        if body.blank?
          # if request failed failed unexpectedly we may get code 200 but empty body
          self.logger.warn("got response code 200 but empty body")
          return nil
        end

        self.new.from_json(body)
      end

      # synchronic find
      def find(id, params = {})
        result = nil
        self.retries.times do
          begin
            response_code = nil
            async_find(id, params) do |res,code|
              result = res
              response_code = code
            end
            self.hydra.run
            break unless result.nil? && (response_code != 404) # don't retry if response was 404
          end
        end
        result
      end

      # Deletes Object#id
      #
      # Returns nil if delete failed
      #
      # @param [String] id - id of contact to be deleted
      # @param [Hash] params - other params to be sent to WS on request
      #
      # Usage:
      #   Person.delete(params[:id])
      def delete(id, params={})

        params = self.merge_key(params)

        response = Typhoeus::Request.delete( self.resource_uri(id),
                                             params: params,
                                             timeout: self.timeout
        )
        if response.code == 200
          log_ok(response)
          return self
        else
          log_failed(response)
          return nil
        end
      end

      # Deletes all Objects matching given ids
      #
      # This method will make a DELETE request to resource_uri/destroy_multiple
      #
      # Returns nil if delete failed
      #
      # @param [Array] ids - ids of contacts to be deleted
      # @param [Hash] params - other params to be sent to WS on request
      #
      # Usage:
      #   Person.delete_multiple([1,2,4,5,6])
      def delete_multiple(ids, params={})
        raise "not-enabled" unless self.delete_multiple_enabled?

        params = self.merge_key(params)
        params = params.merge({:ids => ids})

        response = Typhoeus::Request.delete( self.resource_uri+"/destroy_multiple",
                                             params: params,
                                             timeout: self.timeout
        )
        if response.code == 200
          log_ok(response)
          return self
        else
          log_failed(response)
          return nil
        end
      end
    end
  end

  ##
  # Will parse JSON string and initialize classes for all hashes in json_string[collection_key].
  #
  # @param json_string [JSON String] This JSON should have format: {collection: [...], total: X}
  #
  def self.from_json(json_string)
    parsed_response = ActiveSupport::JSON.decode(json_string)
    parsed_collection = collection_key.nil?? parsed_response : parsed_response[collection_key]
    collection = parsed_collection.map{|i| self.new(i)}

    if total_key
      {collection: collection, total: parsed_response[total_key].to_i}
    else
      { collection: collection }
    end
  end

end


text:
package main

import (
	"bytes"
	"io"
	"os/exec"
)

// Jobs are the way plugins can run processes in the background
// A job is simply a process that gets executed asynchronously
// There are callbacks for when the job exits, when the job creates stdout
// and when the job creates stderr

// These jobs run in a separate goroutine but the lua callbacks need to be
// executed in the main thread (where the Lua VM is running) so they are
// put into the jobs channel which gets read by the main loop

// JobFunction is a representation of a job (this data structure is what is loaded
// into the jobs channel)
type JobFunction struct {
	function func(string, ...string)
	output   string
	args     []string
}

// A CallbackFile is the data structure that makes it possible to catch stderr and stdout write events
type CallbackFile struct {
	io.Writer

	callback func(string, ...string)
	args     []string
}

func (f *CallbackFile) Write(data []byte) (int, error) {
	// This is either stderr or stdout
	// In either case we create a new job function callback and put it in the jobs channel
	jobFunc := JobFunction{f.callback, string(data), f.args}
	jobs <- jobFunc
	return f.Writer.Write(data)
}

// JobStart starts a shell command in the background with the given callbacks
// It returns an *exec.Cmd as the job id
func JobStart(cmd string, onStdout, onStderr, onExit string, userargs ...string) *exec.Cmd {
	return JobSpawn("sh", []string{"-c", cmd}, onStdout, onStderr, onExit, userargs...)
}

// JobSpawn starts a process with args in the background with the given callbacks
// It returns an *exec.Cmd as the job id
func JobSpawn(cmdName string, cmdArgs []string, onStdout, onStderr, onExit string, userargs ...string) *exec.Cmd {
	// Set up everything correctly if the functions have been provided
	proc := exec.Command(cmdName, cmdArgs...)
	var outbuf bytes.Buffer
	if onStdout != "" {
		proc.Stdout = &CallbackFile{&outbuf, LuaFunctionJob(onStdout), userargs}
	} else {
		proc.Stdout = &outbuf
	}
	if onStderr != "" {
		proc.Stderr = &CallbackFile{&outbuf, LuaFunctionJob(onStderr), userargs}
	} else {
		proc.Stderr = &outbuf
	}

	go func() {
		// Run the process in the background and create the onExit callback
		proc.Run()
		jobFunc := JobFunction{LuaFunctionJob(onExit), string(outbuf.Bytes()), userargs}
		jobs <- jobFunc
	}()

	return proc
}

// JobStop kills a job
func JobStop(cmd *exec.Cmd) {
	cmd.Process.Kill()
}

// JobSend sends the given data into the job's stdin stream
func JobSend(cmd *exec.Cmd, data string) {
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return
	}

	stdin.Write([]byte(data))
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

namespace Crevice4Tests
{
    using Crevice.Config;
    using Crevice.UserScript;

    [TestClass()]
    public class UserScriptTests
    {
        [ClassInitialize()]
        public static void ClassInitialize(TestContext context)
        {
            TestHelpers.TestDirectoryMutex.WaitOne();
            Directory.CreateDirectory(TestHelpers.TemporaryDirectory);
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            if (Directory.Exists(TestHelpers.TemporaryDirectory))
            {
                Directory.Delete(TestHelpers.TemporaryDirectory, recursive: true);
            }
            TestHelpers.TestDirectoryMutex.ReleaseMutex();
        }

        [TestMethod()]
        public void ParseScriptTest()
        {
            var globalConfig = new GlobalConfig();
            var userScriptString = "dummy_script";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            Assert.AreEqual(parsedScript.Code, userScriptString);
            Assert.AreEqual(parsedScript.GlobalsType.Name, "UserScriptExecutionContext");
            Assert.AreEqual(parsedScript.GlobalsType.FullName, "Crevice.UserScript.UserScriptExecutionContext");
            Assert.IsTrue(parsedScript.Options.MetadataReferences.Any(v => v.Display.Contains("mscorlib.dll")));
            Assert.IsTrue(parsedScript.Options.MetadataReferences.Any(v => v.Display.Contains("System.dll")));
            Assert.IsTrue(parsedScript.Options.MetadataReferences.Any(v => v.Display.Contains("System.Core.dll")));
            Assert.IsTrue(parsedScript.Options.MetadataReferences.Any(v => v.Display.Contains("crevice4.exe")));
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript0_0Test()
        {
            var globalConfig = new GlobalConfig();
            var userScriptString = "var hoge = 1;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() == 0);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript0_1Test()
        {
            // When the user script containing dynamic expression is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "dynamic hoge = 1;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() == 0);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript0_2Test()
        {
            // When the user script which defines a mouse gesture is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "var Whenever = When((ctx) => {return true;});";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() == 0);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript0_3Test()
        {
            // When the user script which using CreviceApp API is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "using static Crevice.WinAPI.Constants.WindowsMessages;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() == 0);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript0_4Test()
        {
            // When the user script containing a error is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "undefined_variable";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() > 0);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript1_0Test()
        {
            var globalConfig = new GlobalConfig();
            var userScriptString = "var hoge = 1;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript1_1Test()
        {
            // When the user script containing dynamic expression is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "dynamic hoge = 1;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript1_2Test()
        {
            // When the user script which defines a mouse gesture is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "var Whenever = When((ctx) => {return true;});";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        public void CompileAndEvaluateUserScript1_3Test()
        {
            // When the user script which using CreviceApp API is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "using static Crevice.WinAPI.Constants.WindowsMessages;";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        [ExpectedException(typeof(UserScript.EvaluationAbortedException))]
        public void CompileAndEvaluateUserScript1_4Test()
        {
            // When the user script containing a error is given.
            var globalConfig = new GlobalConfig();
            var userScriptString = "undefined_variable";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        [TestMethod()]
        [ExpectedException(typeof(UserScript.EvaluationAbortedException))]
        public void CompileAndEvaluateUserScript_AnbiguousOnOnDecomposed_Test()
        {
            // When the user script containing a error is given.
            var globalConfig = new GlobalConfig();
            var userScriptString =
                "var Never = When(ctx => { return false; });" +
                "Never.On(Keys.RButton);" +
                "Never.OnDecomposed(Keys.RButton);";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var userScriptCache = UserScript.CompileUserScript(parsedScript);
            var ctx = new UserScriptExecutionContext(globalConfig, null);
            UserScript.EvaluateUserScript(ctx, parsedScript);
        }

        public class SynchronizeInvokeMock : System.ComponentModel.ISynchronizeInvoke
        {
            public bool InvokeRequired
            {
                get { return true;  }
            }

            public IAsyncResult BeginInvoke(Delegate method, object[] args)
            {
                return Task.Run(() => {
                    method.DynamicInvoke(args);
                });
            }

            public object EndInvoke(IAsyncResult result)
            {
                return Task.Run(() => {});
            }

            public object Invoke(Delegate method, object[] args)
            {
                return new object();
            }
        }

        [TestMethod()]
        public void WatcherTest()
        {
            var tempDir = TestHelpers.GetTestDirectory();
            var mock = new SynchronizeInvokeMock();
            var watcher = new UserScript.DirectoryWatcher(mock, tempDir, "*.csx");
            var watcherTestfile = Path.Combine(tempDir, "watcher_test.csx");
            var countdownEvent = new CountdownEvent(1);
            watcher.Created += new FileSystemEventHandler((s, e) =>
            {
                countdownEvent.Signal();
            });
            watcher.EnableRaisingEvents = true;
            Task.Run(() =>
            {
                File.WriteAllText(watcherTestfile, "watcher test text");
            });
            countdownEvent.Wait(TimeSpan.FromSeconds(4));
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
        }

        [TestMethod()]
        public void GetPrettyTextTest()
        {
            var globalConfig = new GlobalConfig();
            var userScriptString = @"
var hoge = 1;

void foo()
{
  undefined_variable
}

";
            var parsedScript = UserScript.ParseScript(userScriptString, globalConfig.UserDirectory, globalConfig.UserDirectory);
            var errors = UserScript.CompileUserScript(parsedScript);
            Assert.IsTrue(errors.Count() > 0);
            var prettyText = UserScript.GetPrettyErrorMessage(errors);

            Assert.AreEqual(prettyText, @"--------------------------------------------------------------------------------
[Compiler Error] CS1002

; expected

Line 5, Pos 20
==========
0|
1|var hoge = 1;
2|
3|void foo()
4|{
5|  undefined_variable
                      ~
6|}
7|
8|
[EOF]
==========
--------------------------------------------------------------------------------
");
        }
    }
}


text:
describe('Ad units', function () {

    var cleanup = function () {
        $('.adunit').remove();
        $('script[src*="gpt.js"]').remove();
        window.googletag = undefined;
    };
    beforeEach(cleanup);
    afterEach(cleanup);

    it('Call to DFP with dfpID in adunit name', function (done) {
        var id = 'xxxxxxx';

        var dummyTag = {};
        dummyTag.enableServices = function() {};

        $('body').append('

');
        $.dfp({
            googletag: dummyTag
        });

        waitsForAndRuns(function () {
            if (typeof window.googletag.getVersion === 'function' && $('.adunit').data('googleAdUnit')) {
                return true;
            } else {
                return false;
            }
        }, function () {
            expect($('.adunit').data('googleAdUnit').getName()).toEqual('/' + id + '/Leader');
            done();
        }, 5000);

    });

    it('Auto generate an ID for the ad unit if no ID provided', function (done) {

        var dummyTag = {};
        dummyTag.enableServices = function() {};

        $('body').append('

');
        $.dfp({
            dfpID: 'xxxxxxx',
            googletag: dummyTag
        });

        waitsForAndRuns(function () {
            if (typeof window.googletag.getVersion === 'function') {
                return true;
            } else {
                return false;
            }
        }, function () {
            expect($('.adunit').attr('id')).toMatch(/Leader-auto-gen-id-\d+/i);
            done();
        }, 5000);

    });

    it('Google ad unit object get attached to the ad unit container', function (done) {

        var dummyTag = {};
        dummyTag.enableServices = function() {};

        $('body').append('

');
        $.dfp({
            dfpID: 'xxxxxxx',
            googletag: dummyTag
        });

        waitsForAndRuns(function () {
            if (typeof window.googletag.getVersion === 'function' && $('.adunit').data('googleAdUnit')) {
                return true;
            } else {
                return false;
            }
        }, function () {
            expect($('.adunit').data('googleAdUnit').getName()).toEqual('/xxxxxxx/Leader');
            done();
        }, 5000);

    });

    it('Google ad unit object get attached to the ad unit container (with namespace)', function (done) {
        var namespace = 'my-long-namespace';

        var dummyTag = {};
        dummyTag.enableServices = function() {};

        $('body').append('

');
        $.dfp({
            dfpID: 'xxxxxxx',
            googletag: dummyTag,
            namespace: namespace
        });

        waitsForAndRuns(function () {
            if (typeof window.googletag.getVersion === 'function' && $('.adunit').data('googleAdUnit')) {
                return true;
            } else {
                return false;
            }
        }, function () {
            expect($('.adunit').data('googleAdUnit').getName()).toEqual('/xxxxxxx/' + namespace);
            done();
        }, 5000);

    });

});


text:
var App = require('app');
require('models/client_component');

describe('App.ClientComponent', function () {

  var clientComponent;

  beforeEach(function () {
    clientComponent = App.ClientComponent.createRecord();
  });

  describe('#allowToDelete', function () {

    var cases = [
      {
        statesCounts: {
          installedCount: 1,
          installFailedCount: 2,
          initCount: 3,
          unknownCount: 4,
          totalCount: 10
        },
        allowToDelete: true,
        title: 'delete allowed'
      },
      {
        statesCounts: {
          installedCount: 1,
          installFailedCount: 2,
          initCount: 3,
          unknownCount: 4,
          totalCount: 11
        },
        allowToDelete: false,
        title: 'delete not allowed'
      }
    ];

    cases.forEach(function (item) {

      it(item.title, function () {
        clientComponent.setProperties(item.statesCounts);
        expect(clientComponent.get('allowToDelete')).to.equal(item.allowToDelete);
      });

    });

  });

  describe('#summaryLabelClassName', function () {

    it('should use lower case of component name', function () {
      clientComponent.set('componentName', 'ZOOKEEPER_CLIENT');
      expect(clientComponent.get('summaryLabelClassName')).to.equal('label_for_zookeeper_client');
    });

  });

  describe('#summaryValueClassName', function () {

    it('should use lower case of component name', function () {
      clientComponent.set('componentName', 'ZOOKEEPER_CLIENT');
      expect(clientComponent.get('summaryValueClassName')).to.equal('value_for_zookeeper_client');
    });

  });

  describe('#displayNamePluralized', function () {

    var cases = [
      {
        installedCount: 1,
        displayNamePluralized: 'Zookeeper Client',
        title: 'singular'
      },
      {
        installedCount: 2,
        displayNamePluralized: 'Zookeeper Clients',
        title: 'plural'
      }
    ];

    cases.forEach(function (item) {

      it(item.title, function () {
        clientComponent.setProperties({
          displayName: 'Zookeeper Client',
          installedCount: item.installedCount
        });
        expect(clientComponent.get('displayNamePluralized')).to.equal(item.displayNamePluralized);
      });

    });

  });

});


text:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports U2.Data.Client
Imports System.Data

Namespace DataAdapter_MultiValue
    Class Program
        Shared Sub Main(args As String())
            Try
                Dim conn_str As New U2ConnectionStringBuilder()
                conn_str.UserID = "user"
                conn_str.Password = "pass"
                conn_str.Server = "localhost"
                conn_str.Database = "demo"
                conn_str.ServerType = "UNIDATA"
                conn_str.Pooling = False
                conn_str.FirstNormalForm = False
                Dim s As String = conn_str.ToString()
                Dim con As New U2Connection()
                con.ConnectionString = s
                con.Open()
                Console.WriteLine("Connected.........................")
                Dim cmd As U2Command = con.CreateCommand()
                cmd.CommandText = "SELECT * FROM STUDENT UNNEST NL_ALL CGA ;"
                Dim ds As New DataSet()
                Dim da As New U2DataAdapter(cmd)
                da.Fill(ds)
                Dim dt As DataTable = ds.Tables(0)
                For Each dr As DataRow In dt.Rows
                    Console.WriteLine(Convert.ToString(dr("FNAME")) & "==" & Convert.ToString(dr("SEMESTER")))
                Next

                con.Close()
            Catch e As Exception

                Console.WriteLine(e.Message)
            Finally
                Console.WriteLine("Enter to exit:")
                Dim line As String = Console.ReadLine()
            End Try
        End Sub
    End Class
End Namespace


text:
/* tslint:disable */

import { ConcreteRequest } from "relay-runtime";
export type CommerceSetPaymentInput = {
    readonly clientMutationId?: string | null;
    readonly creditCardId: string;
    readonly id: string;
};
export type PaymentRouteSetOrderPaymentMutationVariables = {
    readonly input: CommerceSetPaymentInput;
};
export type PaymentRouteSetOrderPaymentMutationResponse = {
    readonly commerceSetPayment: ({
        readonly orderOrError: {
            readonly order?: {
                readonly creditCard: ({
                    readonly id: string;
                    readonly name: string | null;
                    readonly street1: string | null;
                    readonly street2: string | null;
                    readonly city: string | null;
                    readonly state: string | null;
                    readonly country: string | null;
                    readonly postal_code: string | null;
                }) | null;
            };
            readonly error?: {
                readonly type: string;
                readonly code: string;
                readonly data: string | null;
            };
        };
    }) | null;
};
export type PaymentRouteSetOrderPaymentMutation = {
    readonly response: PaymentRouteSetOrderPaymentMutationResponse;
    readonly variables: PaymentRouteSetOrderPaymentMutationVariables;
};

/*
mutation PaymentRouteSetOrderPaymentMutation(
  $input: CommerceSetPaymentInput!
) {
  commerceSetPayment(input: $input) {
    orderOrError {
      __typename
      ... on CommerceOrderWithMutationSuccess {
        order {
          __typename
          creditCard {
            id
            name
            street1
            street2
            city
            state
            country
            postal_code
            __id
          }
          __id: id
        }
      }
      ... on CommerceOrderWithMutationFailure {
        error {
          type
          code
          data
        }
      }
    }
  }
}
*/

const node: ConcreteRequest = (function(){
var v0 = [
  {
    "kind": "LocalArgument",
    "name": "input",
    "type": "CommerceSetPaymentInput!",
    "defaultValue": null
  }
],
v1 = [
  {
    "kind": "Variable",
    "name": "input",
    "variableName": "input",
    "type": "CommerceSetPaymentInput!"
  }
],
v2 = {
  "kind": "InlineFragment",
  "type": "CommerceOrderWithMutationFailure",
  "selections": [
    {
      "kind": "LinkedField",
      "alias": null,
      "name": "error",
      "storageKey": null,
      "args": null,
      "concreteType": "CommerceApplicationError",
      "plural": false,
      "selections": [
        {
          "kind": "ScalarField",
          "alias": null,
          "name": "type",
          "args": null,
          "storageKey": null
        },
        {
          "kind": "ScalarField",
          "alias": null,
          "name": "code",
          "args": null,
          "storageKey": null
        },
        {
          "kind": "ScalarField",
          "alias": null,
          "name": "data",
          "args": null,
          "storageKey": null
        }
      ]
    }
  ]
},
v3 = {
  "kind": "LinkedField",
  "alias": null,
  "name": "creditCard",
  "storageKey": null,
  "args": null,
  "concreteType": "CreditCard",
  "plural": false,
  "selections": [
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "id",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "name",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "street1",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "street2",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "city",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "state",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "country",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "postal_code",
      "args": null,
      "storageKey": null
    },
    {
      "kind": "ScalarField",
      "alias": null,
      "name": "__id",
      "args": null,
      "storageKey": null
    }
  ]
},
v4 = {
  "kind": "ScalarField",
  "alias": "__id",
  "name": "id",
  "args": null,
  "storageKey": null
},
v5 = {
  "kind": "ScalarField",
  "alias": null,
  "name": "__typename",
  "args": null,
  "storageKey": null
};
return {
  "kind": "Request",
  "operationKind": "mutation",
  "name": "PaymentRouteSetOrderPaymentMutation",
  "id": null,
  "text": "mutation PaymentRouteSetOrderPaymentMutation(\n  $input: CommerceSetPaymentInput!\n) {\n  commerceSetPayment(input: $input) {\n    orderOrError {\n      __typename\n      ... on CommerceOrderWithMutationSuccess {\n        order {\n          __typename\n          creditCard {\n            id\n            name\n            street1\n            street2\n            city\n            state\n            country\n            postal_code\n            __id\n          }\n          __id: id\n        }\n      }\n      ... on CommerceOrderWithMutationFailure {\n        error {\n          type\n          code\n          data\n        }\n      }\n    }\n  }\n}\n",
  "metadata": {},
  "fragment": {
    "kind": "Fragment",
    "name": "PaymentRouteSetOrderPaymentMutation",
    "type": "Mutation",
    "metadata": null,
    "argumentDefinitions": v0,
    "selections": [
      {
        "kind": "LinkedField",
        "alias": null,
        "name": "commerceSetPayment",
        "storageKey": null,
        "args": v1,
        "concreteType": "CommerceSetPaymentPayload",
        "plural": false,
        "selections": [
          {
            "kind": "LinkedField",
            "alias": null,
            "name": "orderOrError",
            "storageKey": null,
            "args": null,
            "concreteType": null,
            "plural": false,
            "selections": [
              v2,
              {
                "kind": "InlineFragment",
                "type": "CommerceOrderWithMutationSuccess",
                "selections": [
                  {
                    "kind": "LinkedField",
                    "alias": null,
                    "name": "order",
                    "storageKey": null,
                    "args": null,
                    "concreteType": null,
                    "plural": false,
                    "selections": [
                      v3,
                      v4
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  "operation": {
    "kind": "Operation",
    "name": "PaymentRouteSetOrderPaymentMutation",
    "argumentDefinitions": v0,
    "selections": [
      {
        "kind": "LinkedField",
        "alias": null,
        "name": "commerceSetPayment",
        "storageKey": null,
        "args": v1,
        "concreteType": "CommerceSetPaymentPayload",
        "plural": false,
        "selections": [
          {
            "kind": "LinkedField",
            "alias": null,
            "name": "orderOrError",
            "storageKey": null,
            "args": null,
            "concreteType": null,
            "plural": false,
            "selections": [
              v5,
              v2,
              {
                "kind": "InlineFragment",
                "type": "CommerceOrderWithMutationSuccess",
                "selections": [
                  {
                    "kind": "LinkedField",
                    "alias": null,
                    "name": "order",
                    "storageKey": null,
                    "args": null,
                    "concreteType": null,
                    "plural": false,
                    "selections": [
                      v5,
                      v3,
                      v4
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
};
})();
(node as any).hash = 'fca070e4e891f997375e79407ed33fe7';
export default node;


text:
using System;
using System.Net;
using System.Threading;
using Gridsum.NHBaseThrift.Messages;
using Gridsum.NHBaseThrift.Network.Transactions;
using KJFramework.EventArgs;
using KJFramework.Net.Channels;
using KJFramework.Net.ProtocolStacks;
using KJFramework.Net.Transaction;
using KJFramework.Net.Transaction.Helpers;
using KJFramework.Net.Transaction.Identities;
using KJFramework.Tracing;

namespace Gridsum.NHBaseThrift.Network.Agents
{
    /// <summary>
    ///     ¿Í»§¶ËÁ¬½Ó´úÀíÆ÷£¬ÌṩÁËÏà¹ØµÄ»ù±¾²Ù×÷
    /// </summary>
    public class ThriftConnectionAgent : IThriftConnectionAgent
    {
        #region Constructor

        /// <summary>
        ///     ¿Í»§¶ËÁ¬½Ó´úÀíÆ÷£¬ÌṩÁËÏà¹ØµÄ»ù±¾²Ù×÷
        /// </summary>
        /// <param name="channel">¿Í»§¶ËÁ¬½Ó</param>
        /// <param name="transactionManager">ÊÂÎñ¹ÜÀíÆ÷</param>
        public ThriftConnectionAgent(IMessageTransportChannel<ThriftMessage> channel, ThriftMessageTransactionManager transactionManager)
        {
            if (channel == null) throw new ArgumentNullException("channel");
            if (!channel.IsConnected) throw new ArgumentException("Cannot wrap this msg channel, because current msg channel has been disconnected!");
            if (transactionManager == null) throw new ArgumentNullException("transactionManager");
            _sequenceId = 0;
            _channel = channel;
            _transactionManager = transactionManager;
            _channel.Disconnected += ChannelDisconnected;
            _channel.ReceivedMessage += ChannelReceivedMessage;
        }

        #endregion

        #region Members

        private int _sequenceId;
        private bool _isInitiativeDisconnect;
        private IMessageTransportChannel<ThriftMessage> _channel;
        protected static readonly ITracing _tracing = TracingManager.GetTracing(typeof (ThriftConnectionAgent));

        #endregion

        #region Events

        //inner msg channel disconect event.
        void ChannelDisconnected(object sender, EventArgs e)
        {
            _channel.Disconnected -= ChannelDisconnected;
            _channel.ReceivedMessage -= ChannelReceivedMessage;
            if (_isInitiativeDisconnect) return;
            DisconnectedHandler(null);
        }

        //new message arrived.
        void ChannelReceivedMessage(object sender, LightSingleArgEventArgs<System.Collections.Generic.List<ThriftMessage>> e)
        {
            IMessageTransportChannel<ThriftMessage> msgChannel = (IMessageTransportChannel<ThriftMessage>)sender;
            foreach (ThriftMessage message in e.Target)
            {
                if (message == null) continue;
                _tracing.Info("L: {0}\r\nR: {1}\r\n{2}", msgChannel.LocalEndPoint, msgChannel.RemoteEndPoint, message.ToString());
                //rebuilds corresponding TransactionIdentity for current RSP message.
                TransactionIdentity identity = IdentityHelper.Create((IPEndPoint) msgChannel.LocalEndPoint, (int) message.Identity.SequenceId, false);
                _transactionManager.Active(identity, message);
            }
        }

        #endregion

        #region Implementation of IConnectionAgent

        private object _tag;
        private readonly ThriftMessageTransactionManager _transactionManager;

        /// <summary>
        ///     »ñÈ¡»òÉèÖø½ÊôÊôÐÔ
        /// </summary>
        public object Tag
        {
            get { return _tag; }
            set { _tag = value; }
        }

        /// <summary>
        ///     »ñÈ¡ÊÂÎñ¹ÜÀíÆ÷
        /// </summary>
        public ThriftMessageTransactionManager TransactionManager
        {
            get { return _transactionManager; }
        }

        /// <summary>
        ///     Ö÷¶¯¹Ø±ÕÁ¬½Ó´úÀíÆ÷
        ///     * Ö÷¶¯¹Ø±ÕµÄÐÐΪ½«»á¹Ø±ÕÄÚ²¿µÄͨÐÅÐŵÀÁ¬½Ó
        /// </summary>
        public void Close()
        {
            _isInitiativeDisconnect = true;
            if(_channel != null && _channel.IsConnected)
            {
                _channel.Disconnect();
                DisconnectedHandler(null);
            }
        }

        /// <summary>
        ///     »ñÈ¡ÄÚ²¿µÄͨÐÅÐŵÀ
        ///     * Ò»°ã²»½¨ÒéʹÓô˷½·¨Ö±½Ó²Ù×÷ÄÚ²¿µÄͨÐÅÐŵÀ
        /// </summary>
        /// <returns>·µ»ØͨÐÅÐŵÀ</returns>
        public IMessageTransportChannel<ThriftMessage> GetChannel()
        {
            return _channel;
        }

        /// <summary>
        ///     ´´½¨Ò»¸öеÄÊÂÎñ
        /// </summary>
        /// <returns>·µ»ØÒ»¸öÕë¶Ô¿Í»§¶ËµÄÐÂÊÂÎï</returns>
        public ThriftMessageTransaction CreateTransaction()
        {
            return TransactionManager.Create(Interlocked.Increment(ref _sequenceId), GetChannel());
        }

        /// <summary>
        ///     ¶Ï¿ªÊ¼þ
        /// </summary>
        public event EventHandler Disconnected;
        private void DisconnectedHandler(EventArgs e)
        {
            EventHandler handler = Disconnected;
            if (handler != null) handler(this, e);
        }

        /// <summary>
        ///     еÄÊÂÎï´´½¨±»´´½¨Ê±¼¤»î´Ë'þ
        /// </summary>
        public event EventHandler<LightSingleArgEventArgs<IMessageTransaction<ThriftMessage>>> NewTransaction;
        private void NewTransactionHandler(LightSingleArgEventArgs<IMessageTransaction<ThriftMessage>> e)
        {
            EventHandler<LightSingleArgEventArgs<IMessageTransaction<ThriftMessage>>> handler = NewTransaction;
            if (handler != null) handler(this, e);
        }

        #endregion

        #region Methods

        /// <summary>
        ///     ´´½¨Ò»¸öеÄÁ¬½Ó´úÀíÆ÷
        /// </summary>
        /// <param name="iep">Ô¶³ÌÖÕ½áµãµØÖ·</param>
        /// <param name="protocolStack">ЭÒéÕ»</param>
        /// <param name="transactionManager">ÊÂÎñ¹ÜÀíÆ÷</param>
        /// <returns>Èç¹ûÎÞ·¨Á¬½Óµ½Ô¶³ÌµØÖ·£¬Ôò·µ»Ønull.</returns>
        public static IThriftConnectionAgent Create(IPEndPoint iep, IProtocolStack<ThriftMessage> protocolStack, ThriftMessageTransactionManager transactionManager)
        {
            if (iep == null) throw new ArgumentNullException("iep");
            if (protocolStack == null) throw new ArgumentNullException("protocolStack");
            if (transactionManager == null) throw new ArgumentNullException("transactionManager");
            ITransportChannel transportChannel = new TcpTransportChannel(iep);
            transportChannel.Connect();
            if (!transportChannel.IsConnected) return null;
            IMessageTransportChannel<ThriftMessage> msgChannel = new MessageTransportChannel<ThriftMessage>((IRawTransportChannel)transportChannel, protocolStack, new ThriftProtocolSegmentDataParser((ThriftProtocolStack) protocolStack));
            return new ThriftConnectionAgent(msgChannel, transactionManager);
        }

        #endregion
    }
}


text:
package org.apache.solr.util;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yonik
 * @version $Id$
 */

public abstract class RefCounted<Type> {
  protected final Type resource;
  protected final AtomicInteger refcount= new AtomicInteger();
  public RefCounted(Type resource) { this.resource = resource; }
  public final RefCounted<Type> incref() { refcount.incrementAndGet(); return this; }
  public final Type get() { return resource; }
  public void decref() { if (refcount.decrementAndGet()==0) close(); }
  protected abstract void close();
}


text:
find_path(ROBIN_HOOD_INCLUDE_DIR robin_hood.h)
mark_as_advanced(ROBIN_HOOD_INCLUDE_DIR)

# Get version number and create library
if(ROBIN_HOOD_INCLUDE_DIR)
    file(READ "${ROBIN_HOOD_INCLUDE_DIR}/robin_hood.h" ROBIN_HOOD_FILE_CONTENT)

    # Find major version number
    if(ROBIN_HOOD_FILE_CONTENT MATCHES "ROBIN_HOOD_VERSION_MAJOR +([0-9]+)")
        set(ROBIN_HOOD_VERSION_MAJOR "${CMAKE_MATCH_1}")
    endif()

    # Find minor version number
    if(ROBIN_HOOD_FILE_CONTENT MATCHES "ROBIN_HOOD_VERSION_MINOR +([0-9]+)")
        set(ROBIN_HOOD_VERSION_MINOR "${CMAKE_MATCH_1}")
    endif()

    # Find patch version number
    if(ROBIN_HOOD_FILE_CONTENT MATCHES "ROBIN_HOOD_VERSION_PATCH +([0-9]+)")
        set(ROBIN_HOOD_VERSION_PATCH "${CMAKE_MATCH_1}")
    endif()

    set(ROBIN_HOOD_VERSION ${ROBIN_HOOD_VERSION_MAJOR}.${ROBIN_HOOD_VERSION_MINOR}.${ROBIN_HOOD_VERSION_PATCH})

    # Create CMake library
    add_library(robin_hood INTERFACE IMPORTED)
    add_library(robin_hood::robin_hood ALIAS robin_hood)

    target_include_directories(robin_hood
        INTERFACE
            ${ROBIN_HOOD_INCLUDE_DIR}
    )

    set(ROBIN_HOOD_LIBRARY robin_hood::robin_hood)
endif()

# Handles find_package arguments and set FBX_FOUND to TRUE if all listed variables and version are valid.
include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(robin_hood
  FOUND_VAR ROBIN_HOOD_FOUND
  REQUIRED_VARS ROBIN_HOOD_LIBRARY ROBIN_HOOD_INCLUDE_DIR
  VERSION_VAR ROBIN_HOOD_VERSION)


text:
package org.apache.beam.sdk.util;

/**
 * Lambda interface for inspecting an http request and response to match the failure and possibly
 * generate a custom error message with more context.
 */
interface HttpCallMatcher {

  /** @return true iff the request and response represent a matching http c\all. */
  boolean matchResponse(HttpRequestWrapper req, HttpResponseWrapper response);
}


text:
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"github.com/jmoiron/sqlx"
	"github.com/lib/pq"

	"github.com/apache/incubator-trafficcontrol/lib/go-log"
)

const MonitoringPrivLevel = PrivLevelReadOnly

const CacheMonitorConfigFile = "rascal.properties"
const MonitorType = "RASCAL"
const RouterType = "CCR"
const MonitorProfilePrefix = "RASCAL"
const MonitorConfigFile = "rascal-config.txt"
const KilobitsPerMegabit = 1000
const DeliveryServiceStatus = "REPORTED"

type BasicServer struct {
	Profile    string `json:"profile"`
	Status     string `json:"status"`
	IP         string `json:"ip"`
	IP6        string `json:"ip6"`
	Port       int    `json:"port"`
	Cachegroup string `json:"cachegroup"`
	HostName   string `json:"hostname"`
	FQDN       string `json:"fqdn"`
}

type Monitor struct {
	BasicServer
}

type Cache struct {
	BasicServer
	InterfaceName string `json:"interfacename"`
	Type          string `json:"type"`
	HashID        string `json:"hashid"`
}

type Cachegroup struct {
	Name        string      `json:"name"`
	Coordinates Coordinates `json:"coordinates"`
}

type Coordinates struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
}

type Profile struct {
	Name       string                 `json:"name"`
	Type       string                 `json:"type"`
	Parameters map[string]interface{} `json:"parameters"`
}

type Monitoring struct {
	TrafficServers   []Cache                `json:"trafficServers"`
	TrafficMonitors  []Monitor              `json:"trafficMonitors"`
	Cachegroups      []Cachegroup           `json:"cacheGroups"`
	Profiles         []Profile              `json:"profiles"`
	DeliveryServices []DeliveryService      `json:"deliveryServices"`
	Config           map[string]interface{} `json:"config"`
}

type MonitoringResponse struct {
	Response Monitoring `json:"response"`
}

type Router struct {
	Type    string
	Profile string
}

type DeliveryService struct {
	XMLID              string  `json:"xmlId"`
	TotalTPSThreshold  float64 `json:"totalTpsThreshold"`
	Status             string  `json:"status"`
	TotalKBPSThreshold float64 `json:"totalKbpsThreshold"`
}

// TODO change to use the PathParams, instead of parsing the URL
func monitoringHandler(db *sqlx.DB) RegexHandlerFunc {
	return func(w http.ResponseWriter, r *http.Request, p PathParams) {
		handleErr := func(err error, status int) {
			log.Errorf("%v %v\n", r.RemoteAddr, err)
			w.WriteHeader(status)
			fmt.Fprintf(w, http.StatusText(status))
		}

		cdnName := p["cdn"]

		resp, err := getMonitoringJson(cdnName, db)
		if err != nil {
			handleErr(err, http.StatusInternalServerError)
			return
		}

		respBts, err := json.Marshal(resp)
		if err != nil {
			handleErr(err, http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, "%s", respBts)
	}
}

func getMonitoringServers(db *sqlx.DB, cdn string) ([]Monitor, []Cache, []Router, error) {
	query := `SELECT
me.host_name as hostName,
CONCAT(me.host_name, '.', me.domain_name) as fqdn,
status.name as status,
cachegroup.name as cachegroup,
me.tcp_port as port,
me.ip_address as ip,
me.ip6_address as ip6,
profile.name as profile,
me.interface_name as interfaceName,
type.name as type,
me.xmpp_id as hashId
FROM server me
JOIN type type ON type.id = me.type
JOIN status status ON status.id = me.status
JOIN cachegroup cachegroup ON cachegroup.id = me.cachegroup
JOIN profile profile ON profile.id = me.profile
JOIN cdn cdn ON cdn.id = me.cdn_id
WHERE cdn.name = $1`

	rows, err := db.Query(query, cdn)
	if err != nil {
		return nil, nil, nil, err
	}
	defer rows.Close()

	monitors := []Monitor{}
	caches := []Cache{}
	routers := []Router{}

	for rows.Next() {
		var hostName sql.NullString
		var fqdn sql.NullString
		var status sql.NullString
		var cachegroup sql.NullString
		var port sql.NullInt64
		var ip sql.NullString
		var ip6 sql.NullString
		var profile sql.NullString
		var interfaceName sql.NullString
		var ttype sql.NullString
		var hashId sql.NullString

		if err := rows.Scan(&hostName, &fqdn, &status, &cachegroup, &port, &ip, &ip6, &profile, &interfaceName, &ttype, &hashId); err != nil {
			return nil, nil, nil, err
		}

		if ttype.String == MonitorType {
			monitors = append(monitors, Monitor{
				BasicServer: BasicServer{
					Profile:    profile.String,
					Status:     status.String,
					IP:         ip.String,
					IP6:        ip6.String,
					Port:       int(port.Int64),
					Cachegroup: cachegroup.String,
					HostName:   hostName.String,
					FQDN:       fqdn.String,
				},
			})
		} else if strings.HasPrefix(ttype.String, "EDGE") || strings.HasPrefix(ttype.String, "MID") {
			caches = append(caches, Cache{
				BasicServer: BasicServer{
					Profile:    profile.String,
					Status:     status.String,
					IP:         ip.String,
					IP6:        ip6.String,
					Port:       int(port.Int64),
					Cachegroup: cachegroup.String,
					HostName:   hostName.String,
					FQDN:       fqdn.String,
				},
				InterfaceName: interfaceName.String,
				Type:          ttype.String,
				HashID:        hashId.String,
			})
		} else if ttype.String == RouterType {
			routers = append(routers, Router{
				Type:    ttype.String,
				Profile: profile.String,
			})
		}
	}
	return monitors, caches, routers, nil
}

func getCachegroups(db *sqlx.DB, cdn string) ([]Cachegroup, error) {
	query := `
SELECT name, latitude, longitude
FROM cachegroup
WHERE id IN
  (SELECT cachegroup FROM server WHERE server.cdn_id =
    (SELECT id FROM cdn WHERE name = $1));`

	rows, err := db.Query(query, cdn)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	cachegroups := []Cachegroup{}

	for rows.Next() {
		var name sql.NullString
		var lat sql.NullFloat64
		var lon sql.NullFloat64
		if err := rows.Scan(&name, &lat, &lon); err != nil {
			return nil, err
		}
		cachegroups = append(cachegroups, Cachegroup{
			Name: name.String,
			Coordinates: Coordinates{
				Latitude:  lat.Float64,
				Longitude: lon.Float64,
			},
		})
	}
	return cachegroups, nil
}

func getProfiles(db *sqlx.DB, caches []Cache, routers []Router) ([]Profile, error) {
	cacheProfileTypes := map[string]string{}
	profiles := map[string]Profile{}
	profileNames := []string{}
	for _, router := range routers {
		profiles[router.Profile] = Profile{
			Name: router.Profile,
			Type: router.Type,
		}
	}

	for _, cache := range caches {
		if _, ok := cacheProfileTypes[cache.Profile]; !ok {
			cacheProfileTypes[cache.Profile] = cache.Type
			profiles[cache.Profile] = Profile{
				Name: cache.Profile,
				Type: cache.Type,
			}
			profileNames = append(profileNames, cache.Profile)
		}
	}

	query := `
SELECT p.name as profile, pr.name, pr.value
FROM parameter pr
JOIN profile p ON p.name = ANY($1)
JOIN profile_parameter pp ON pp.profile = p.id and pp.parameter = pr.id
WHERE pr.config_file = $2;
`
	rows, err := db.Query(query, pq.Array(profileNames), CacheMonitorConfigFile)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var profileName sql.NullString
		var name sql.NullString
		var value sql.NullString
		if err := rows.Scan(&profileName, &name, &value); err != nil {
			return nil, err
		}
		if name.String == "" {
			return nil, fmt.Errorf("null name") // TODO continue and warn?
		}
		profile := profiles[profileName.String]
		if profile.Parameters == nil {
			profile.Parameters = map[string]interface{}{}
		}

		if valNum, err := strconv.Atoi(value.String); err == nil {
			profile.Parameters[name.String] = valNum
		} else {
			profile.Parameters[name.String] = value.String
		}
		profiles[profileName.String] = profile

	}

	profilesArr := []Profile{} // TODO make for efficiency?
	for _, profile := range profiles {
		profilesArr = append(profilesArr, profile)
	}
	return profilesArr, nil
}

func getDeliveryServices(db *sqlx.DB, routers []Router) ([]DeliveryService, error) {
	profileNames := []string{}
	for _, router := range routers {
		profileNames = append(profileNames, router.Profile)
	}

	query := `
SELECT ds.xml_id, ds.global_max_tps, ds.global_max_mbps
FROM deliveryservice ds
JOIN profile profile ON profile.id = ds.profile
WHERE profile.name = ANY($1)
AND ds.active = true
`
	rows, err := db.Query(query, pq.Array(profileNames))
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	dses := []DeliveryService{}

	for rows.Next() {
		var xmlid sql.NullString
		var tps sql.NullFloat64
		var mbps sql.NullFloat64
		if err := rows.Scan(&xmlid, &tps, &mbps); err != nil {
			return nil, err
		}
		dses = append(dses, DeliveryService{
			XMLID:              xmlid.String,
			TotalTPSThreshold:  tps.Float64,
			Status:             DeliveryServiceStatus,
			TotalKBPSThreshold: mbps.Float64 * KilobitsPerMegabit,
		})
	}
	return dses, nil
}

func getConfig(db *sqlx.DB) (map[string]interface{}, error) {
	// TODO remove 'like' in query? Slow?
	query := fmt.Sprintf(`
SELECT pr.name, pr.value
FROM parameter pr
JOIN profile p ON p.name LIKE '%s%%'
JOIN profile_parameter pp ON pp.profile = p.id and pp.parameter = pr.id
WHERE pr.config_file = '%s'
`, MonitorProfilePrefix, MonitorConfigFile)

	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	cfg := map[string]interface{}{}

	for rows.Next() {
		var name sql.NullString
		var val sql.NullString
		if err := rows.Scan(&name, &val); err != nil {
			return nil, err
		}
		if valNum, err := strconv.Atoi(val.String); err == nil {
			cfg[name.String] = valNum
		} else {
			cfg[name.String] = val.String
		}
	}
	return cfg, nil
}

func getMonitoringJson(cdnName string, db *sqlx.DB) (*MonitoringResponse, error) {
	monitors, caches, routers, err := getMonitoringServers(db, cdnName)
	if err != nil {
		return nil, fmt.Errorf("error getting servers: %v", err)
	}

	cachegroups, err := getCachegroups(db, cdnName)
	if err != nil {
		return nil, fmt.Errorf("error getting cachegroups: %v", err)
	}

	profiles, err := getProfiles(db, caches, routers)
	if err != nil {
		return nil, fmt.Errorf("error getting profiles: %v", err)
	}

	deliveryServices, err := getDeliveryServices(db, routers)
	if err != nil {
		return nil, fmt.Errorf("error getting deliveryservices: %v", err)
	}

	config, err := getConfig(db)
	if err != nil {
		return nil, fmt.Errorf("error getting config: %v", err)
	}

	resp := MonitoringResponse{
		Response: Monitoring{
			TrafficServers:   caches,
			TrafficMonitors:  monitors,
			Cachegroups:      cachegroups,
			Profiles:         profiles,
			DeliveryServices: deliveryServices,
			Config:           config,
		},
	}
	return &resp, nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/homeMainSLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#F0F0F0">

    <LinearLayout
	    android:id="@+id/homeMainLLayout"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:background="#F0F0F0"
	    android:orientation="vertical" >
	</LinearLayout>
</ScrollView>