text:
5 of the Strangest Prehistoric Crocs
YouTube: https://youtube.com/watch?v=vh2wRYQPCPk
Previous: Should You Worry About Caffeine Dehydrating You?
Next: Can Plants Really Count?
Over the years, scientists have found evidence for a lot of weird prehistoric animals, but some of the strangest have been the crocodyliformes!
Hosted by: Hank Green
Thumbnail Credit: Dmitry Bogdanov
SciShow has a spinoff podcast! It's called SciShow Tangents. Check it out at http://www.scishowtangents.org
Adam Brainard, Greg, Alex Hackman, Sam Lutfi, D.A. Noe, الخليفي سلطان, Piya Shedden, KatieMarie Magnone, Scott Satovsky Jr, Charles Southerland, Patrick D. Ashmore, charles george, Kevin Bealer, Chris Peters
https://royalsocietypublishing.org/doi/pdf/10.1098/rsos.140385
https://www.eurekalert.org/pub_releases/2009-11/ngs-brd111809.php
Buckley et al 2000 A pug-nosed crocodyliform from the Late Cretaceous of Madagascar (https://www.nature.com/articles/35016061)
https://www.nature.com/news/2010/100804/full/news.2010.389.html
http://www.brooklyn.cuny.edu/bc/ahp/LAD/C21/C21_Convergent.html
https://evolution.berkeley.edu/evolibrary/article/similarity_ms_08
https://ucmp.berkeley.edu/vertebrates/flight/converge.html
https://evolution.berkeley.edu/evolibrary/article/evo_09
Mourasuchus
Bronchu 1999 (https://www.jstor.org/stable/pdf/3889340.pdf)
Fossils explained 34: Crocodilians, Geology Today.- https://darrennaish.files.wordpress.com/2013/01/naish-2001-geology-today-crocodilians.pdf
http://museohn.unmsm.edu.pe/docs/pub_pv/Salas_et_al.,2007_Fitzcarrald_crocodiles.pdf
https://academic.oup.com/icb/article/41/3/564/2091832
http://bit.ly/2XwQx9d
http://bit.ly/2IBL34Q
https://www.britannica.com/science/Miocene-Epoch
Kaprosuchus
Serano and Larsson 2009 (https://zookeys.pensoft.net/article/2104/)
https://www.eurekalert.org/pub_releases/2009-11/ngs-brd111809.php (was also used in intro)
https://www.theguardian.com/science/2009/nov/19/galloping-dinosaur-eating-crocodiles
Armadillosuchus
https://on.natgeo.com/2N53dQJ
https://www.igeo.ufrj.br/ismar/3/3_31.pdf
https://animals.sandiegozoo.org/animals/armadillo
https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0097138#abstract0
Pelagosaurus
Gignac et al (https://link.springer.com/chapter/10.1007/978-3-030-13739-7_15)
http://bit.ly/2RtW8I5
https://onlinelibrary.wiley.com/doi/pdf/10.1111/pala.12432
http://bit.ly/2xbM78U
http://bit.ly/2WYKRka
Metriorhynchids
Fossils explained 34: Crocodilians, Geology Today.- https://darrennaish.files.wordpress.com/2013/01/naish-2001-geology-today-crocodilians.pdf (used in mourasuchus)
https://www.eurekalert.org/pub_releases/2004-05/iop-sds051404.php
https://academic.oup.com/zoolinnean/article/158/4/801/2617599
http://jeb.biologists.org/content/jexbio/205/13/1853.full.pdf
https://ocean.si.edu/ocean-life/reptiles/sea-turtles
http://bit.ly/2Y9zneM
Mourasuchus illustration from https://jonbosco.artstation.com/
https://commons.wikimedia.org/wiki/File:Protosuchus_BW.jpg
https://commons.wikimedia.org/wiki/File:Australia_Cairns_18.jpg
http://bit.ly/2Y5ZIKM
https://commons.wikimedia.org/wiki/File:Stomatosuchus2.jpg
https://commons.wikimedia.org/wiki/File:Kaprosuchus_2.jpg
https://commons.wikimedia.org/wiki/File:Kaprosuchus.jpg
https://commons.wikimedia.org/wiki/File:Armadillosuchus.jpg
https://commons.wikimedia.org/wiki/File:Armadillosuchus_NT.jpg
https://commons.wikimedia.org/wiki/File:Armadillo-Florida-crop-2009.jpg
https://commons.wikimedia.org/wiki/File:Baurusuchus_albertoi.jpg
https://commons.wikimedia.org/wiki/File:Pelagosaurus_BW.jpg
https://commons.wikimedia.org/wiki/File:Pelagosaurus_typus_2.JPG
https://commons.wikimedia.org/wiki/File:Gavialis_gangeticus.jpg
https://commons.wikimedia.org/wiki/File:Metriorhynchus_superciliosum.jpg
https://commons.wikimedia.org/wiki/File:Suchodus_durobrivense.jpg
https://commons.wikimedia.org/wiki/File:Sea_turtle_head.jpg
http://bit.ly/2FsRmpo
Thanks to Skillshare for supporting this episode of SciShow. [♩INTRO].
Over the years, scientists have found evidence for a lot of weird prehistoric animals, but some of the strangest have been crocodyliformes. These animals belong to a group that's existed for millions of years and that today includes modern crocodiles.
We'll call these animals "crocs" for short, since "crocodyliformes" is kind of a mouthful. But some of these things were super weird. Modern crocodiles might seem to follow roughly the same body plan, but some of their prehistoric relatives look strangely like other animals.
We're talking duck croc, rat croc, pug croc, and cat croc. These adaptations weren't totally random, though:. Many of them are examples of convergent evolution.
Basically, this is where traits are so useful that they show up again and again, in animals that are not closely related. Like, bats and birds are not closely related, but they did converge on flight by flapping bits of their bodies around, possibly as a way to get around quickly while avoiding predators. And crocs, too, converged on many traits that gave them an advantage, depending on the environmental niche that they lived in.
Which is how we ended up these five very strange, but very lovely, examples. Mourasuchus was a group of crocodyliformes that lived in South America during the Miocene, about five to twenty-three million years ago. During this time, the Amazon may have been dominated by a vast wetland.
And a wide variety of crocs would have called it home. What made the Mourasuchus stand out, though, was their heads. Scientists have identified several species of these crocs, and each had an unusually long and broad skull.
The skulls were topped with a snout that looked kind of like a duck's bill, and they were filled with lots of slender little teeth. As for why… well, it's been suggested that these things might have actually eaten more like baleen whales than modern crocodiles. They may have used filter-feeding to catch their meals, engulfing water and small, aquatic prey, then straining out the water and swallowing what was left.
As for why they evolved such an odd diet, scientists say this might have been an example of what's known as resource partitioning. There were a lot of crocs in South America at this time, and there's only ever a certain amount of food to go around in any given ecosystem. If all the crocodyliformes were out chasing the same food, they'd be under intense competition with each other.
By specializing in only getting a certain type of food, Mourasuchus and the other crocs might have been able to limit their competition and carve out niches for themselves. Some would have hunted fish, and others might have specialized in hard-shelled prey like crabs, while Mourasuchus filtered their food from the water. Granted, the filter-feeding idea is a hypothesis, and not everyone agrees on it.
But since scientists have found at least one other crocodyliform that might have also been a filter feeder, it's probably not, outlandish. During the Cretaceous, from 144 million years ago to 65 million years ago,. North Africa was a rich ecosystem full of lakes and rivers and animals.
It was also home to a wide array of crocodyliformes, just like South America was millions of years later. And some of them, like Kaprosuchus saharicus, took the need to diversify to terrifying extremes. Kaprosuchus, nicknamed the "boar croc" for its tusk-like teeth, might have looked kind of like a cross between a crocodile and a wolf or big cat, like a leopard.
It was six meters long, had forward-facing eyes like a predatory cat, and had big, muscular jaws that came equipped with three sets of long, sharp teeth. Its nose might have also sported a keratin-reinforced shield that could be used like a battering ram. Basically, its entire snout was potentially built for high-impact hunting.
And although we've only ever found its skull, the scientists who discovered it suggest that Kaprosuchus might have even held its legs beneath its body, instead of splayed out like a modern croc. That would have made it more agile on land. The reason this thing shared so many features with land predators is that, like, it may have actually hunted on land, maybe tackling big terrestrial prey like dinosaurs.
These new features were biological responses to the challenges of this lifestyle. The forward facing eyes, for example, might have evolved to help it judge distances more precisely or see through camouflage better. Modern crocodiles are ambush predators, so their eyes are on the top of their head to help them watch for prey as they float in the water.
Different niches require different strategies. While Kaprosuchus might have been the most intimidating crocodyliform to make the jump to land, at least partially, it was far from the only one. The same expedition that discovered it also found a bunch of other weird crocodyliformes, including the "dog croc", which might have had a soft, dog-like nose, and the "rat croc", which was tiny and had buck teeth.
The most striking land-dweller, though, may have been Armadillosuchus arrudai. Found in Brazil during the Cretaceous, it really lived up to its name. All modern crocs have armor in the form of osteoderms, which are small bony deposits in the skin.
But Armadillosuchus took this a step further. It grew a full set of rigid body armor separated into mobile bands, like a modern armadillo. It also had big claws and robust shoulder bones, which suggest it might have actually been able to dig or burrow, again, kind of like an armadillo.
The area it lived in at the time was a hot, semi-arid environment, so these big claws might have helped it dig up food or scavenge for dead animals. This could have also enabled Armadillosuchus to be an omnivore. This was a relatively open niche that mammals, which were somewhat rare at the time, had not yet filled up.
As for why it evolved such strong armor, we can't say for sure, but, well, it wasn't the only crocodyliform in the area. Fossils of Armadillosuchus have often been found near big predatory crocodyliformes known as Baurusuchus. So like a modern armadillo, the extra armor could have helped it ward off predators that maybe it was somewhat closely related to.
After all, just because you're a croc, doesn't mean you're always at the top of the croc food chain. Of course, some crocodyliformes didn't take to land. Instead, they doubled down on hunting in the water.
Pelagosaurus typus, for example, was an ocean-going crocodyliform that lived during the Jurassic, about 180 million years ago. It lived in shallow, near-shore seas that covered what is today Western Europe. One of the things that really sticks out about Pelagosaurus is its snout.
It's super long and thin, similar to modern gharials. And, actually, this super-skinny skull shape has cropped up a bunch of different times before in distantly related crocodyliform species. So scientists think this is another example of convergent evolution, this time as a special adaptation for catching fish.
Having a slender snout limits how hard a creature can bite down on prey, so if you're trying to snag something big and tough, a skinny snout would be a bad idea. But the trade-off is that a skinny snout can move through the water much faster, letting you swipe your head back and forth much quicker. So if your diet is agile, but relatively small and soft, like, say, a fish, that might be a worthwhile trade-off.
And we know that Pelagosaurus hunted fish. One fossil was actually found with an early bony fish in its stomach. But though Pelagosaurus' adaptations may have been the result of taking to the ocean, there were crocodyliformes that took the body changes even further.
Our last example of a weird croc is a group called the metriorhynchids. These might have had the most extreme changes to their body plan and some of the clearest examples of convergent evolution. As the metriorhynchids' ancestors adapted to a life at sea, their limbs became.
Paddle-shaped, like a manatee, while their tails grew shark-like flukes. They also lost the typical crocodylomorphs' signature armor in favor of streamlined skin, like a dolphin or seal. These adaptations would have helped them maneuver through the water.
A streamlined body shape helps reduce drag, for instance. This would have made it easier and less energy-intensive for them to move around. They also developed glands that excrete salt, like the ones that sea turtles have.
Ingesting too much salt is harmful and even potentially fatal for most life, but if you live in the ocean, it can be hard to avoid that. So by developing a special gland to rid themselves of the excess, metriorhynchids could eat salty sea life or swallow water without getting sick. All of these adaptations were in response to them going from land into the ocean.
After examining the animals' hips, scientists have even suggested that they adapted to giving live birth, which would have let them avoid having to come out of the water to lay eggs. Metriorhynchids were very successful in their time, with lots of different species and wide ranges. Fossils have been found from South America to Europe, from the middle Jurassic all the way up to the early Cretaceous, when they disappeared, possibly due to shifting sea levels.
It's really striking just how often we see convergent evolution occurring among the crocodyliformes, from to adapting to life at sea to developing armadillo-like armor to protect yourself from other crocs. This lineage is diverse and surprising, full of oddities and off-shoots. And whether adapting to new habitats, finding the right niche or food supply, or avoiding getting eaten, the crocodyliformes provide some amazing examples of how similar patterns emerge to combat similar problems.
These animals are also just really cool to look at, or at least, the artists' interpretations of them are. And if looking at all these pictures is making you wish you were better at illustrating, well, there's a Skillshare class for that! It's about mastering the basics of Adobe Illustrator and is taught by an artist named Julian Burford.
He won't teach you how to illustrate crocs, but he will teach you all the basics you need to get started. Once you're done, you could also check out one of Skillshare's other classes. They have more than 25,000 of them, and with a Premium Membership, you can get unlimited access to them all.
Skillshare is a great way to learn new skills as a creator, and it's also really affordable at less than ten dollars a month. The SciShow team actually uses it all the time! You can join us, and more than seven million other creators, by checking out the link in the description.
The first five hundred people to use that link will get a two-month trial for free! [♩OUTRO].
Giant of anger


text:
Legend of Zelda: Skyward Sword Blowout: Story Details, Three New Trailers & Screens Galore
– September 29, 2011Posted in: News, Nintendo, Screenshots, The Legend of Zelda, Trailers
The hype train leading up to The Legend of Zelda: Skyward Sword's November 20th launch officially enters hyper-chug today with Nintendo releasing a ton of exciting new details, videos and screenshots from what is shaping up to be the Wii's glorious swan song.
To get you started, click play on the video up top to watch a trailer for the game's opening sequence.
Next, here are some introductory story details outlining key characters and scenarios that will "lay the foundation for the events that occur in the rest of the series."
– Introduction: The new game's storyline begins in Skyloft, an island town suspended high in the sky, on the day before young Link is to compete in a major bird-flying competition. The winner of the contest will earn the honor of taking part in a special ceremony with Zelda.
– Link and Zelda: Friends since childhood, Link and Zelda have always shared a special bond. Events in the new game will add even more depth to their relationship.
– Groose: Link's nemesis at school, Groose, plays a significant role in the early moments of the new game. This bully of a character not only threatens Link's chances to win the bird-flying competition, but he also reveals a jealous streak toward Link and Zelda's special bond.
– Fi: Early on in Link's new adventure, he encounters Fi, the spirit of the powerful Goddess Sword. Fi's guidance proves to be crucial as Link goes forth on a challenging quest that will ultimately result in the creation of the Master Sword.
– Zelda's father: Gaepora, Zelda's father, is the headmaster of Link's school. As such, he has knowledge of the history and legends of Skyloft.
What's up next? Only two more brand spankin' new videos to wistfully drool over. The first one is titled the 'Romance' trailer, appropriately showing the childhood, puppy-love relationship between Link and Zelda as they frolic and fly together in Skyloft. After that is a gameplay video of the game's sword combat tutorial. So check that one out for a quick lesson in Wii-mote sword fighting.
Last but not least in Nintendo's massive Skyward Sword info dump, we come to a gallery of 30 freshly captured screenshots. Enjoy, Zelda fans!
Tags: Nintendo, Screenshots, The Legend of Zelda: Skyward Sword, Trailers, Wii

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: jira-python getting custom field's value from an issue-link I'm trying to get the value of an issue link's custom field.
I know how to do it in a regular sub-task, but with issue-link, I can't get it.
This is how I get a custom field's value in a Sub Task:
getattr(issue.fields, name_map[fields[0]])

And when I try it with issue link, like this:
getattr(**issue_link**.fields, name_map[fields[0]])

I get: AttributeError: type object 'PropertyHolder' has no attribute 'customfield_18697'
What's interesting, I can update the custom field's value, like this:
issue_link.update(fields={name_map["Field1"]:"ABC"})

Why can I update but not get the value?
Thanks in advance

A: Found the answer in https://community.atlassian.com/t5/Jira-questions/Get-custom-fields-from-linked-issues-with-Jira-API/qaq-p/1148453
Needs to be done with a rest call, and not through the API

redpajama_set_name: RedPajamaStackExchange


text:
Business /
Labor strikes halt Tecno mobile factory line
By Samuel Getachew
With an ambitious goal of exporting its products to neighboring nations to the tune of more than USD 40 million a year and appease the demands of its products simultaneously, the Chinese-owned Transsion – maker of affordable TECNO mobile phones in Ethiopia – is facing its biggest challenge to date. Its plant factory is in a midst of a week-long strike over pay and working conditions of its 2000-plus employees in the Gofa and Alem Gena factories, triggering many to join the picket lines, The Reporter has learnt.
Efforts to mediate the situation have yielded little success and the strike is expected to continue, sources told The Reporter, failing to deliver its products at its signature stores throughout the country forcing many to open "in name" only for more than a month with little transaction and minimal staff support.
The now-called Transsion opened its first factory in Ethiopia by partnering with local actors, including Levi Wake – an Ethiopian-American entrepreneur — one of its major shareholders in 2009. This happened after abruptly abandoning its plan to open its first factory in the continent in Nigeria in 2014, making its Addis Ababa suburb location its first. It introduced its locally made Android smart phones with bilingual language options, Amharic and English in the summer of 2012.
Within its plants, the company intended to become a hub for neighboring nations and earn it a much needed forex. The TECNO brand continues to win favors from local consumers attributed to its cost, warranties and services, giving it advantages other imported phones do not offer.
Last year, among the 4 million phones blocked by Ethio-telecom over a new national Equipment Identity Registration System to help control contraband products, TECNO was hit the hardest inconveniencing thousands of customers for well over a month.
The Ethiopian Revenue and Customs Authority have been looking at measures to curb contraband phones in the country and that the Ethiopian Assemblers Association estimates to be 65 percent out of the estimated 47 cell phone users in the nation.
The maker of TECNO claims to sell products worth USD 50 million annually in Ethiopia and had hoped to up its share in the market this year.
The Reporter reached out to the company's public relations director, Samrawit Solomon for comment, despite being given ample time to respond to a list of written inquires made on Monday and being made aware of the deadline, she did not reply as of press time.
Korean manufacturer proposes establishment of research center to substitute imports
New Tech firm to join ICT sector with 200 mln birr capital
Railway Maintenance Depot at Risk of Machine Failure


text:
LGBT Cancer Support Group at QSpot LGBT Community Center in Asbury Park NJ
Every Friday - 11:30AM to 1:00PM EST
An LGBT Cancer Support Group being help at the QSpot Community Center every Friday from 11:30am to 1:00pm.
QSpot LGBT Center…
Totally Awesome 80's Weekend at The Hideaway Campground in Collins GA
Events. At The Hideaway Campground, Collins, GA, United states.
September 9-11, 2022 - 12:00PM to 11:00PM EST
This weekend is 50% off on all acomodations when checking in on Friday 2-3 days Discounts 9/9 - 9/11 when you book online only.…
The 2023 Connecticut Leather Weekend & Contest at 168 York Street Cafe in New Haven CT
Events. At 168 York Street Cafe, New Haven, CT, United states.
September 9-11, 2022 - 1:00PM to 1:00AM
The Connecticut Leather Contest returns!
Save the date and join us for a weekend of leather, fetish, and…
Online Event: Who Cares: Caregivers Support Group
Events. At The LGBTQ Community Center Of The Desert, Palm Springs, CA, United states.
Every Friday - 3:00PM to 4:00PM PST
Who Cares? is a peer-led support group for those who are caring for their loved ones. As unpaid caregivers, you can gain support from peers and know that we are…
Piano Lounge with John Flynn at Top Of The Pines in Rehoboth Beach DE
Events. At Top Of The Pines, Rehoboth Beach, DE, United states.
Every Friday & Saturday - 5:00PM to 7:30PM EST
Sing along at The Piano Lounge with John Flynn!
Every Friday and Saturday, 5PM-7:30PM
John "The Piano Man" Flynn will…
LGBTQA+ Community Awards: Pride Within Our Culture at The Barn in Bloomsburg PA
Events. At The Barn, Bloomsburg, PA, United states.
Friday, September 9, 2022 - 6:00PM to 9:00PM EST
Want to network, uplift, and support members and the community of a 5 county region. Join us to discover who won the…
Pride Night at Kings Island in Kings Mills OH
Events. At Kings Island, Kings Mills, OH, United states.
Friday, September 9, 2022 - 6:00PM to 11:30PM EST
Pride Night at Kings Island is back! We're putting this out here as a Save The Date.
Mark yourself as "going" and we'll be in touch soon with…
CT-PAH Pup Night at 168 York Street Cafe in New Haven CT
Second Friday - 6:00PM to 1:00AM EST
CT-PAH's first Pup Night at 168 York St Cafe in New Haven!
6pm - 8pm: Panels on consent and mosh guard training.
8pm - 11pm: Puppy Mosh
After Work Fridays at Boxers in New York NY
Every Friday - 7:00PM to 11:00PM EST
DJ JROC SPINNING ALL YOUR FAVORITE HITS
Diva Royale Drag Queen Show at La Chanson Lounge Nightclub in Wildwood NJ
Shows. At La Chanson Lounge Nightclub, Wildwood, NJ, United states.
Featuring The Finest In Wildwood Drag Queen Dinner and Brunch Shows and Female Celebrity Impersonation. Get Up Close And…
Retro Music Night at The Garage On Central in Saint Petersburg FL
Events. At The Garage On Central, Saint Petersburg, FL, United states.
Second Friday - 8:00PM to 12:00AM EST
So excited about this night. DJ Bill Kody spinning great music videos to the 70's, 80's and early 90's!!!!
Happy Hour Until 9 PM.
Retro,…
Friday Night Hope: Crystal Meth Anonymous at QSpot LGBT Community Center in Asbury Park NJ
Every Friday - 8:00PM to 9:00PM EST
Friday Night Hope will be having a Crystal Meth Anonymous meeting every Friday night from 8:00pm to 9:00pm at the QSpot…
CaBEARet at Tabu Lounge & Sports Bar in Philadelphia PA
Shows. At Tabu Lounge & Sports Bar, Philadelphia, PA, United states.
A body positive variety show.
A variety show that will focus on inclusivity, body positivity and will feature singing, burlesque, drag (Kings and…
Faaabulous! The Show at Notoriety in Las Vegas NV
Shows. At Notoriety, Las Vegas, NV, United states.
Every Thursday & Friday - 9:00PM to 11:00PM PST
Come watch the only ALL LIVE SINGING DRAG SHOW in Las Vegas.
Faaabulous! with guest host Stevie Hart! Features the powerhouse vocals of 5…
A body-positive variety show.
A variety shows that will focus on inclusivity, body positivity and will feature singing, burlesque, drag (Kings and…
Spill The Tea Revue at La Peg in Philadelphia PA
Shows. At La Peg, Philadelphia, PA, United states.
Friday, September 9, 2022 - 10:00PM to 12:00AM EST
We're Back. Its been a long time and I have a lot to Spill about. Come join us at La Peg Brasserie on September 9th starting @9pm.
Club Cafe Fridays at Club Cafe in Boston MA
Every Friday - 10:00PM to 2:00AM EST
Every Friday night you can catch DJ Stevie Psyclone for a whirlwind of pop, top 40, and fun throwbacks that will have you singing along till closing!
10 PM. $10…
Finally Fridays at Boxers in New York NY
BEATS BY MAX DAMIAN
HOSTED BY YUSEF X
10PM-4AM
Thottin & Boppin at Tabu Lounge & Sports Bar in Philadelphia PA
Second Friday - 10:00PM to 12:00AM EST
Come out to the most lit show in Philly!
A night where you can express yourself, be free and thot all night! Join Philadelphia's favorite…


text:
Click to scroll
Patenting Chemical and Pharmaceutical Inventions Patent information Latest news and insights Case studies Our experts
Guide to Intellectual Property Guide to the Patent System
Dehns is proud of its strong reputation in the chemical, pharmaceutical and chemical engineering sectors. We represent clients in the full gamut of chemical arts, including medicines and diagnostic materials, agrochemicals, petrochemicals, polymers, paints, inks and pigments, novel and high-tech materials, photochemistry and food technology.
Our attorneys are experienced at formulating strategies that seek to optimise the legal protection for our clients' inventions, consistent with the clients' commercial objectives and the applicable patent laws. We are experienced providers of advice relating to infringement and validity matters, and can also assist in due diligence exercises.
In some countries, the term of patent protection for some pharmaceutical and agrochemical inventions can be extended using Supplementary Protection Certificates. Our team has obtained numerous SPCs for our clients in these sectors of industry.
Patenting Chemical and Pharmaceutical Inventions
Inventions in the chemical arts can encompass medicines and diagnostic materials, agrochemicals, petrochemicals, polymers, paints, inks and pigments, novel and high-tech materials, photochemistry, food technology, chemical engineering and many other fields. In many respects, patent practice in these areas is no different from that in other technical fields; however, there some special factors that may need to be considered.
What can be patented?
In general, the patent system allows patent protection to be obtained for products, apparatus, processes and methods of use. Thus, chemical inventions may include physical entities such as new chemical compounds or compositions, and physical acts such as processes for making materials, or methods for using them. It is often appropriate to claim more than one of these aspects in the context of a single patent application; your patent attorney can advise you about this in more detail. For reasons of public policy and history, in some territories there are restrictions on the subject-matter that can be patented. For example, in Europe it is not possible to obtain a patent for a method of treatment of the human or animal body by surgery or therapy, or for a diagnostic method practised on the human or animal body. This provision was implemented with the aim of protecting medical practitioners from the risk of legal action for patent infringement. However, the exclusion has generally been construed narrowly, and furthermore the European Patent Convention incorporates special rules allowing for the patenting of known substances or compositions "for use in" an excluded method, provided that its use for such a method is not already known. In other countries, methods of treatment may be patentable (e.g. in the USA) and/or the manner of claiming pharmaceutical inventions may require certain claim formats. For this reason, it is essential for anyone wishing to protect an invention in this field to consult a patent attorney with relevant experience.
How long does patent protection last?
In Europe and most other jurisdictions, the maximum term of a patent is 20 years, counting from the date of filing of the application, and subject to the payment of (usually annual) maintenance fees to the relevant authorities. However, before a patent is granted the patent application is usually subjected to a more or less rigorous examination procedure in order to ensure that it meets the relevant legal requirements.
Examination may take several years, although in some fields, e.g. pharmaceuticals and agrochemicals, such delays may not necessarily disadvantage the applicant, who may often need to carry out clinical or field trials in order to establish the efficacy and safety of the materials covered by the patent application. A measure of delay thus affords applicants welcome flexibility when lead candidates are still being identified, as well as allowing them to respond to changing business priorities.
Additionally, some countries provide for Supplementary Protection Certificates or the like, by which the term of patent protection for products in certain fields can be extended beyond the usual 20-year term. This applies to fields such as pharmaceuticals which require pre-marketing approval and particularly when there has been delay in obtaining regulatory approval for the patented product. Our team of patent attorneys has obtained numerous SPCs for our clients in these industry sectors, and is well placed to advise on this aspect.
Developing a licencing strategy
Camurus AB is a Swedish research-based pharmaceutical and biotechnology company specialising in the commercialisation of innovative specialty medicines for treating serious and chronic diseases, where there are clear medical needs and potential to significantly improve treatment.
Louise Golding
Partner View profile
Roberto Calamita
Consultant View profile
Philip Towler
Annabel Beacham
Neil Campbell
Chris Goddard
Sara de Bresser
Senior Associate View profile
Jennifer Gordon
Mark Scott
Associate View profile
Back to Patents overview


text:
Paths of Glory
Stanley Kubrick's Paths of Glory is among the most powerful antiwar films ever made. A fiery Kirk Douglas stars as a World War I French colonel who goes head-to-head with the army's ruthless top brass when his men are accused of cowardice after being unable to carry out an impossible mission. This haunting, exquisitely photographed dissection of the military machine in all its absurdity and capacity for dehumanization (a theme Kubrick would continue to explore throughout his career) is assembled with its legendary director's customary precision, from its tense trench warfare sequences to its gripping courtroom climax to its ravaging final scene.
Paths of Glory was restored by the UCLA Film & Television Archive in cooperation with MGM Studios, with funding provided by The Film Foundation and the Hollywood Foreign Press Association.
New high definition digital transfer made from 35 mm film elements restored by UCLA Film & Television Archive in cooperation with MGM Studios, with funding provided by the Film Foundation and the Hollywood Foreign Press Association, with uncompressed monaural soundtrack on the Blu-ray edition
New audio commentary featuring critic Gary Giddins
Excerpt from a 1966 audio interview with director Stanley Kubrick
Television interview from 1979 with star Kirk Douglas
New video interviews with Kubrick's longtime executive producer Jan Harlan, Paths of Glory producer James B. Harris, and actress Christiane Kubrick
French television piece about a real-life World War I execution that partly inspired the film
Theatrical trailer
PLUS: A booklet featuring a new essay by film scholar James Naremore
New cover by F. Ron Miller
Colonel Dax
Corporal Philippe Paris
Adolphe Menjou
General Geoge Broulard
George Macready
General Paul Mireau
Wayne Morris
Lieutenant Roget
Major Saint-Auban
Joseph Turkel
Private Pierre Arnaud
Christiane Kubrick (as Susanne Christian)
German singer
Jerry Hausner
Proprietor of cafe
Peter Capell
Narrator/Court-martial official
Emile Meyer
Father Dupree
Sergeant Boulanger
Kem Dibbs
Private Lejeune
Timothy Carey
Private Maurice Ferol
James B. Harris
Calder Willingham
Based on the novel by
Humphrey Cobb
Photographed by
George Krause
Hannes Staudinger
Ludwig Reiber
American production manager
John Pommer
German production manager
George von Block
Eva Kroll
Arthur Schramm
Ace in the Hole
Wooden Crosses
Raymond Bernard
Paths of Glory: "We Have Met the Enemy . . ."
The ceremony of execution, seen against the background of the château, gains impact from Kubrick's deliberate pacing and dynamic manipulation of wide-angle perspectives. The camera advances slowly and inexorably toward the three stakes where the m…
By James Naremore
On Film / Essays — Oct 23, 2010
At Work with Curtis Tsui on Paths of Glory
I work in the editorial department here at Criterion, and I've recently taken it on myself to do a little poking around at the office, to find out what my colleagues have going on and share that with visitors to the Current. Producer Curtis Tsui is…
Inside Criterion / Production Notes — Aug 5, 2010
Terry Gilliam's Closet Picks
While in town for the release of his new movie The Man Who Killed Don Quixote, the legendary filmmaker stopped by to pick up some Criterion favorites.
Inside Criterion / Closet Picks — May 10, 2019
David Simon Unravels the Moral Twists of Paths of Glory
The creator of The Wire takes inspiration from the narrative and moral complexity of Stanley Kubrick's war masterpiece.
Pat Healy's Top 10
Pat Healy is an actor who has appeared in dozens of films, including Compliance, Cheap Thrills, and The Assassination of Jesse James by the Coward Robert Ford.
Celebrating Kirk Douglas's Centennial
With a career spanning more than seven decades, Kirk Douglas has long since earned his place among the most luminous figures in Hollywood history. After cutting his teeth on the New York stage, he began his film career in the 1946 Barbara Stanwyck ve…
From the Kubrick Archives
On what would have been the iconic filmmaker's eighty-eighth birthday, we're celebrating him with a selection of essays, photos, and videos from our releases.
Troy Miller's Top 10
Troy Miller is a director and producer whose credits include the hit television comedies Mr. Show, Arrested Development, The Office, Flight of the Conchords, and Parks and Recreation.
Jesse Malin's Top 10
After playing in hard-core and glam bands throughout the 1980s and '90s, Queens-born singer-songwriter Jesse Malin released his first solo album, The Fine Art of Self Destruction, in 2002.
Roger Corman's Top 10
A genuine American movie legend, the eighty-seven-year-old producer and director Roger Corman has been in the film business since the early 1950s.
Nicholas Stoller's Top 10
Nicholas Stoller directed the comedies Forgetting Sarah Marshall, Get Him to the Greek, and The Five-Year Engagement.
Andrew Weil's Top 10
For decades, Andrew Weil has been one of the best-known doctors in America.
William Friedkin's Top 10
"I discovered Criterion in the late eighties with the laserdisc of
Citizen Kane, which I still watch," writes director William Friedkin, whose films include The French Connection, The Exorcist, Sorcerer, and 2011's Killer Joe.
Michael Korda's Top 10
Author Michael Korda (Charmed Lives: A Family Romance) writes: Few things are more challenging than picking ten favorites out of such a long list of distinguished films.
Alec Baldwin's Top 10
Actor Alec Baldwin's film credits include Beetlejuice, Miami Blues, Glengarry Glen Ross, The Royal Tenenbaums, The Cooler (for which he was nominated for an Oscar), and The Departed. He has also won two Emmys for his role as Jack Donaghy on NBC's
He Is Spartacus
Grauman's Chinese Theater in Los Angeles will host a special screening Friday, April 29, of Stanley Kubrick's Spartacus, as part of the annual TCM Classic Film Festival—and the mighty gladiator himself will be there. Kirk Douglas, who at ninety…
Guillermo del Toro's Top 10
In compiling his top ten Criterions, Cronos director Guillermo del Toro had a hell of a time limiting himself. Del Toro humorously bemoaned the "unfair, arbitrary, and sadistic top ten practice," so instead he decided on ties or rather, "themat
Caption Contest Winners
Last month, we asked you to give us a hand in creating brief ad taglines for our October titles. The response, in comments on the Criterion Current, was so overwhelming that we had trouble narrowing it down. Congratulations to the winners, Andy J., …
Inside Criterion / FYI
With Paths of Glory (1958), director Stanley Kubrick established himself not simply as the leading commercial filmmaker of his generation, but a world-class talent as well. Based on a novel by Humphrey Cobb, this tragic tale of World War I was immedi…
By David Ehrenstein


text:
Naomi Campbell wears hazmat suit to airport amid coronavirus outbreak
Tamara Hardingham-Gill, CNN • Updated 12th March 2020
(CNN) — Naomi Campbell has long been an advocate of staying germ-free while traveling.
The supermodel even posted a video of her intense pre-flight ritual, which involved wiping down everything close to her airplane seat with Dettol anti-bacterial wipes, last year.
So, it's perhaps no surprise the 49-year-old has opted to step things up considerably amid the novel coronavirus outbreak.
Campbell recently posted several images of herself boarding a plane at Los Angeles International Airport on Tuesday while wearing a hazmat suit, a pair of goggles, a face mask and pink latex gloves.
In one photo, she poses inside Tom Bradley International Terminal with her suitcase, while another shows her on-board a plane wearing a cape draped over the protective suit, with one latex-covered hand clutching her mobile phone to her ear and the other gripping on to a transparent plastic bag.
Private jets are taking off because of coronavirus
'Safety first'
Campbell captioned the images with the words, "Safety First. NEXT LEVEL," before pledging to post a "full video" on her YouTube channel shortly.
While the supermodel's precautionary outfit was given the seal of approval by many of her followers, others accused her of making light of the deadly outbreak, which has infected over a 100,000 people and killed over 4,000 across the world.
Campbell spoke of her techniques for avoiding germs while flying during a five-minute video shared on her YouTube channel last summer.
"Clean anything that you could possibly touch," she advised, before wiping her seat, seat belt, tray table, TV screen, remote control and window with anti-bacterial wipes.
"This is what I do on every plane I get on. I do not care what people think of me. It's my health and it makes me feel better."
After putting on a sanitary face mask before take-off, Campbell went on to stress the rigorous routine has helped her to stay healthy during her lengthy modeling career, which has spanned three decades.
"I mean as much as I travel, I should get sick so much more with colds and stuff," she said.
"I'm blessed that I don't. I really think that this helps me, my little routine."
While Campbell's approach might seem a little on the extreme side, travelers are being instructed to wash or sanitize their hands after touching surfaces in airports and planes as world leaders attempt to contain coronavirus.
According to infectious disease experts, frequent hand washing is one of the best defenses against the spread of such viruses.


text:
Black unemployment rate lowest in nearly 5 years
by Steve Hargreaves @hargreavesCNN August 2, 2013: 12:26 PM ET
The unemployment rate for black Americans hit its lowest level since December 2008.
According to the government's latest jobs report, 12.6% of black Americans were unemployed. That's down from a high of 16.5% in August of 2011.
But the current unemployment rate for blacks is considerably higher than the rate of 7.4% for the overall population. Historically, the black unemployment rate has always been higher, largely due to long term structural trends that include a lower education level and a more limited social circle, according to Heidi Shierholz, an economist Economic Policy Institute.
Shierholz noted that the unemployment rate for blacks isn't falling any faster than it is for the population at large, which is also at its lowest rate in nearly five years.
Related: Obama's jobs record: Where are we now?
"The black population is not seeing different overall trends," said Shierholz.
Still, the unemployment rate for blacks was 13.7% in June. So the most recent move has been more dramatic. Shierholz noted that due to the smaller sample size of data, the swings in the unemployment rate for blacks can be more volatile.
Blacks are benefiting from the same forces that are driving unemployment down for the population at large -- a slowly improving economy that's producing a fair amount of new jobs. But many of them are lower wage service industry professions or part time positions.
Still, the good news is the black unemployment rate isn't falling because they are leaving the workforce in greater numbers. The labor force participation rate for blacks has remained relatively constant over the last few years, hovering between 61% and 62%.
CNNMoney (New York) First published August 2, 2013: 12:26 PM ET


text:
What's The Next Move For Amazon Aggregators?
Amazon aren't the only ones to capitalize on the success of their small business sellers.
While Amazon sellers may have seen a surge of interest from consumers over the past 24 months, representing close to 60 percent of the retailer's business in 2021, entirely new developments and industries have sprouted in the wake of Amazon's third-party surge over the past few years.
But perhaps the biggest development of all in 2021 for Amazon sellers? The rise of the Amazon aggregator market.
It's a tempting proposition for many third-party sellers hoping to make a profitable exit from the Amazon landscape. But can the market for Amazon brand aggregators continue to thrive in the face of new challenges in eCommerce?
Key Players in the Amazon Aggregator Market
Thrasio may dominate the Amazon aggregator market with over $750 Million being raised during its most recent round of funding, but they're hardly the only ones to capitalize on acquiring Amazon businesses.
Amazon aggregators first drew attention in 2021 after the announcement that Seattle's Cap Hill Brands managed to secure $150 Million in funding. Not to be outdone, Austin's Elevate Brands secured $372 Million in November 2021, while New York's Forum Brands and the German based Berlin Brands Group managed to raise $100 Million respectively in that same period.
But perhaps the most significant indicator of interest in Amazon aggregators was in the EU, which saw over $1 Billion raised in a single day in September 2021.
But the 2022 market for Amazon aggregators is a different beast entirely. According to a recent review from Marketplace Pulse, funding has decreased by a disheartening 80 percent in 2022 compared to the previous year.
Yet in spite of this, it was recently announced that Elevate Brands has acquired an additional $400 Million in financing, bringing the total amount of their funding to just under $600 Million to date.
For every success story, there's a failure or three for both brands as well as Amazon aggregators. But how did the market grow so rapidly? And what does the future hold?
Why the Amazon Aggregator Market Grew in 2021
The Amazon aggregator market didn't sprout up overnight. The concept of private equity-based rollups is almost as old as private equity itself.
But Amazon aggregators became an overnight success in 2020 fueled as much by the pandemic as the need for a data-rich platform—factors which Amazon capitalized upon to the tune of over $386 Billion.
The third party seller market is one that has helped sustain Amazon, even as they saw its stock performance take a rollercoaster ride during 2021. That's largely because the new wave of digital consumers demand digitally native brands. Amazon FBA brands know far too well that consumers demand efficient fulfillment options and service in addition to a high performance product.
But taking a brand off Amazon can result in a disconnect—particularly for aggregators who fail to take into account exactly how much time and effort it takes to manage a brand's fulfillment services.
The Potential for Amazon Sellers
The performance of Amazon businesses has spawned an entirely new empire that could very well threaten to compete with Amazon itself. In September 2021, leading third-party health and wellness supplier Pharma packs went public via an SPAC merger with a valuation of $1.55 Billion.
Private label brands have always provided low overhead in manufacturing costs for Amazon sellers, allowing sellers a greater focus on marketing strategies and strategic development than in house brands. But private label brands aren't a tremendous focus for most aggregators unless they have a proven track record of sales and innovation behind them.
The digital economy demands freshness and innovation to survive—neither of which are always factors physical retail can provide. Marketplace Pulse recently estimated that the amount of cumulative capital being poured into the Amazon aggregator market reached approximately $10 Billion in September 2021.
But the third-party marketplace on Amazon itself is populated by as many inferior brands as it is by top sellers. Performance is never stagnant; and aggregators looking to acquire brands may not always take into account that a brand's history evolves at the same rate consumer purchasing habits do.
The Perils and Pitfalls of Amazon Business
The reality is that eCommerce itself can present an entirely new set of challenges private equity may not necessarily be aware of.
In August 2021, it was reported that one of China's busiest ports temporarily shut down after a single employee contracted the novel coronavirus, placing additional burden on an already overwhelmed global supply chain.
With retail sales now predicted to exceed $4.44 Trillion in the US at the end of 2021, the news presented a particular crisis for retailers. But navigating a global supply chain crisis presents a dangerous challenge for any digital brand.
Prior to 2020, much of the inventory management strain in eCommerce was the result of overstock. In 2021, it's as much a question of stock-outs as it is any number of factors—not the least of which is market saturation.
The Amazon aggregator market has grown by $7 Billion since April of 2020. With over 70 agencies operating in at least 12 separate countries, there's every reason to consider the segment to be the digital equivalent of a gold rush. And it can certainly seem attractive to over 15,000 third-party brands on Amazon earning in excess of $1 Million—some of whom can reportedly expect an EBITDA (Earnings Before Interest, Taxes, Depreciation, and Amortization) up to 8 times higher in their valuation as a result.
But it's not just the potential for $4 Trillion loss of revenue in supply chain disruption which presents a pitfall for eCommerce management. It's the operational strain of managing multiple brands, particularly for agencies without extensive expertise in the quirks of the Amazon marketplace.
"Amazon aggregators are gobbling up brands faster than their internal teams can grow them due to resource constraints and expertise," said Josh Levine, Managing Partner at Color More Lines. "Amazon is a lucrative but challenging marketplace to grow brands without deep, data-driven knowledge to scale successfully."
The Future For Amazon Aggregators
Amazon is facing their own crisis in managing digitally native brands; this time in the form of bad actors. In May, a widely publicized expulsion of fourteen different top-selling brands for review manipulation resulted in a loss of sales of over $1 Billion.
If Amazon aggregators aren't careful in selecting brands, that loss could be potentially much higher. The dynamics of eCommerce are entirely different from other forms of tech acquisition. Brand growth in the former is largely contingent on short-term returns—and the loss of an Amazon-based identity could result in the loss of brand identity altogether.
"Our Amazon and Walmart agency is turnkey and augments aggregator teams to help them grow their brands faster than they could on their own," explained Levine. "Brands need to ensure that the firms they work with also have the experience and dedication to foster their own growth."
Brand Growth and Amazon Aggregators
There's no telling if the aggregator market is a bubble poised to burst. And at the moment, there is no word on whether or not Amazon aggregators have any strong interest in looking at other platforms—including Walmart, Amazon's chief competitor.
But at a time in which the sheer plethora of Amazon sellers has led to market saturation and undifferentiated product lines, brands can't afford to worry about aggregator acquisition unless their offerings are unique, viable and able to establish long-term consumer interest. It can be enough of a task to maintain visibility on Amazon. And brands who can't may find Amazon aggregators aren't quite the gold rush they appear to be.
There's a difference between buying a brand and building a brand. And there's a difference between developing an Amazon business and acquiring one.
Digital commerce is only as strong as the brands that help build it. It's not a question of portfolio growth for an agency, but of the growth in a brand's development.
Need help developing a fully fledged brand identity? Find out more at Color More Lines.
Marketplace Expansion
Will 2022 Be The Dawning Of A New Era For eCommerce?


text:
import os
from unittest import mock

import tempfile

from cinderclient import exceptions as cinder_exception
import eventlet
from oslo_concurrency import processutils
from oslo_serialization import jsonutils

from ec2api.api import image as image_api
from ec2api import exception
from ec2api.tests.unit import base
from ec2api.tests.unit import fakes
from ec2api.tests.unit import matchers
from ec2api.tests.unit import tools

AMI_MANIFEST_XML = """<?xml version="1.0" ?>
<manifest>
        <version>2011-06-17</version>
        <bundler>
                <name>test-s3</name>
                <version>0</version>
                <release>0</release>
        </bundler>
        <machine_configuration>
                <architecture>x86_64</architecture>
                <block_device_mapping>
                        <mapping>
                                <virtual>ami</virtual>
                                <device>sda1</device>
                        </mapping>
                        <mapping>
                                <virtual>root</virtual>
                                <device>/dev/sda1</device>
                        </mapping>
                        <mapping>
                                <virtual>ephemeral0</virtual>
                                <device>sda2</device>
                        </mapping>
                        <mapping>
                                <virtual>swap</virtual>
                                <device>sda3</device>
                        </mapping>
                </block_device_mapping>
                <kernel_id>%(aki-id)s</kernel_id>
                <ramdisk_id>%(ari-id)s</ramdisk_id>
        </machine_configuration>
        <image>
                <ec2_encrypted_key>foo</ec2_encrypted_key>
                <user_encrypted_key>foo</user_encrypted_key>
                <ec2_encrypted_iv>foo</ec2_encrypted_iv>
                <parts count="1">
                        <part index="0">
                               <filename>foo</filename>
                        </part>
                </parts>
        </image>
</manifest>
""" % {'aki-id': fakes.ID_EC2_IMAGE_AKI_1,
       'ari-id': fakes.ID_EC2_IMAGE_ARI_1}

FILE_MANIFEST_XML = """<?xml version="1.0" ?>
<manifest>
        <image>
                <ec2_encrypted_key>foo</ec2_encrypted_key>
                <user_encrypted_key>foo</user_encrypted_key>
                <ec2_encrypted_iv>foo</ec2_encrypted_iv>
                <parts count="1">
                        <part index="0">
                               <filename>foo</filename>
                        </part>
                </parts>
        </image>
</manifest>
"""

class ImageTestCase(base.ApiTestCase):

    @mock.patch('ec2api.api.instance._is_ebs_instance')
    def _test_create_image(self, instance_status, no_reboot, is_ebs_instance):
        self.set_mock_db_items(fakes.DB_INSTANCE_2)
        os_instance = mock.MagicMock()
        os_instance.configure_mock(id=fakes.ID_OS_INSTANCE_2,
                                   status=instance_status)
        stop_called = iter([False, True])
        os_instance.stop.side_effect = lambda: next(stop_called)
        os_instance.get.side_effect = lambda: (setattr(os_instance, 'status',
                                                       'SHUTOFF')
                                               if next(stop_called) else None)
        image_id = fakes.random_ec2_id('ami')
        os_image_id = fakes.random_os_id()
        os_instance.create_image.return_value = os_image_id
        self.glance.images.get.return_value = fakes.OSImage(
            {'id': os_image_id},
            from_get=True)
        self.nova.servers.get.return_value = os_instance
        is_ebs_instance.return_value = True
        self.db_api.add_item.side_effect = tools.get_db_api_add_item(image_id)

        resp = self.execute('CreateImage',
                            {'InstanceId': fakes.ID_EC2_INSTANCE_2,
                             'Name': 'fake_name',
                             'Description': 'fake desc',
                             'NoReboot': str(no_reboot)})
        self.assertEqual({'imageId': image_id},
                         resp)
        self.db_api.get_item_by_id.assert_called_once_with(
            mock.ANY, fakes.ID_EC2_INSTANCE_2)
        self.nova.servers.get.assert_called_once_with(fakes.ID_OS_INSTANCE_2)
        is_ebs_instance.assert_called_once_with(mock.ANY, os_instance.id)
        expected_image = {'is_public': False,
                          'description': 'fake desc'}
        if no_reboot:
            expected_image['os_id'] = os_image_id
        self.db_api.add_item.assert_called_once_with(
            mock.ANY, 'ami', expected_image)
        if not no_reboot:
            eventlet.sleep()
        if not no_reboot:
            os_instance.stop.assert_called_once_with()
            os_instance.get.assert_called_once_with()
            os_instance.start.assert_called_once_with()
        if no_reboot:
            os_instance.create_image.assert_called_once_with('fake_name')
        else:
            os_instance.create_image.assert_called_once_with(
                'fake_name', metadata={'ec2_id': image_id})
            self.db_api.update_item.assert_called_once_with(
                mock.ANY, {'id': image_id,
                           'is_public': False,
                           'description': 'fake desc',
                           'os_id': os_image_id,
                           'vpc_id': None})

        self.db_api.reset_mock()
        self.nova.servers.reset_mock()

    def test_create_image(self):
        self._test_create_image('ACTIVE', False)
        self._test_create_image('SHUTOFF', True)

    @mock.patch('ec2api.api.instance._is_ebs_instance')
    def test_register_image_by_url(self, is_ebs_instance):
        self.set_mock_db_items(fakes.DB_INSTANCE_2)
        is_ebs_instance.return_value = True

        # Setup the mock parameters
        image_id = fakes.random_ec2_id('ami')
        os_image_id = fakes.random_os_id()
        self.glance.images.create.return_value = fakes.OSImage(
            {'id': os_image_id},
            from_get=True)
        self.db_api.add_item.side_effect = tools.get_db_api_add_item(image_id)

        # Setup Import Command
        import_command = 'RegisterImage'

        # Setup the import arguments
        args = {
            'Name': 'TestImage123',
            'ImageLocation':
                fakes.LOCATION_IMAGE_2,
            'Architecture': 'x86_64'
        }

        # Execute the import image process
        resp = self.execute(import_command, args)

        # Assert that the image returned is equal to what was expected
        self.assertEqual({'imageId': image_id}, resp)

        # Assert that Glance Image Create was called
        self.glance.images.create.assert_called_once_with(
            name='TestImage123',
            disk_format='raw',
            container_format='bare',
            visibility='private',
            architecture='x86_64',
            image_location=fakes.LOCATION_IMAGE_2)

        # Assert that Glance Image Import was called
        self.glance.images.image_import.assert_called_once_with(
            os_image_id,
            method='web-download',
            uri=fakes.LOCATION_IMAGE_2)

        # Assert that the image was created
        expected_image = {'is_public': False,
                          'os_id': mock.ANY,
                          'description': None}
        self.db_api.add_item.assert_called_once_with(
            mock.ANY, 'ami', expected_image)

        # Reset all test settings/state
        self.db_api.reset_mock()
        self.glance.reset_mock()

    @mock.patch('ec2api.api.instance._is_ebs_instance')
    def test_create_image_invalid_parameters(self, is_ebs_instance):
        self.set_mock_db_items(fakes.DB_INSTANCE_1)
        is_ebs_instance.return_value = False

        self.assert_execution_error('InvalidParameterValue', 'CreateImage',
                                    {'InstanceId': fakes.ID_EC2_INSTANCE_1,
                                     'Name': 'fake_name'})

    @mock.patch('ec2api.api.image._s3_create')
    def test_register_image_by_s3(self, s3_create):
        s3_create.return_value = fakes.OSImage(fakes.OS_IMAGE_1)
        self.db_api.add_item.side_effect = (
            tools.get_db_api_add_item(fakes.ID_EC2_IMAGE_1))

        resp = self.execute(
            'RegisterImage',
            {'ImageLocation': fakes.LOCATION_IMAGE_1})
        self.assertThat(resp, matchers.DictMatches(
            {'imageId': fakes.ID_EC2_IMAGE_1}))

        s3_create.assert_called_once_with(
            mock.ANY,
            {'name': fakes.LOCATION_IMAGE_1,
             'image_location': fakes.LOCATION_IMAGE_1})
        s3_create.reset_mock()

        resp = self.execute(
            'RegisterImage',
            {'ImageLocation': fakes.LOCATION_IMAGE_1,
             'Name': 'an image name'})
        self.assertThat(resp, matchers.DictMatches(
            {'imageId': fakes.ID_EC2_IMAGE_1}))

        s3_create.assert_called_once_with(
            mock.ANY,
            {'name': 'an image name',
             'image_location': fakes.LOCATION_IMAGE_1})

    @mock.patch('ec2api.api.ec2utils.get_os_image')
    def test_register_image_by_bdm(self, get_os_image):
        self.glance.images.create.return_value = (
            fakes.OSImage(fakes.OS_IMAGE_2))
        self.glance.images.upload.return_value = (
            fakes.OSImage(fakes.OS_IMAGE_2))
        self.cinder.volume_snapshots.get.side_effect = (
            tools.get_by_1st_arg_getter(
                {fakes.ID_OS_SNAPSHOT_1: (
                    fakes.OSSnapshot(fakes.OS_SNAPSHOT_1))},
                notfound_exception=cinder_exception.NotFound(404)))
        self.db_api.add_item.side_effect = (
            tools.get_db_api_add_item(fakes.ID_EC2_IMAGE_2))
        self.set_mock_db_items(fakes.DB_SNAPSHOT_1, fakes.DB_SNAPSHOT_2,
                               fakes.DB_IMAGE_AKI_1, fakes.DB_IMAGE_ARI_1)
        get_os_image.side_effect = [fakes.OSImage(fakes.OS_IMAGE_AKI_1),
                                    fakes.OSImage(fakes.OS_IMAGE_ARI_1)]

        resp = self.execute(
            'RegisterImage',
            {'RootDeviceName': fakes.ROOT_DEVICE_NAME_IMAGE_2,
             'Name': 'fake_name',
             'KernelId': fakes.ID_EC2_IMAGE_AKI_1,
             'RamdiskId': fakes.ID_EC2_IMAGE_ARI_1,
             'BlockDeviceMapping.1.DeviceName': fakes.ROOT_DEVICE_NAME_IMAGE_2,
             'BlockDeviceMapping.1.Ebs.SnapshotId': fakes.ID_EC2_SNAPSHOT_1,
             'BlockDeviceMapping.2.DeviceName': '/dev/vdf',
             'BlockDeviceMapping.2.Ebs.VolumeSize': '100',
             'BlockDeviceMapping.2.Ebs.DeleteOnTermination': 'False',
             'BlockDeviceMapping.3.DeviceName': '/dev/vdg',
             'BlockDeviceMapping.3.Ebs.SnapshotId': fakes.ID_EC2_SNAPSHOT_1,
             'BlockDeviceMapping.3.Ebs.VolumeSize': '55',
             'BlockDeviceMapping.3.Ebs.DeleteOnTermination': 'True',
             'BlockDeviceMapping.4.DeviceName': '/dev/vdh',
             'BlockDeviceMapping.4.Ebs.SnapshotId': fakes.ID_EC2_SNAPSHOT_2})
        self.assertThat(resp, matchers.DictMatches(
            {'imageId': fakes.ID_EC2_IMAGE_2}))
        self.db_api.add_item.assert_called_once_with(
            mock.ANY, 'ami', {'os_id': fakes.ID_OS_IMAGE_2,
                              'is_public': False,
                              'description': None})
        self.assertEqual(1, self.glance.images.create.call_count)
        self.assertEqual((), self.glance.images.create.call_args[0])
        self.assertIsInstance(
            self.glance.images.create.call_args[1], dict)
        bdm = self.glance.images.create.call_args[1].pop(
            'block_device_mapping', 'null')
        self.assertEqual(
            {'visibility': 'private',
             'name': 'fake_name',
             'kernel_id': fakes.ID_OS_IMAGE_AKI_1,
             'ramdisk_id': fakes.ID_OS_IMAGE_ARI_1,
             'root_device_name': fakes.ROOT_DEVICE_NAME_IMAGE_2,
             'container_format': 'bare',
             'disk_format': 'raw',
             'bdm_v2': 'True'},
            self.glance.images.create.call_args[1])
        self.assertEqual([{'boot_index': 0,
                           'delete_on_termination': True,
                           'destination_type': 'volume',
                           'device_name': fakes.ROOT_DEVICE_NAME_IMAGE_2,
                           'source_type': 'snapshot',
                           'snapshot_id': fakes.ID_OS_SNAPSHOT_1,
                           'volume_size': 1},
                          {'boot_index': -1,
                           'delete_on_termination': False,
                           'destination_type': 'volume',
                           'device_name': '/dev/vdf',
                           'source_type': 'blank',
                           'volume_size': 100},
                          {'boot_index': -1,
                           'delete_on_termination': True,
                           'destination_type': 'volume',
                           'device_name': '/dev/vdg',
                           'source_type': 'snapshot',
                           'snapshot_id': fakes.ID_OS_SNAPSHOT_1,
                           'volume_size': 55},
                          {'boot_index': -1,
                           'delete_on_termination': True,
                           'destination_type': 'volume',
                           'device_name': '/dev/vdh',
                           'source_type': 'snapshot',
                           'snapshot_id': fakes.ID_OS_SNAPSHOT_2}],
                         jsonutils.loads(bdm))
        get_os_image.assert_has_calls(
            [mock.call(mock.ANY, fakes.ID_EC2_IMAGE_AKI_1),
             mock.call(mock.ANY, fakes.ID_EC2_IMAGE_ARI_1)])
        self.cinder.volume_snapshots.get.assert_any_call(
            fakes.ID_OS_SNAPSHOT_1)

    def test_register_image_invalid_parameters(self):
        self.assert_execution_error(
            'InvalidParameterCombination', 'RegisterImage', {})

    def test_deregister_image(self):
        self._setup_model()

        # normal flow
        resp = self.execute('DeregisterImage',
                            {'ImageId': fakes.ID_EC2_IMAGE_1})
        self.assertThat(resp, matchers.DictMatches({'return': True}))
        self.db_api.delete_item.assert_called_once_with(
            mock.ANY, fakes.ID_EC2_IMAGE_1)
        self.glance.images.delete.assert_called_once_with(
            fakes.ID_OS_IMAGE_1)

        # deregister image which failed on asynchronously creation
        self.glance.reset_mock()
        image_id = fakes.random_ec2_id('ami')
        self.add_mock_db_items({'id': image_id,
                                'os_id': None,
                                'state': 'failed'})
        resp = self.execute('DeregisterImage',
                            {'ImageId': image_id})
        self.assertThat(resp, matchers.DictMatches({'return': True}))
        self.db_api.delete_item.assert_called_with(mock.ANY, image_id)
        self.assertFalse(self.glance.images.delete.called)

    def test_deregister_image_invalid_parameters(self):
        self._setup_model()

        self.assert_execution_error('InvalidAMIID.NotFound', 'DeregisterImage',
                                    {'ImageId': fakes.random_ec2_id('ami')})

        # deregister asynchronously creating image
        image_id = fakes.random_ec2_id('ami')
        self.add_mock_db_items({'id': image_id,
                                'os_id': None})
        self.assert_execution_error('IncorrectState',
                                    'DeregisterImage',
                                    {'ImageId': image_id})

    def test_describe_images(self):
        self._setup_model()

        resp = self.execute('DescribeImages', {})
        self.assertThat(
            resp,
            matchers.DictMatches(
                {'imagesSet': [fakes.EC2_IMAGE_1, fakes.EC2_IMAGE_2]},
                orderless_lists=True),
            verbose=True)

        self.db_api.get_items.assert_any_call(mock.ANY, 'ami')
        self.db_api.get_items.assert_any_call(mock.ANY, 'aki')
        self.db_api.get_items.assert_any_call(mock.ANY, 'ari')

        self.db_api.get_items_by_ids = tools.CopyingMock(
            side_effect=self.db_api.get_items_by_ids.side_effect)

        resp = self.execute('DescribeImages',
                            {'ImageId.1': fakes.ID_EC2_IMAGE_1})
        self.assertThat(resp,
                        matchers.DictMatches(
                            {'imagesSet': [fakes.EC2_IMAGE_1]},
                            orderless_lists=True))
        self.db_api.get_items_by_ids.assert_any_call(
            mock.ANY, set([fakes.ID_EC2_IMAGE_1]))

        self.check_filtering(
            'DescribeImages', 'imagesSet',
            [('architecture', 'x86_64'),
             ('block-device-mapping.device-name', '/dev/sdb2'),
             ('block-device-mapping.snapshot-id', fakes.ID_EC2_SNAPSHOT_1),
             ('block-device-mapping.volume-size', 22),
             ('description', 'fake desc'),
             ('image-id', fakes.ID_EC2_IMAGE_1),
             ('image-type', 'machine'),
             ('is-public', True),
             ('kernel_id', fakes.ID_EC2_IMAGE_AKI_1,),
             ('name', 'fake_name'),
             ('owner-id', fakes.ID_OS_PROJECT),
             ('ramdisk-id', fakes.ID_EC2_IMAGE_ARI_1),
             ('root-device-name', fakes.ROOT_DEVICE_NAME_IMAGE_1),
             ('root-device-type', 'instance-store'),
             ('state', 'available')])
        self.check_tag_support(
            'DescribeImages', 'imagesSet',
            fakes.ID_EC2_IMAGE_1, 'imageId',
            ('ami', 'ari', 'aki'))

    def test_describe_images_invalid_parameters(self):
        self._setup_model()

        self.assert_execution_error('InvalidAMIID.NotFound', 'DescribeImages',
                                    {'ImageId.1': fakes.random_ec2_id('ami')})

        self.glance.images.list.side_effect = lambda: []

        self.assert_execution_error('InvalidAMIID.NotFound', 'DescribeImages',
                                    {'ImageId.1': fakes.ID_EC2_IMAGE_1})

    def test_describe_image_attributes(self):
        self._setup_model()

        def do_check(attr, ec2_image_id, response):
            resp = self.execute('DescribeImageAttribute',
                                {'ImageId': ec2_image_id,
                                 'Attribute': attr})
            response['imageId'] = ec2_image_id
            self.assertThat(resp,
                            matchers.DictMatches(response,
                                                 orderless_lists=True),
                            verbose=True)

        do_check('launchPermission',
                 fakes.ID_EC2_IMAGE_2,
                 {'launchPermission': [{'group': 'all'}]})

        do_check('kernel',
                 fakes.ID_EC2_IMAGE_1,
                 {'kernel': {'value': fakes.ID_EC2_IMAGE_AKI_1}})

        do_check('ramdisk',
                 fakes.ID_EC2_IMAGE_1,
                 {'ramdisk': {'value': fakes.ID_EC2_IMAGE_ARI_1}})

        do_check('rootDeviceName',
                 fakes.ID_EC2_IMAGE_1,
                 {'rootDeviceName': fakes.ROOT_DEVICE_NAME_IMAGE_1})

        do_check('rootDeviceName',
                 fakes.ID_EC2_IMAGE_2,
                 {'rootDeviceName': fakes.ROOT_DEVICE_NAME_IMAGE_2})

        do_check('blockDeviceMapping',
                 fakes.ID_EC2_IMAGE_1,
                 {'blockDeviceMapping': (
                        fakes.EC2_IMAGE_1['blockDeviceMapping'])})

        do_check('blockDeviceMapping',
                 fakes.ID_EC2_IMAGE_2,
                 {'blockDeviceMapping': (
                        fakes.EC2_IMAGE_2['blockDeviceMapping'])})

    def test_describe_image_attributes_invalid_parameters(self):
        image_id = fakes.random_ec2_id('ami')
        self.set_mock_db_items({'id': image_id,
                                'os_id': None})
        self.assert_execution_error('IncorrectState',
                                    'DescribeImageAttribute',
                                    {'ImageId': image_id,
                                     'Attribute': 'kernel'})

    def test_modify_image_attributes(self):
        self._setup_model()

        resp = self.execute('ModifyImageAttribute',
                            {'imageId': fakes.ID_EC2_IMAGE_1,
                             'attribute': 'launchPermission',
                             'operationType': 'add',
                             'userGroup.1': 'all'})
        self.assertThat(resp, matchers.DictMatches({'return': True}))
        self.glance.images.update.assert_called_once_with(
                fakes.ID_OS_IMAGE_1, visibility='public')

    def test_modify_image_attributes_invalid_parameters(self):
        image_id = fakes.random_ec2_id('ami')
        self.set_mock_db_items({'id': image_id,
                                'os_id': None})
        self.assert_execution_error('IncorrectState',
                                    'ModifyImageAttribute',
                                    {'ImageId': image_id,
                                     'Attribute': 'kernel'})

    def _setup_model(self):
        self.set_mock_db_items(fakes.DB_IMAGE_1, fakes.DB_IMAGE_2,
                               fakes.DB_SNAPSHOT_1, fakes.DB_SNAPSHOT_2,
                               fakes.DB_IMAGE_AKI_1, fakes.DB_IMAGE_ARI_1,
                               fakes.DB_VOLUME_1, fakes. DB_VOLUME_2)
        self.db_api.get_public_items.return_value = []

        # NOTE(ft): glance.image.list returns an iterator, not just a list
        self.glance.images.list.side_effect = (
            lambda: (fakes.OSImage(i)
                     for i in (fakes.OS_IMAGE_1, fakes.OS_IMAGE_2)))
        self.glance.images.get.side_effect = (
            lambda os_id: (fakes.OSImage(fakes.OS_IMAGE_1, from_get=True)
                           if os_id == fakes.ID_OS_IMAGE_1 else
                           fakes.OSImage(fakes.OS_IMAGE_2, from_get=True)
                           if os_id == fakes.ID_OS_IMAGE_2 else
                           None))

class ImagePrivateTestCase(base.BaseTestCase):

    def test_format_image(self):
        image_ids = {fakes.ID_OS_IMAGE_1: fakes.ID_EC2_IMAGE_1,
                     fakes.ID_OS_IMAGE_AKI_1: fakes.ID_EC2_IMAGE_AKI_1,
                     fakes.ID_OS_IMAGE_ARI_1: fakes.ID_EC2_IMAGE_ARI_1}
        os_image = {'id': fakes.ID_OS_IMAGE_1,
                    'owner': fakes.ID_OS_PROJECT,
                    'created_at': fakes.TIME_CREATE_IMAGE,
                    'visibility': 'private',
                    'status': 'active',
                    'container_format': 'ami',
                    'name': 'fake_name'}

        # check name and location attributes for an unnamed image
        os_image['image_location'] = 'location'
        os_image['name'] = None

        image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, fakes.OSImage(os_image),
                None, image_ids)

        self.assertEqual('location', image['imageLocation'])
        self.assertEqual('location', image['name'])

        # check name and location attributes for complete image
        os_image['image_location'] = None
        os_image['name'] = 'fake_name'

        image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, fakes.OSImage(os_image),
                None, image_ids)

        self.assertEqual('None (fake_name)', image['imageLocation'])
        self.assertEqual('fake_name', image['name'])

        # check ebs image type for bdm_v2 mapping type
        os_image['bdm_v2'] = True
        os_image['root_device_name'] = '/dev/vda'
        os_image['block_device_mapping'] = [
            {'boot_index': 0,
             'snapshot_id': fakes.ID_OS_SNAPSHOT_2,
             'source_type': 'snapshot',
             'destination_type': 'volume'}]

        image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, fakes.OSImage(os_image),
                None, image_ids,
                snapshot_ids={fakes.ID_OS_SNAPSHOT_2: fakes.ID_EC2_SNAPSHOT_2})

        self.assertEqual('ebs', image['rootDeviceType'])

        # check instance-store image attributes with no any device mappings
        os_image['bdm_v2'] = False
        os_image['root_device_name'] = '/dev/vda'
        os_image['block_device_mapping'] = []
        image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, fakes.OSImage(os_image),
                None, None)

        self.assertEqual('instance-store', image['rootDeviceType'])
        self.assertNotIn('blockDeviceMapping', image)

        # check Glance status translation
        os_image = fakes.OSImage({'id': fakes.ID_OS_IMAGE_1})

        def check_status_translation(status, expected):
            os_image.status = status
            image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, os_image, None, None)
            self.assertEqual(expected, image['imageState'],
                             "Wrong '%s' Glance status translation" % status)
        check_status_translation('queued', 'pending')
        check_status_translation('saving', 'pending')
        check_status_translation('active', 'available')
        check_status_translation('killed', 'deregistered')
        check_status_translation('pending_delete', 'deregistered')
        check_status_translation('deleted', 'deregistered')
        check_status_translation('deactivated', 'invalid')
        check_status_translation('unknown-status', 'error')

        # check internal state translation
        os_image.status = 'queued'

        def check_state_translation(state, expected):
            os_image.image_state = state
            image = image_api._format_image(
                'fake_context', fakes.DB_IMAGE_1, os_image, None, None)
            self.assertEqual(expected, image['imageState'],
                             "Wrong '%s' internal state translation" % state)

        for state in ('downloading', 'decrypting', 'untarring', 'uploading'):
            check_state_translation(state, 'pending')
        for state in ('failed_download', 'failed_decrypt', 'failed_untar',
                      'failed_upload'):
            check_state_translation(state, 'failed')
        os_image.status = 'active'
        check_state_translation('available', 'available')
        check_state_translation('unknown-state', 'available')

    def test_format_mappings(self):
        db_api = self.mock_db()
        # check virtual mapping formatting
        properties = {
            'mappings': [
                {'virtual': 'ami', 'device': '/dev/sda'},
                {'virtual': 'root', 'device': 'sda'},
                {'virtual': 'ephemeral0', 'device': 'sdb'},
                {'virtual': 'swap', 'device': 'sdc'},
                {'virtual': 'ephemeral1', 'device': 'sdd'},
                {'virtual': 'ephemeral2', 'device': 'sde'},
                {'virtual': 'ephemeral', 'device': 'sdf'},
                {'virtual': '/dev/sdf1', 'device': 'root'}],
        }
        expected = [
            {'virtualName': 'ephemeral0', 'deviceName': '/dev/sdb'},
            {'virtualName': 'swap', 'deviceName': '/dev/sdc'},
            {'virtualName': 'ephemeral1', 'deviceName': '/dev/sdd'},
            {'virtualName': 'ephemeral2', 'deviceName': '/dev/sde'},
        ]

        result = image_api._format_mappings('fake_context', properties)
        self.assertEqual(expected, result)

        # check bdm v2 formatting
        db_api.set_mock_items(fakes.DB_IMAGE_2, fakes.DB_VOLUME_3)
        properties = {
            'bdm_v2': True,
            'block_device_mapping': [
                {'boot_index': 0,
                 'snapshot_id': fakes.ID_OS_SNAPSHOT_1,
                 'source_type': 'snapshot',
                 'destination_type': 'volume'},
                {'boot_index': None,
                 'snapshot_id': fakes.ID_OS_SNAPSHOT_2,
                 'source_type': 'snapshot',
                 'destination_type': 'volume'},
                {'device_name': 'vdi',
                 'boot_index': -1,
                 'image_id': fakes.ID_OS_IMAGE_2,
                 'source_type': 'image',
                 'destination_type': 'volume',
                 'volume_size': 20},
                {'device_name': 'vdv',
                 'boot_index': -1,
                 'volume_id': fakes.ID_OS_VOLUME_3,
                 'source_type': 'volume',
                 'destination_type': 'volume'},
                {'device_name': 'vdb',
                 'boot_index': -1,
                 'source_type': 'blank',
                 'destination_type': 'volume',
                 'volume_size': 100,
                 'delete_on_termination': True},
            ],
        }
        expected = [
            {'deviceName': 'vdx',
             'ebs': {'snapshotId': fakes.ID_EC2_SNAPSHOT_1,
                     'deleteOnTermination': False}},
            {'ebs': {'snapshotId': fakes.ID_EC2_SNAPSHOT_2,
                     'deleteOnTermination': False}},
            {'deviceName': 'vdi',
             'ebs': {'snapshotId': fakes.ID_EC2_IMAGE_2,
                     'volumeSize': 20,
                     'deleteOnTermination': False}},
            {'deviceName': 'vdv',
             'ebs': {'snapshotId': fakes.ID_EC2_VOLUME_3,
                     'deleteOnTermination': False}},
            {'deviceName': 'vdb',
             'ebs': {'volumeSize': 100,
                     'deleteOnTermination': True}},
        ]
        result = image_api._format_mappings(
            'fake_context', properties, root_device_name='vdx',
            snapshot_ids={fakes.ID_OS_SNAPSHOT_1: fakes.ID_EC2_SNAPSHOT_1,
                          fakes.ID_OS_SNAPSHOT_2: fakes.ID_EC2_SNAPSHOT_2})
        self.assertEqual(expected, result)

        # check inheritance and generation of virtual name
        properties = {
            'mappings': [
                {'device': 'vdd', 'virtual': 'ephemeral1'},
            ],
            'bdm_v2': True,
            'block_device_mapping': [
                {'device_name': '/dev/vdb',
                 'source_type': 'blank',
                 'destination_type': 'local',
                 'guest_format': 'swap'},
                {'device_name': 'vdc',
                 'source_type': 'blank',
                 'destination_type': 'local',
                 'volume_size': 5},
                {'device_name': 'vde',
                 'source_type': 'blank',
                 'destination_type': 'local'},
            ],
        }
        expected = [
            {'deviceName': '/dev/vdd', 'virtualName': 'ephemeral1'},
            {'deviceName': '/dev/vdb', 'virtualName': 'swap'},
            {'deviceName': 'vdc', 'virtualName': 'ephemeral0'},
            {'deviceName': 'vde', 'virtualName': 'ephemeral2'},
        ]
        result = image_api._format_mappings('fake_context', properties)
        self.assertEqual(expected, result)

    def test_get_db_items(self):
        describer = image_api.ImageDescriber()
        describer.context = base.create_context()

        # NOTE(ft): the first requested image appears is user owend and public,
        # the second is absent
        db_api = self.mock_db()
        db_api.set_mock_items(fakes.DB_IMAGE_1)

        describer.ids = set([fakes.ID_EC2_IMAGE_1, fakes.ID_EC2_IMAGE_2])
        self.assertRaises(exception.InvalidAMIIDNotFound,
                          describer.get_db_items)

    def test_describe_images_being_created(self):
        db_api = self.mock_db()
        glance = self.mock_glance()
        context = base.create_context()
        image_id = fakes.random_ec2_id('ami')
        image = {'id': image_id,
                 'os_id': None,
                 'is_public': False,
                 'description': 'fake desc'}
        db_api.set_mock_items(image)
        db_api.get_public_items.return_value = []

        # describe cases when no glance image exists
        glance.images.list.return_value = []
        expected = {'imagesSet': [{'imageId': image_id,
                                   'description': 'fake desc',
                                   'imageOwnerId': fakes.ID_OS_PROJECT,
                                   'imageState': 'pending',
                                   'imageType': 'machine',
                                   'isPublic': False}]}

        # describe all images
        result = image_api.describe_images(context)
        self.assertEqual(expected, result)

        # describe the image
        result = image_api.describe_images(context, image_id=[image_id])
        self.assertEqual(expected, result)

        # describe with filter
        result = image_api.describe_images(
            context, filter=[{'name': 'name', 'value': 'noname'}])
        self.assertEqual({'imagesSet': []}, result)

        # describe failed image
        image['state'] = 'failed'
        expected['imagesSet'][0]['imageState'] = 'failed'
        result = image_api.describe_images(base.create_context())
        self.assertEqual(expected, result)

        # describe cases when glance image exists, db item is yet not updated
        del image['state']
        os_image_id = fakes.random_os_id()
        os_image = {'id': os_image_id,
                    'owner': fakes.ID_OS_PROJECT,
                    'status': 'active',
                    'visibility': 'private',
                    'ec2_id': image_id}
        glance.images.list.return_value = [fakes.OSImage(os_image)]
        expected['imagesSet'] = [{
            'architecture': None,
            'creationDate': None,
            'description': 'fake desc',
            'imageId': image_id,
            'imageLocation': 'None (None)',
            'imageOwnerId': fakes.ID_OS_PROJECT,
            'imageState': 'available',
            'imageType': 'machine',
            'isPublic': False,
            'name': None,
            'rootDeviceType': 'instance-store'}]

        # describe all images
        result = image_api.describe_images(context)
        self.assertEqual(expected, result)
        db_api.update_item.assert_called_once_with(
            context, tools.update_dict(image, {'os_id': os_image_id}))

        # describe the image
        db_api.reset_mock()
        result = image_api.describe_images(context, image_id=[image_id])
        self.assertEqual(expected, result)
        db_api.update_item.assert_called_once_with(
            context, tools.update_dict(image, {'os_id': os_image_id}))

class S3TestCase(base.BaseTestCase):

    def test_s3_parse_manifest(self):
        db_api = self.mock_db()
        glance = self.mock_glance()
        db_api.set_mock_items(fakes.DB_IMAGE_AKI_1, fakes.DB_IMAGE_ARI_1)
        glance.images.get.side_effect = (
            tools.get_by_1st_arg_getter({
                fakes.ID_OS_IMAGE_AKI_1: fakes.OSImage(fakes.OS_IMAGE_AKI_1),
                fakes.ID_OS_IMAGE_ARI_1: fakes.OSImage(fakes.OS_IMAGE_ARI_1)}))

        metadata, image_parts, key, iv = image_api._s3_parse_manifest(
            base.create_context(), AMI_MANIFEST_XML)

        expected_metadata = {
            'disk_format': 'ami',
            'container_format': 'ami',
            'architecture': 'x86_64',
            'kernel_id': fakes.ID_OS_IMAGE_AKI_1,
            'ramdisk_id': fakes.ID_OS_IMAGE_ARI_1,
            'mappings': [
                {"device": "sda1", "virtual": "ami"},
                {"device": "/dev/sda1", "virtual": "root"},
                {"device": "sda2", "virtual": "ephemeral0"},
                {"device": "sda3", "virtual": "swap"}]}
        self.assertThat(metadata,
                        matchers.DictMatches(expected_metadata,
                                             orderless_lists=True))
        self.assertThat(image_parts,
                        matchers.ListMatches(['foo']))
        self.assertEqual('foo', key)
        self.assertEqual('foo', iv)
        db_api.get_items_ids.assert_any_call(
            mock.ANY, 'aki', item_ids=(fakes.ID_EC2_IMAGE_AKI_1,),
            item_os_ids=None)
        db_api.get_items_ids.assert_any_call(
            mock.ANY, 'ari', item_ids=(fakes.ID_EC2_IMAGE_ARI_1,),
            item_os_ids=None)

    def test_s3_create_image_locations(self):
        self.configure(image_decryption_dir=None)
        glance = self.mock_glance()
        _handle, tempf = tempfile.mkstemp()
        fake_context = base.create_context()

        @mock.patch('ec2api.api.image._s3_untarzip_image')
        @mock.patch('ec2api.api.image._s3_decrypt_image')
        @mock.patch('ec2api.api.image._s3_download_file')
        @mock.patch('ec2api.api.image._s3_conn')
        def do_test(s3_conn, s3_download_file, s3_decrypt_image,
                    s3_untarzip_image):
            (s3_conn.return_value.
             get_object.return_value) = {'Body': FILE_MANIFEST_XML}
            s3_download_file.return_value = tempf
            s3_untarzip_image.return_value = tempf
            os_image_id = fakes.random_os_id()
            (glance.images.create.return_value) = (
                fakes.OSImage({'id': os_image_id,
                               'status': 'queued'}))

            data = [
                ({'image_location': 'testbucket_1/test.img.manifest.xml'},
                 'testbucket_1', 'test.img.manifest.xml'),
                ({'image_location': '/testbucket_2/test.img.manifest.xml'},
                 'testbucket_2', 'test.img.manifest.xml')]
            for mdata, bucket, manifest in data:
                image = image_api._s3_create(fake_context, mdata)
                eventlet.sleep()
                self.glance.images.update.assert_called_with(
                    os_image_id, image_state='available')
                self.glance.images.upload.assert_any_call(
                    os_image_id, mock.ANY)
                s3_conn.return_value.get_object.assert_called_with(
                    Bucket=bucket, Key=manifest)
                s3_download_file.assert_called_with(
                    mock.ANY, bucket, 'foo', mock.ANY)
                s3_decrypt_image.assert_called_with(
                    fake_context, mock.ANY, 'foo', 'foo', mock.ANY)
                s3_untarzip_image.assert_called_with(mock.ANY, mock.ANY)

            do_test()

    @mock.patch('ec2api.api.image.eventlet.spawn_n')
    def test_s3_create_bdm(self, spawn_n):
        glance = self.mock_glance()
        metadata = {'image_location': 'fake_bucket/fake_manifest',
                    'root_device_name': '/dev/sda1',
                    'block_device_mapping': [
                        {'device_name': '/dev/sda1',
                         'snapshot_id': fakes.ID_OS_SNAPSHOT_1,
                         'delete_on_termination': True},
                        {'device_name': '/dev/sda2',
                         'virtual_name': 'ephemeral0'},
                        {'device_name': '/dev/sdb0',
                         'no_device': True}]}
        fake_context = base.create_context()
        with mock.patch('ec2api.api.image._s3_conn') as s3_conn:

            (s3_conn.return_value.
             get_object.return_value) = {'Body': FILE_MANIFEST_XML}

            image_api._s3_create(fake_context, metadata)

            glance.images.create.assert_called_once_with(
                disk_format='ami', container_format='ami',
                visibility='private', architecture='x86_64',
                image_state='pending', root_device_name='/dev/sda1',
                block_device_mapping=[{'device_name': '/dev/sda1',
                                       'snapshot_id': fakes.ID_OS_SNAPSHOT_1,
                                       'delete_on_termination': True},
                                      {'device_name': '/dev/sda2',
                                       'virtual_name': 'ephemeral0'},
                                      {'device_name': '/dev/sdb0',
                                       'no_device': True}],
                image_location='fake_bucket/fake_manifest')

    def test_s3_malicious_tarballs(self):
        self.assertRaises(
            exception.EC2InvalidException,
            image_api._s3_test_for_malicious_tarball,
            "/unused", os.path.join(os.path.dirname(__file__), 'abs.tar.gz'))
        self.assertRaises(
            exception.EC2InvalidException,
            image_api._s3_test_for_malicious_tarball,
            "/unused", os.path.join(os.path.dirname(__file__), 'rel.tar.gz'))

    def test_decrypt_text(self):
        public_key = os.path.join(os.path.dirname(__file__), 'test_cert.pem')
        private_key = os.path.join(os.path.dirname(__file__),
                                   'test_private_key.pem')
        subject = "/C=RU/ST=Moscow/L=Moscow/O=Progmatic/CN=RootCA"
        certificate_file = processutils.execute('openssl',
                                                'req', '-x509', '-new',
                                                '-key', private_key,
                                                '-days', '365',
                                                '-out', public_key,
                                                '-subj', subject)
        text = "some @#!%^* test text"
        process_input = text.encode("ascii")
        enc, _err = processutils.execute('openssl',
                                         'rsautl',
                                         '-certin',
                                         '-encrypt',
                                         '-inkey', public_key,
                                         process_input=process_input,
                                         binary=True)
        self.assertRaises(exception.EC2Exception, image_api._decrypt_text, enc)
        self.configure(x509_root_private_key=private_key)
        dec = image_api._decrypt_text(enc)
        self.assertIsInstance(dec, bytes)
        dec = dec.decode('ascii')
        self.assertEqual(text, dec)

redpajama_set_name: RedPajamaGithub


Answers to Everyday Questions : whats the best way to try and give up smoking weed any help?
i smoked everyday for 2 years.
then i just decided to stop one day.
Checking yourself into rehab and getting professional help is a good first step but equally important is using as much of your own willpower as you can to come off it by keeping yourself too busy to light up.
get involved with something that will keep you too busy to do it.
Have a look at this site, you may find this method helpful.
dude its not physically addictive. just try stopping for a few days, and youll see that you dont feel any different. if your bored, go do something with yourself. weed is just gonna make you feel like crap anyways, trust me.
if you done believe me, just try not smoking for about five days. if you light up again after that, I guarantee you will feel like an idiot and ask yourself why you are getting stoned. try it.
anyways, its pricey as hell.


CHARLOTTE — The two-hour drive from Charlotte to Asheville, North Carolina, at this time of year is a symphony for the eyes, with the hickories blazing yellow, the dogwoods a deep red and the maples dressed in several shades of orange.
About halfway there, you start to get tantalizing glimpses of the Blue Ridge Mountains. Before you know it, you're deep in those old hills, crossing the French Broad River and rolling up a steep road to UNC Asheville, an immaculate little city on a hill.
They've built a new basketball arena for the Bulldogs by now, a shiny steel-and-glass structure, and the baseball field has nice painted blue-and-white dugouts and a permanent outfield fence.