text:
Justia Lawyer Directory Intellectual Property Oregon Walterville Attorneys
Walterville Intellectual Property Lawyers
Compare top rated Oregon attorneys serving Walterville.
Emily Sarah Hill
(541) 344-2174	4300 Goodpasture Loop
Eugene,	OR 97401
Free ConsultationOffers Video ConferencingVideo ConfEugene, OR Intellectual Property Attorney with 17 years of experience
IP, Business, Employment and Trademarks
University of California, Berkeley School of Law
I have practiced law in Eugene, Oregon since 2004. I practice Intellectual Property, Business Law, Civil Litigation, and Employment Law. I take pride in delivering exceptional client service. I work promptly and view my clients as partners in problem-solving. Clients describe me as highly responsive, clear, professional, and knowledgeable. Attorneys' integrity and ethics are critical to client service. I uphold the highest professional standards and am on the Oregon State Bar's Disciplinary Board. I earned a B.A. from the University of California, Berkeley in 2001. I graduated from Berkeley Law in 2004, earning my J.D. with a certificate in Berkeley...
Meng Ouyang
Eugene, OR Intellectual Property Lawyer with 11 years of experience
IP, Business, Patents and Trademarks
A chemistry and computer science major, once an international student then an immigrant, worked in a variety of fields, speak English and Mandarin fluently, and I care and have compassion for other people. I have a high standard for myself and will work for you with the same standard.
Nicholas R. Balthrop
Eugene, OR Intellectual Property Attorney with 6 years of experience
(541) 343-8060	440 East Broadway
IP, Business, Construction and Real Estate
John M Eustermann
Corvallis, OR Intellectual Property Lawyer
(781) 902-8615	1100 NE Circle Blvd Ste 200
Corvallis,	OR 97330
IP, Antitrust, Business and Patents
Frederick A Batson
(541) 686-8833	975 Oak St Ste 800
IP, Business and Real Estate
Laura T Z Montgomery
Eugene, OR Intellectual Property Attorney with 18 years of experience
(541) 686-8833	975 Oak St
IP and Employment
Christopher John Buntel
(541) 335-0040	29851 Willow Creek Rd
George A Burgott
(541) 484-9292	777 High St Ste 300
IP, Insurance Defense, Personal Injury and Products Liability
Mary K. Hehman
(541) 636-8609	3272 Stoney Ridge Rd
Charles R Williams
IP, Employment and Entertainment & Sports
Nicole Schaefer
Beaverton, OR Intellectual Property Attorney with 6 years of experience
(971) 350-8516	1500 NW Bethany Blvd, Suite 200
Beaverton,	OR 97006
Offers Video ConferencingVideo ConfIP, Business, Divorce and Trademarks
Lewis & Clark Law School
Hi! I'm Nicole. I'm the lead attorney at Yellow Dog Legal, a virtual firm offering boutique trademark services without the boutique prices. I am the go-to expert for local entrepreneurs seeking information and help with all of their trademark needs. I love doing trademarks and helping my clients protect their businesses and brands.
I graduated from Lewis and Clark Law School with Certificates in Animal Law and Criminal Law and Procedure. I still practice Animal Law, as I am deeply passionate about animals, but I also love trademarks and everything having to do with them!
In my spare time, I enjoy watercolor...
Mr. Michael O. Stevens
Hillsboro, OR Intellectual Property Attorney with 12 years of experience
(971) 533-6178	1915 NE Stucki Avenue
Hillsboro,	OR 97006
Free ConsultationIP, Business, Construction and Employment
Willamette University College of Law
Michael Stevens has a background in insurance defense representing individuals to large corporations in a wide variety of cases from personal injury to wrongful death and construction defects. He handled cases with values of as much as $4 million, and drafted many successful motions for summary judgment. An Oregon native, he graduated from Oregon State University with his bachelor's degree and earned his juris doctorate at Willamette University College of Law in Salem in 2009. At Willamette he was an editor and writer for Willamette Law Online and the Web & Publication Editor for the Willamette Sports Law Journal. He...
Aaron S. Ferreira
Portland, OR Intellectual Property Lawyer with 21 years of experience
(503) 228-2495	525 SW Jackson Street
Portland,	OR 97201
IP, Business, Employment and Real Estate
Aaron Ferreira grew up in Livermore, California. As an undergrad, he attended the California Polytechnic State University at San Luis Obispo (Cal Poly), first studying Computer Science and then graduating in 1994 with a Bachelor of Arts degree in Philosophy. After graduation, he got his feet wet in the legal profession by working for three years as a legal assistant in Shell Beach, California.
In 1997, Aaron entered the Northwestern School of Law of Lewis & Clark College, in Portland, Oregon. While attending law school, he participated in law review as a Research Editor and then Articles Editor for the...
Mark C. Cogan
(503) 563-7382	1500 SW 1st Ave
IP, Criminal, DUI and Environmental
New York University School of Law
Aggressive Representation Against a Range of Criminal Charges Criminal charges are serious matters. Accusations that qualify as Ballot Measure 11 charges are not only serious, they carry mandatory prison sentences. Our law firm, located in Portland, Oregon, represents clients with a variety of criminal defense needs, including clearing a criminal record through expungement, representation in grand jury investigations and criminal defense in state and federal courts. Our criminal defense lawyer, Mark Cogan, received an AV - Preeminent 5.0 out of 5.0 Rating* through Martindale-Hubbell, the highest ranking available to attorneys. He is an Oregon SuperLawyer® (only 5% of...
Ryan Douglas Smith
(800) 880-5122	1050 SW 6th Ave.
Free ConsultationIP and Business
University of Oregon School of Law
Peak Franchise Law focuses on franchise law and areas of law that complement the franchise legal practice, including business entity formations; trademark law; business sales and acquisitions; intellectual property rights; and a variety of commercial contracts.
With respect to franchise law, the firm creates and reviews Franchise Disclosure Documents (FDDs), prepares and files state franchise registrations, advises on franchise relationship matters, negotiates franchise-related contracts, helps U.S. companies expand internationally through franchising and licensing, helps international companies franchise in the United States, and provides other franchise legal services.
With respect to business sales and acquisitions, the firm represents buyers and sellers...
Andrew Harris
Portland, OR Intellectual Property Attorney with 16 years of experience
(503) 405-4939	4605 NE Fremont St Ste 204B
Offers Video ConferencingVideo ConfIP, Business, International and Trademarks
I offer entrepreneurs, small businesses, and the owners of those businesses, access to straightforward, cost-effective, and responsive legal services for the three major stages of a business's lifecycle: the startup, the operation, and the transition (such as a sale, transfer or closing down) of the business. For clients, this means access to a top notch, experienced attorney focused exclusively on the types of transactional issues that directly affect your business.
Karen Dana Oster
Lake Oswego, OR Intellectual Property Attorney with 31 years of experience
(503) 810-2560	16869 SW 65th Avenue
PMB 506
Lake Oswego,	OR 97035
Loyola Law School, Los Angeles
For over twenty-five years Karen has been assisting businesses and individuals turn ideas into patents. Her practice focuses on patent prosecution (the process of obtaining a patent). Karen has written and/or prosecuted patents in technological categories such as machines and tools, medical and dental devices and processes, construction, consumer products, sporting equipment, toys and games, and computer-related inventions. She also has extensive experience with design patents. Karen's practice includes opinion work (e.g. patentability, noninfringement, and infringement).
Karen realizes that each client has unique intellectual property needs and uses creative solutions to help her clients achieve their goals. Karen takes the time...
Lauren Nowierski-Stadnick
Bend, OR Intellectual Property Lawyer with 12 years of experience
(541) 323-2301	920 Northwest Bond Street
Bend,	OR 97703
Free ConsultationOffers Video ConferencingVideo ConfIP, Consumer, Family and Patents
For over a decade, Lauren Nowierski-Stadnick has been litigating complex civil disputes in federal and state courts throughout the United States. Lauren's practice includes a wealth of experience in all aspects of civil litigation: from pre-suit investigations through trial. Her investigative and advocacy skills have contributed to over $100M in pretrial settlements in numerous matters. Throughout her legal career, Lauren has also been heavily involved in pro bono matters, including asylum, litigated divorce, and unemployment-related issues. Her current practice is dedicated to counseling individuals and businesses, helping them understand and protect their rights and navigating any...
Howard Alan Newman MBA
(503) 535-8040	1001 SW 5th Avenue
Free ConsultationIP, Arbitration & Mediation, Business and Patents
Mr. Newman's clientele have included law firms, individuals, and small and medium sized entities in various locations in the United States and around the world, including a niche Brasilian practice. In addition to Mr. Newman's legal experience as a registered patent attorney and working as a litigation and a transactional attorney, he has worked as a CEO of a start-up company, as an associate in an incubator, and he has performed financial valuations of intellectual property both as a function of litigation and arms-length transactions.
Ashley Demland
Tigard, OR Intellectual Property Lawyer with 6 years of experience
(503) 420-5708	7455 SW Bridgeport Road, Suite 205
Tigard,	OR 97224
IP, Business, Health Care and Trademarks
Lewis & Clark College
General Business & Intellectual Property Law
Women-Owned & Family Businesses
Fundraising and Securities
Biotechnology & Health Care
Ashley focuses exclusively on advising corporate clients. From formation to exit, fundraising to litigation, Ashley is an experienced advocate who keeps her eye on the bottom line.
Like many of her clients, Ashley is an entrepreneur. After being battle-tested at a mid-sized business law firm in Portland, she and her husband Jeff and law school classmate Kristie realized their long-standing dream of owning their own firm. They're now living out the advice they give their clients.
Ashley focuses on providing savvy, practical...
Dane E. Johnson
(503) 975-8298	Portland,	OR 97239
Free ConsultationIP, Entertainment & Sports and Trademarks
Dane Johnson's practice concentrates on independent filmmakers who want to develop, finance, produce, and distribute professional film and scripted television projects. He concentrates on helping clients accomplish their cinematic visions, protect their legal interests, and monetize their creative assets. Along with handling entertainment transactions from development through delivery of the final project, structuring new business entities, and advising on literary property acquisitions and other copyright matters, film finance, and the legal aspects of film production, Dane assists film and television production companies in navigating the effects of COVID-19 on the film and television industry. He also counsels clients on choosing,...
Peter Vaughan Shaver
(503) 473-8252	3939 NE Hancock Street
IP, Business, Communications and Trademarks
J. D., University of Oregon School of Law, certificate in Intellectual Property. B. A., University of Michigan - Ann Arbor.
Darren Philip Cross
(503) 303-8472	1347 SE Tacoma Street
IP, Bankruptcy, Immigration and Trademarks
Darren P. Cross is a founder and principal of Cross Nadel LLC. He is highly experienced and knowledgeable in the areas of bankruptcy, immigration and trademark and copyright law. After operating his own law firm in Boston for nearly fifteen years, Darren co-founded Cross Nadel LLC to provide individual and business clients with the same excellent service for which he is known in a more accessible and flexible setting. Darren has spent his career working compassionately and directly with clients to guide them through some of their most difficult and important financial, citizenship and business decisions. He...
Spencer K Hunter
(971) 230-1067	707 SW Washington St.
Free ConsultationIP and Patents
Spencer practices with the law firm of Elliott, Ostrander & Preston, P.C. which has been in practice for more than 20 years, providing legal representation to, and primarily focused on, business and corporate guidance. At Elliott, Ostrander & Preston, Spencer focuses specifically on the preparation and prosecution of complex software and communications related patent applications.
As a former software engineer for Silicon Valley companies, Spencer understands the language and needs of your developers. Whether discussing cloud computing, data communications, databases, or data processing, Spencer can quickly engage with your technical experts and tackle the difficult challenge of presenting software based technologies...
Rick Klingbeil
(503) 490-6763	2300 SW First Avenue
IP and Products Liability
William Wardlow
Bend, OR Intellectual Property Attorney with 22 years of experience
(541) 903-2311	111 NW Hawtorne Avenue
Free ConsultationIP, Arbitration & Mediation, Business and Trademarks
Wardlow Law represents individuals and businesses with intellectual property and business needs, as well as entertainment law, publishing, royalties, and litigation.
Over the last 21 years, Wardlow Law has helped countless businesses and individuals protect their valuable creative assets, negotiate agreements, stop infringement, recover money for damages, obtain injunctive relief to prevent future injury, and oppose questionable lawsuits.
Mr. Wardlow first worked at top Hollywood law firm, Codikow, Carroll, Guido & Groffman, for clients including records labels, publishing companies, and artists such as Jay-Z, Dave Matthews Band, William S. Burroughs, Natalie Merchant, Blondie, and countless others.
Wardlow then opened a private practice in...
Lawrence Mitchell Vergun
Hillsboro, OR Intellectual Property Lawyer with 34 years of experience
(503) 648-4777	165 SE 26th Avenue
IP, Business, Estate Planning and Landlord Tenant
UCLA School of Law
Dennis Steinman
(503) 222-3531	520 SW Yamhill St
IP, Business, Civil Rights and Trademarks
Paul T Loney
(503) 234-2694	12031 NE Maerx St
Free ConsultationOffers Video ConferencingVideo ConfIP, Business, Cannabis Law and Criminal
Paul Loney has practiced law for over 27 years. In 2009, Mr. Loney developed the legal blueprint for Oregon's first private cannabis club, "Highway 420," and the first National high-profile cannabis café, "Oregon NORML's Cannabis Café." Mr. Loney's practice focuses on a variety of legal issues associated with cannabis and hemp, specifically in the areas of business law and regulatory compliance.
Paul Loney has served as Oregon NORML's legal counsel for over 13 years and has helped draft numerous cannabis-related legislative initiatives involving Oregon's medical marijuana and recreational marijuana issues. He has assisted clients in drafting language for proposed additions...
Jason R Polen
PORTLAND, OR Intellectual Property Lawyer with 5 years of experience
(503) 564-8434	401 NE 19TH AVE
Free ConsultationIP, Business, Communications and Trademarks
Jason is a self-starting, go-getting lawyer who takes a pragmatic approach to helping his clients. He co-founded Fortify Law because he was not satisfied with the traditional approach to providing legal services. He firmly believes that legal costs should be predictable, transparent and value-driven. Jason's entrepreneurial mindset enables him to better understand his clients' needs. His first taste of entrepreneurship came from an early age when he helped manage his family's small free-range cattle farm. Every morning, before school, he would deliver hay to a herd of 50 hungry cows. In addition, he was responsible for sweeping "the shop" at...
Lawrence M Vergun
Tigard, OR Intellectual Property Attorney with 33 years of experience
(503) 499-1225	10260 SW Greenburg Road
Offers Video ConferencingVideo ConfIP, Business, Estate Planning and Probate
I've been practicing law for over thirty years, and I am proud to have assisted dozens of businesses, entrepreneurs, professionals, and all other good folks working hard to make a living. I truly respect their commitment to their work and to their families. And I am pleased to be part of their business and personal success.
Donn Kevin Harms
(541) 678-5209	20475 Outback
Thomas Jefferson School of Law
Donn K. Harms is a Registered Patent Attorney also handling business and corporate law matters since 1988, with heavy emphasis on trademarks, copyrights, patents, and licensing matters.
Mr. Harms has served as a Professor of Patent Law and Trademark Law at the University of California at San Diego, and has offices in Bend, Oregon, and in Del Mar, California.
Prior to practicing law, Mr. Harms owned and operated a small business with 50 employees for over 15 years. From actually starting and running a small business, he has a vast amount of practical experience in small business operation.
Mr. Harms...
Bart Day
(503) 224-4900	1435 NW 19th Avenue
IP, Entertainment & Sports and Trademarks
Bradley Schrock
Beaverton, OR Intellectual Property Attorney with 34 years of experience
(877) 676-3841	4800 SW Griffith Dr.
IP, Business, Estate Planning and Probate
Business emphasis general practice serving businesses, business owners and individuals.Business law, divorce and family law, wills, trusts and estates, and several areas of employment law.
Key types of matters handled:
1. Divorce;
2. Non-competition agreements and issues;
3. trust administration disputes;
4. Probates, and probate/will disputes;
5. Business formation and business contracts;
6. Sales of business;
7. Advising employers on employment issues;
8. Wage claims; and
9. Business litigation.
Martin Medeiros
(503) 226-8122	1420 American Bank Building
621 SW Morriston Street
IP and Business
Jonathan Parker Edwards
Portland, OR Intellectual Property Attorney
1177 SW Market Street
IP, Business, Education and Employment
Jonathan Edwards has spent the majority of his legal career working in higher education, as general counsel for a public university, and as an instructor in business law.
Jeffrey Armistead
Melissa Blythe Jaffe
(503) 780-6565	5711 N.Omaha Ave
Offers Video ConferencingVideo ConfIP, Business, Communications and Entertainment & Sports
Golden Gate Univ School of Law and Golden Gate University School of Law
Tony Kullen
(503) 941-0269	401 NW 13th Ave
IP, Business and Securities
St. John's University School of Law
(503) 459-4141	806 SW Broadway
Intellectual Property Lawyers in Nearby Cities
Intellectual Property Lawyers in Nearby Counties
Lane County
Linn County


Death looms largely over The Sisters Brothers, a grim revisionist Western peppered generously with sprinklings of humanity. Rather than subscribing to standard genre constructions, the film opts for a decisively picaresque approach as brothers Eli (John C. Reilly) and Charlie Sisters (Joaquin Phoenix) traverse the beautiful, unsettled expanses of the Pacific Northwest in the 1850s. The American Frontier is blossoming with the gold rush in full swing, luring in settlers to boomtowns like San Francisco with the promise of unimaginable wealth and glory. Our two bickering protagonists stand at the periphery of all this, searching for a man named Hermann Kermit Warm (Riz Ahmed), a chemist who's come up with a lucrative formula for discerning gold in a river bed. He's traveling with John Morris (Jake Gyllenhaal), an aimless journeyman of sorts, and together they're pursuing the American dream while attempting to dodge the pursuit of money-grubbing capitalists, our eponymous heroes on horseback.
There's a perversity to the framework here, as we're saddled with following these brutal brothers attempting to steal Warm's groundbreaking formula. Being a western after all, this structure doesn't eschew complexity, especially when it comes to characterization. Often sloppy and belligerently drunk, Charlie is the more brutal of the pair, picking more fights than he can handle and shooting more men than he can count. If some Westerns tend to glamorize boozing stoics, then this film seeks to rectify that archetype with Charlie ingloriously falling off his horse and vomiting in every other scene. Eli, conversely, stays away from the liquor and thinks a bit more rationally as he considers retiring from being a hitman. This may very well be worn territory for veterans Phoenix and Reilly, who seem to play variations of these types of characters often, but that isn't to say that they don't do a good job. As the two brothers duke it out over ideological differences, their argumentative banter proves entertaining while revealing their respective shortcomings.
Punctuated by this pursuit is the quickly fading frontier of the American West, which is being built-up with storefronts, hotels, and other marks of civilization. The brothers pick up on this change along their journey, stopping in newly founded towns and cities that they seem ill-suited for. In a comical, but potent scene, Eli is introduced to the concept of brushing his teeth—he then buys a toothbrush and spends the rest of the film teaching himself how to use it. With this change comes a set of new challenges, as seemingly every character begins to consider how they want to future of their country to take shape. Warm, with his success as a chemist, stands apart from everyone else, resolutely idealistic with the hope that the country will learn how to remedy the corrosiveness of its capitalism. The film's conclusion is not nearly as optimistic.
With The Sisters Brothers, French director Jacques Audiard (A Prophet, Dheepan) joins the ranks of foreign filmmakers who have come to America to make a film about America. And as critical and cynical as the film may be, there's an evident love of the genre that can be felt in Audiard's directorial choices—he indulges in gorgeous landscape photography, relishes in the banter of his cowboy leads, and includes a fair share of violent bloodshed. There's often an ingenuity and knowing self-awareness at play in revisionists outlooks of this kind, but the film often feels too schematic for its own good—in some ways, its an easier film to write about than it is to love. Intentional or not, its subversions and critiques of the genre, while smart, frequently undermine the propulsion of the narrative—the film's anti-climax may very well be the prime example of this inclination.
The film's greatest achievement may be its mood, as Audiard maintains a sense of dread that persists even as the plot delves into comical diversions and philosophical inquiries. The Sisters Brothers is dark, without being unbearably heavy, and it's a journey worth taking. As inelegant as some of the storytelling may be, the story itself remains intriguing enough in its own right, subsisting as a grim parable about civilization and its discontents.


Thousands of USDA Rural Development (RD) Section 515 rental housing units are being prepaid annually, many illegally. Thousands more have loans that will mature over the next ten years. RD Section 521 Rental Assistance (RA) payments end when a loan matures or is prepaid, leaving residents vulnerable to severe rent increases and displacement. The National Housing Law Project (NHLP) will conduct a webinar on this prepayment and maturing mortgage problem, describing how to protect residents against displacement and offering ways to preserve the properties for current and future low income residents.
The webinar will help advocates find out whether a development in their area is maturing or is being prepaid. The session will review RD regulations, Administrative Notices, and other policies intended to preserve RD developments and protect residents against displacement and will discuss what nonprofit and public entities can do to preserve the housing. The webinar will review ways in which RD prepayment and Housing Choice Voucher regulations do not conform to their authorizing statutes and therefore fail to preserve developments or prevent resident displacement.
NHLP staff attorneys Gideon Anders and Jessica Cassella will be the presenters.


text:
/**
 * ES7-like async via a wrapped generator function.
 * Inside the function you can yield Promises.
 */
function spawn (genF) {
  return new Promise((resolve, reject) => {
    let gen = genF()
    let step = (nextF) => {
      let next
      try {
        next = nextF()
      } catch(e) {
        // Finished with failure, reject the promise.
        reject(e)
        return
      }
      if (next.done) {
        // Finished with success, resolve the promise.
        resolve(next.value)
        return
      }
      // Not finished, chain off the yielded promise and `step` again.
      Promise
        .cast(next.value)
        .then((v) => {
          step(() => gen.next(v))
        }, (e) => {
          step(() => gen.throw(e))
        })
    }
    step(() => gen.next(undefined))
  })
}

export default spawn

redpajama_set_name: RedPajamaGithub


I've a Moto-G XT1033. When I connect the phone to WiFi, it connects fine, shows the WiFi icon but uses 3G for internet. H+ or E is shown over mobile signal icon and an exclamation mark on WiFi.
I've to manually disable mobile data to force the phone to use WiFi. Then it works just fine.
Also, this problem appeared only after I upgraded from kitkat to lollipop official ROM. Now I've switched to CM12 but the problem persists.
My WiFi uses proxy to connect to the internet and this problem is only on WiFi networks that use proxy.
Any idea what causes this or how to fix it.
Not the answer you're looking for? Browse other questions tagged cyanogenmod wi-fi motorola-moto-g 3g proxy or ask your own question.


pedestal jewelry holder tall dish uncommon goods.
pedestal jewelry holder metal earrings organizer rotating earring display necklace rack storage tree ceramic.
pedestal jewelry holder earring organizer lace pottery by tracy shea.
pedestal jewelry holder image 0 by tracy shea.
pedestal jewelry holder wish necklace display chain bust pendant neck stand showcase uncommon goods.
pedestal jewelry holder desktop necklace acrylic block ceramic.
pedestal jewelry holder plate earring organizer by tracy shea.
pedestal jewelry holder women lady girl black velvet pendant necklace display chain uncommon goods.
pedestal jewelry holder acrylic organizer beautiful photos plastic necklace earring display of uncommon goods.
pedestal jewelry holder uncommon goods by.
pedestal jewelry holder linen columns necklace finger ring bracelet pendant stand display ceramic.
pedestal jewelry holder earring ice and sky by box uncommon goods.
pedestal jewelry holder metal earrings organizer rotating display necklace rack earring storage tree by tracy shea.
pedestal jewelry holder get quotations a new hot women lady girl portrait resin rack necklace display chain by tracy shea.
pedestal jewelry holder earring organizer ceramic by tracy shea.
pedestal jewelry holder women lady girl black velvet body necklace packing display uncommon goods.
pedestal jewelry holder picture 1 of ceramic.
pedestal jewelry holder create unique bowls with a few easy steps and multi surface acrylic earring bowl uncommon goods.
pedestal jewelry holder earring tower figurine catch all french boudoir by tracy s.
pedestal jewelry holder by tracy shea.
pedestal jewelry holder uncommon goods.
pedestal jewelry holder cake cupcake plate candle blue stand ceramic.
pedestal jewelry holder free shipping latest version acrylic 3 set necklace pendents stand ceramic.
pedestal jewelry holder metal earrings organizer rotating display necklace rack earring storage tree uncommon goods.
pedestal jewelry holder sphere stone charging morocco ceramic.
pedestal jewelry holder with optional pamphlet ceramic.
pedestal jewelry holder image 0 ceramic.
pedestal jewelry holder hey i found this really awesome listing at earring by tracy shea.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter.DataStructs;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Interop;

namespace MoonSharp.Interpreter.Execution.VM
{
    sealed partial class Processor
    {
        private const int YIELD_SPECIAL_TRAP = -99;

        private DynValue Processing_Loop(int instructionPtr)
        {
            // This is the main loop of the processor, has a weird control flow and needs to be as fast as possible.
            // This sentence is just a convoluted way to say "don't complain about gotos".

            repeat_execution:

            try
            {
                while (true)
                {
                    var i = m_RootChunk.Code[instructionPtr];

                    if (m_Debug.DebuggerAttached != null)
                    {
                        ListenDebugger(i, instructionPtr);
                    }

                    ++instructionPtr;

                    switch (i.OpCode)
                    {
                        case OpCode.Nop:
                        case OpCode.Debug:
                        case OpCode.FuncMeta:
                            break;
                        case OpCode.Pop:
                            m_ValueStack.RemoveLast(i.NumVal);
                            break;
                        case OpCode.Copy:
                            m_ValueStack.Push(m_ValueStack.Peek(i.NumVal));
                            break;
                        case OpCode.Swap:
                            ExecSwap(i);
                            break;
                        case OpCode.Literal:
                            m_ValueStack.Push(i.Value);
                            break;
                        case OpCode.Add:
                            instructionPtr = ExecAdd(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Concat:
                            instructionPtr = ExecConcat(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Neg:
                            instructionPtr = ExecNeg(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Sub:
                            instructionPtr = ExecSub(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Mul:
                            instructionPtr = ExecMul(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Div:
                            instructionPtr = ExecDiv(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Mod:
                            instructionPtr = ExecMod(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Power:
                            instructionPtr = ExecPower(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Eq:
                            instructionPtr = ExecEq(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.LessEq:
                            instructionPtr = ExecLessEq(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Less:
                            instructionPtr = ExecLess(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Len:
                            instructionPtr = ExecLen(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Call:
                        case OpCode.ThisCall:
                            instructionPtr = Internal_ExecCall(i.NumVal, instructionPtr, null, null,
                                i.OpCode == OpCode.ThisCall, i.Name);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Scalar:
                            m_ValueStack.Push(m_ValueStack.Pop().ToScalar());
                            break;
                        case OpCode.Not:
                            ExecNot(i);
                            break;
                        case OpCode.CNot:
                            ExecCNot(i);
                            break;
                        case OpCode.JfOrPop:
                        case OpCode.JtOrPop:
                            instructionPtr = ExecShortCircuitingOperator(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.JNil:
                        {
                            var v = m_ValueStack.Pop().ToScalar();

                            if (v.Type == DataType.Nil || v.Type == DataType.Void)
                                instructionPtr = i.NumVal;
                        }
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Jf:
                            instructionPtr = JumpBool(i, false, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Jump:
                            instructionPtr = i.NumVal;
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.MkTuple:
                            ExecMkTuple(i);
                            break;
                        case OpCode.Clean:
                            ClearBlockData(i);
                            break;
                        case OpCode.Closure:
                            ExecClosure(i);
                            break;
                        case OpCode.BeginFn:
                            ExecBeginFn(i);
                            break;
                        case OpCode.ToBool:
                            m_ValueStack.Push(DynValue.NewBoolean(m_ValueStack.Pop().ToScalar().CastToBool()));
                            break;
                        case OpCode.Args:
                            ExecArgs(i);
                            break;
                        case OpCode.Ret:
                            instructionPtr = ExecRet(i);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            if (instructionPtr < 0)
                                goto return_to_native_code;
                            break;
                        case OpCode.Incr:
                            ExecIncr(i);
                            break;
                        case OpCode.ToNum:
                            ExecToNum(i);
                            break;
                        case OpCode.JFor:
                            instructionPtr = ExecJFor(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.NewTable:
                            m_ValueStack.Push(DynValue.NewTable(m_Script));
                            break;
                        case OpCode.IterPrep:
                            ExecIterPrep(i);
                            break;
                        case OpCode.IterUpd:
                            ExecIterUpd(i);
                            break;
                        case OpCode.ExpTuple:
                            ExecExpTuple(i);
                            break;
                        case OpCode.Local:
                            var scope = m_ExecutionStack.Peek().LocalScope;
                            var index = i.Symbol.i_Index;
                            m_ValueStack.Push(scope[index].AsReadOnly());
                            break;
                        case OpCode.Upvalue:
                            m_ValueStack.Push(m_ExecutionStack.Peek().ClosureScope[i.Symbol.i_Index].AsReadOnly());
                            break;
                        case OpCode.StoreUpv:
                            ExecStoreUpv(i);
                            break;
                        case OpCode.StoreLcl:
                            ExecStoreLcl(i);
                            break;
                        case OpCode.TblInitN:
                            ExecTblInitN(i);
                            break;
                        case OpCode.TblInitI:
                            ExecTblInitI(i);
                            break;
                        case OpCode.Index:
                        case OpCode.IndexN:
                        case OpCode.IndexL:
                            instructionPtr = ExecIndex(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.IndexSet:
                        case OpCode.IndexSetN:
                        case OpCode.IndexSetL:
                            instructionPtr = ExecIndexSet(i, instructionPtr);
                            if (instructionPtr == YIELD_SPECIAL_TRAP) goto yield_to_calling_coroutine;
                            break;
                        case OpCode.Invalid:
                            throw new NotImplementedException(string.Format("Invalid opcode : {0}", i.Name));
                        default:
                            throw new NotImplementedException(string.Format("Execution for {0} not implented yet!",
                                i.OpCode));
                    }
                }

                yield_to_calling_coroutine:

                var yieldRequest = m_ValueStack.Pop().ToScalar();

                if (m_CanYield)
                    return yieldRequest;
                if (State == CoroutineState.Main)
                    throw ScriptRuntimeException.CannotYieldMain();
                throw ScriptRuntimeException.CannotYield();
            }
            catch (InterpreterException ex)
            {
                FillDebugData(ex, instructionPtr);

                if (!(ex is ScriptRuntimeException)) throw;

                if (m_Debug.DebuggerAttached != null)
                {
                    if (m_Debug.DebuggerAttached.SignalRuntimeException((ScriptRuntimeException) ex))
                    {
                        if (instructionPtr >= 0 && instructionPtr < m_RootChunk.Code.Count)
                        {
                            ListenDebugger(m_RootChunk.Code[instructionPtr], instructionPtr);
                        }
                    }
                }

                for (var i = 0; i < m_ExecutionStack.Count; i++)
                {
                    var c = m_ExecutionStack.Peek(i);

                    if (c.ErrorHandlerBeforeUnwind != null)
                        ex.DecoratedMessage = PerformMessageDecorationBeforeUnwind(c.ErrorHandlerBeforeUnwind,
                            ex.DecoratedMessage, GetCurrentSourceRef(instructionPtr));
                }

                while (m_ExecutionStack.Count > 0)
                {
                    var csi = PopToBasePointer();

                    if (csi.ErrorHandler != null)
                    {
                        instructionPtr = csi.ReturnAddress;

                        if (csi.ClrFunction == null)
                        {
                            var argscnt = (int) (m_ValueStack.Pop().Number);
                            m_ValueStack.RemoveLast(argscnt + 1);
                        }

                        var cbargs = new[] {DynValue.NewString(ex.DecoratedMessage)};

                        var handled =
                            csi.ErrorHandler.Invoke(
                                new ScriptExecutionContext(this, csi.ErrorHandler, GetCurrentSourceRef(instructionPtr)),
                                cbargs);

                        m_ValueStack.Push(handled);

                        goto repeat_execution;
                    }
                    if ((csi.Flags & CallStackItemFlags.EntryPoint) != 0)
                    {
                        throw;
                    }
                }

                throw;
            }

            return_to_native_code:
            return m_ValueStack.Pop();
        }

        internal string PerformMessageDecorationBeforeUnwind(DynValue messageHandler, string decoratedMessage,
            SourceRef sourceRef)
        {
            try
            {
                DynValue[] args = {DynValue.NewString(decoratedMessage)};
                var ret = DynValue.Nil;

                if (messageHandler.Type == DataType.Function)
                {
                    ret = Call(messageHandler, args);
                }
                else if (messageHandler.Type == DataType.ClrFunction)
                {
                    var ctx = new ScriptExecutionContext(this, messageHandler.Callback, sourceRef);
                    ret = messageHandler.Callback.Invoke(ctx, args);
                }
                else
                {
                    throw new ScriptRuntimeException("error handler not set to a function");
                }

                var newmsg = ret.ToPrintString();
                if (newmsg != null)
                    return newmsg;
            }
            catch (ScriptRuntimeException innerEx)
            {
                return innerEx.Message + "\n" + decoratedMessage;
            }

            return decoratedMessage;
        }

        private void AssignLocal(SymbolRef symref, DynValue value)
        {
            var stackframe = m_ExecutionStack.Peek();

            var v = stackframe.LocalScope[symref.i_Index];
            if (v == null)
                stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();

            v.Assign(value);
        }

        private void ExecStoreLcl(Instruction i)
        {
            var value = GetStoreValue(i);
            var symref = i.Symbol;

            AssignLocal(symref, value);
        }

        private void ExecStoreUpv(Instruction i)
        {
            var value = GetStoreValue(i);
            var symref = i.Symbol;

            var stackframe = m_ExecutionStack.Peek();

            var v = stackframe.ClosureScope[symref.i_Index];
            if (v == null)
                stackframe.ClosureScope[symref.i_Index] = v = DynValue.NewNil();

            v.Assign(value);
        }

        private void ExecSwap(Instruction i)
        {
            var v1 = m_ValueStack.Peek(i.NumVal);
            var v2 = m_ValueStack.Peek(i.NumVal2);

            m_ValueStack.Set(i.NumVal, v2);
            m_ValueStack.Set(i.NumVal2, v1);
        }

        private DynValue GetStoreValue(Instruction i)
        {
            var stackofs = i.NumVal;
            var tupleidx = i.NumVal2;

            var v = m_ValueStack.Peek(stackofs);

            if (v.Type == DataType.Tuple)
            {
                return (tupleidx < v.Tuple.Length) ? v.Tuple[tupleidx] : DynValue.NewNil();
            }
            return (tupleidx == 0) ? v : DynValue.NewNil();
        }

        private void ExecClosure(Instruction i)
        {
            var c = new Closure(m_Script, i.NumVal, i.SymbolList,
                i.SymbolList.Select(s => GetUpvalueSymbol(s)).ToList());

            m_ValueStack.Push(DynValue.NewClosure(c));
        }

        private DynValue GetUpvalueSymbol(SymbolRef s)
        {
            if (s.Type == SymbolRefType.Local)
                return m_ExecutionStack.Peek().LocalScope[s.i_Index];
            if (s.Type == SymbolRefType.Upvalue)
                return m_ExecutionStack.Peek().ClosureScope[s.i_Index];
            throw new Exception("unsupported symbol type");
        }

        private void ExecMkTuple(Instruction i)
        {
            var slice = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - i.NumVal, i.NumVal, false);

            var v = Internal_AdjustTuple(slice);

            m_ValueStack.RemoveLast(i.NumVal);

            m_ValueStack.Push(DynValue.NewTuple(v));
        }

        private void ExecToNum(Instruction i)
        {
            var v = m_ValueStack.Pop().ToScalar().CastToNumber();
            if (v.HasValue)
                m_ValueStack.Push(DynValue.NewNumber(v.Value));
            else
                throw ScriptRuntimeException.ConvertToNumberFailed(i.NumVal);
        }

        private void ExecIterUpd(Instruction i)
        {
            var v = m_ValueStack.Peek(0);
            var t = m_ValueStack.Peek(1);
            t.Tuple[2] = v;
        }

        private void ExecExpTuple(Instruction i)
        {
            var t = m_ValueStack.Peek(i.NumVal);

            if (t.Type == DataType.Tuple)
            {
                for (var idx = 0; idx < t.Tuple.Length; idx++)
                    m_ValueStack.Push(t.Tuple[idx]);
            }
            else
            {
                m_ValueStack.Push(t);
            }
        }

        private void ExecIterPrep(Instruction i)
        {
            var v = m_ValueStack.Pop();

            if (v.Type != DataType.Tuple)
            {
                v = DynValue.NewTuple(v, DynValue.Nil, DynValue.Nil);
            }

            var f = v.Tuple.Length >= 1 ? v.Tuple[0] : DynValue.Nil;
            var s = v.Tuple.Length >= 2 ? v.Tuple[1] : DynValue.Nil;
            var var = v.Tuple.Length >= 3 ? v.Tuple[2] : DynValue.Nil;

            // MoonSharp additions - given f, s, var
            // 1) if f is not a function and has a __iterator metamethod, call __iterator to get the triplet
            // 2) if f is a table with no __call metamethod, use a default table iterator

            if (f.Type != DataType.Function && f.Type != DataType.ClrFunction)
            {
                var meta = GetMetamethod(f, "__iterator");

                if (meta != null && !meta.IsNil())
                {
                    if (meta.Type != DataType.Tuple)
                        v = GetScript().Call(meta, f, s, var);
                    else
                        v = meta;

                    f = v.Tuple.Length >= 1 ? v.Tuple[0] : DynValue.Nil;
                    s = v.Tuple.Length >= 2 ? v.Tuple[1] : DynValue.Nil;
                    var = v.Tuple.Length >= 3 ? v.Tuple[2] : DynValue.Nil;

                    m_ValueStack.Push(DynValue.NewTuple(f, s, var));
                }
                else if (f.Type == DataType.Table)
                {
                    var callmeta = GetMetamethod(f, "__call");

                    if (callmeta == null || callmeta.IsNil())
                    {
                        m_ValueStack.Push(EnumerableWrapper.ConvertTable(f.Table));
                    }
                }
            }

            m_ValueStack.Push(DynValue.NewTuple(f, s, var));
        }

        private int ExecJFor(Instruction i, int instructionPtr)
        {
            var val = m_ValueStack.Peek(0).Number;
            var step = m_ValueStack.Peek(1).Number;
            var stop = m_ValueStack.Peek(2).Number;

            var whileCond = (step > 0) ? val <= stop : val >= stop;

            if (!whileCond)
                return i.NumVal;
            return instructionPtr;
        }

        private void ExecIncr(Instruction i)
        {
            var top = m_ValueStack.Peek(0);
            var btm = m_ValueStack.Peek(i.NumVal);

            if (top.ReadOnly)
            {
                m_ValueStack.Pop();

                if (top.ReadOnly)
                    top = top.CloneAsWritable();

                m_ValueStack.Push(top);
            }

            top.AssignNumber(top.Number + btm.Number);
        }

        private void ExecCNot(Instruction i)
        {
            var v = m_ValueStack.Pop().ToScalar();
            var not = m_ValueStack.Pop().ToScalar();

            if (not.Type != DataType.Boolean)
                throw new InternalErrorException("CNOT had non-bool arg");

            if (not.CastToBool())
                m_ValueStack.Push(DynValue.NewBoolean(!(v.CastToBool())));
            else
                m_ValueStack.Push(DynValue.NewBoolean(v.CastToBool()));
        }

        private void ExecNot(Instruction i)
        {
            var v = m_ValueStack.Pop().ToScalar();
            m_ValueStack.Push(DynValue.NewBoolean(!(v.CastToBool())));
        }

        private void ExecBeginFn(Instruction i)
        {
            var cur = m_ExecutionStack.Peek();

            cur.Debug_Symbols = i.SymbolList;
            cur.LocalScope = new DynValue[i.NumVal];

            ClearBlockData(i);
        }

        private CallStackItem PopToBasePointer()
        {
            var csi = m_ExecutionStack.Pop();
            if (csi.BasePointer >= 0)
                m_ValueStack.CropAtCount(csi.BasePointer);
            return csi;
        }

        private int PopExecStackAndCheckVStack(int vstackguard)
        {
            var xs = m_ExecutionStack.Pop();
            if (vstackguard != xs.BasePointer)
                throw new InternalErrorException("StackGuard violation");

            return xs.ReturnAddress;
        }

        private IList<DynValue> CreateArgsListForFunctionCall(int numargs, int offsFromTop)
        {
            if (numargs == 0) return new DynValue[0];

            var lastParam = m_ValueStack.Peek(offsFromTop);

            if (lastParam.Type == DataType.Tuple && lastParam.Tuple.Length > 1)
            {
                var values = new List<DynValue>();

                for (var idx = 0; idx < numargs - 1; idx++)
                    values.Add(m_ValueStack.Peek(numargs - idx - 1 + offsFromTop));

                for (var idx = 0; idx < lastParam.Tuple.Length; idx++)
                    values.Add(lastParam.Tuple[idx]);

                return values;
            }
            return new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - numargs - offsFromTop, numargs, false);
        }

        private void ExecArgs(Instruction I)
        {
            var numargs = (int) m_ValueStack.Peek(0).Number;

            // unpacks last tuple arguments to simplify a lot of code down under
            var argsList = CreateArgsListForFunctionCall(numargs, 1);

            for (var i = 0; i < I.SymbolList.Length; i++)
            {
                if (i >= argsList.Count)
                {
                    AssignLocal(I.SymbolList[i], DynValue.NewNil());
                }
                else if ((i == I.SymbolList.Length - 1) && (I.SymbolList[i].i_Name == WellKnownSymbols.VARARGS))
                {
                    var len = argsList.Count - i;
                    var varargs = new DynValue[len];

                    for (var ii = 0; ii < len; ii++, i++)
                    {
                        varargs[ii] = argsList[i].ToScalar().CloneAsWritable();
                    }

                    AssignLocal(I.SymbolList[I.SymbolList.Length - 1], DynValue.NewTuple(Internal_AdjustTuple(varargs)));
                }
                else
                {
                    AssignLocal(I.SymbolList[i], argsList[i].ToScalar().CloneAsWritable());
                }
            }
        }

        private int Internal_ExecCall(int argsCount, int instructionPtr, CallbackFunction handler = null,
            CallbackFunction continuation = null, bool thisCall = false, string debugText = null,
            DynValue unwindHandler = null)
        {
            var fn = m_ValueStack.Peek(argsCount);
            var flags = (thisCall ? CallStackItemFlags.MethodCall : CallStackItemFlags.None);

            // if TCO threshold reached
            if ((m_ExecutionStack.Count > m_Script.Options.TailCallOptimizationThreshold && m_ExecutionStack.Count > 1)
                || (m_ValueStack.Count > m_Script.Options.TailCallOptimizationThreshold && m_ValueStack.Count > 1))
            {
                // and the "will-be" return address is valid (we don't want to crash here)
                if (instructionPtr >= 0 && instructionPtr < m_RootChunk.Code.Count)
                {
                    var I = m_RootChunk.Code[instructionPtr];

                    // and we are followed *exactly* by a RET 1
                    if (I.OpCode == OpCode.Ret && I.NumVal == 1)
                    {
                        var csi = m_ExecutionStack.Peek();

                        // if the current stack item has no "odd" things pending and neither has the new coming one..
                        if (csi.ClrFunction == null && csi.Continuation == null && csi.ErrorHandler == null
                            && csi.ErrorHandlerBeforeUnwind == null && continuation == null && unwindHandler == null &&
                            handler == null)
                        {
                            instructionPtr = PerformTCO(instructionPtr, argsCount);
                            flags |= CallStackItemFlags.TailCall;
                        }
                    }
                }
            }

            if (fn.Type == DataType.ClrFunction)
            {
                //IList<DynValue> args = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - argsCount, argsCount, false);
                var args = CreateArgsListForFunctionCall(argsCount, 0);
                // we expand tuples before callbacks
                // args = DynValue.ExpandArgumentsToList(args);
                var sref = GetCurrentSourceRef(instructionPtr);

                m_ExecutionStack.Push(new CallStackItem
                {
                    ClrFunction = fn.Callback,
                    ReturnAddress = instructionPtr,
                    CallingSourceRef = sref,
                    BasePointer = -1,
                    ErrorHandler = handler,
                    Continuation = continuation,
                    ErrorHandlerBeforeUnwind = unwindHandler,
                    Flags = flags
                });

                var ret = fn.Callback.Invoke(new ScriptExecutionContext(this, fn.Callback, sref), args, thisCall);
                m_ValueStack.RemoveLast(argsCount + 1);
                m_ValueStack.Push(ret);

                m_ExecutionStack.Pop();

                return Internal_CheckForTailRequests(null, instructionPtr);
            }
            if (fn.Type == DataType.Function)
            {
                m_ValueStack.Push(DynValue.NewNumber(argsCount));
                m_ExecutionStack.Push(new CallStackItem
                {
                    BasePointer = m_ValueStack.Count,
                    ReturnAddress = instructionPtr,
                    Debug_EntryPoint = fn.Function.EntryPointByteCodeLocation,
                    CallingSourceRef = GetCurrentSourceRef(instructionPtr),
                    ClosureScope = fn.Function.ClosureContext,
                    ErrorHandler = handler,
                    Continuation = continuation,
                    ErrorHandlerBeforeUnwind = unwindHandler,
                    Flags = flags
                });
                return fn.Function.EntryPointByteCodeLocation;
            }

            // fallback to __call metamethod
            var m = GetMetamethod(fn, "__call");

            if (m != null && m.IsNotNil())
            {
                var tmp = new DynValue[argsCount + 1];
                for (var i = 0; i < argsCount + 1; i++)
                    tmp[i] = m_ValueStack.Pop();

                m_ValueStack.Push(m);

                for (var i = argsCount; i >= 0; i--)
                    m_ValueStack.Push(tmp[i]);

                return Internal_ExecCall(argsCount + 1, instructionPtr, handler, continuation);
            }

            throw ScriptRuntimeException.AttemptToCallNonFunc(fn.Type, debugText);
        }

        private int PerformTCO(int instructionPtr, int argsCount)
        {
            var args = new DynValue[argsCount + 1];

            // Remove all cur args and func ptr
            for (var i = 0; i <= argsCount; i++)
                args[i] = m_ValueStack.Pop();

            // perform a fake RET
            var csi = PopToBasePointer();
            var retpoint = csi.ReturnAddress;
            var argscnt = (int) (m_ValueStack.Pop().Number);
            m_ValueStack.RemoveLast(argscnt + 1);

            // Re-push all cur args and func ptr
            for (var i = argsCount; i >= 0; i--)
                m_ValueStack.Push(args[i]);

            return retpoint;
        }

        private int ExecRet(Instruction i)
        {
            CallStackItem csi;
            var retpoint = 0;

            if (i.NumVal == 0)
            {
                csi = PopToBasePointer();
                retpoint = csi.ReturnAddress;
                var argscnt = (int) (m_ValueStack.Pop().Number);
                m_ValueStack.RemoveLast(argscnt + 1);
                m_ValueStack.Push(DynValue.Void);
            }
            else if (i.NumVal == 1)
            {
                var retval = m_ValueStack.Pop();
                csi = PopToBasePointer();
                retpoint = csi.ReturnAddress;
                var argscnt = (int) (m_ValueStack.Pop().Number);
                m_ValueStack.RemoveLast(argscnt + 1);
                m_ValueStack.Push(retval);
                retpoint = Internal_CheckForTailRequests(i, retpoint);
            }
            else
            {
                throw new InternalErrorException("RET supports only 0 and 1 ret val scenarios");
            }

            if (csi.Continuation != null)
                m_ValueStack.Push(
                    csi.Continuation.Invoke(new ScriptExecutionContext(this, csi.Continuation, i.SourceCodeRef),
                        new DynValue[1] {m_ValueStack.Pop()}));

            return retpoint;
        }

        private int Internal_CheckForTailRequests(Instruction i, int instructionPtr)
        {
            var tail = m_ValueStack.Peek(0);

            if (tail.Type == DataType.TailCallRequest)
            {
                m_ValueStack.Pop(); // discard tail call request

                var tcd = tail.TailCallData;

                m_ValueStack.Push(tcd.Function);

                for (var ii = 0; ii < tcd.Args.Length; ii++)
                    m_ValueStack.Push(tcd.Args[ii]);

                return Internal_ExecCall(tcd.Args.Length, instructionPtr, tcd.ErrorHandler, tcd.Continuation, false,
                    null, tcd.ErrorHandlerBeforeUnwind);
            }
            if (tail.Type == DataType.YieldRequest)
            {
                m_SavedInstructionPtr = instructionPtr;
                return YIELD_SPECIAL_TRAP;
            }

            return instructionPtr;
        }

        private int JumpBool(Instruction i, bool expectedValueForJump, int instructionPtr)
        {
            var op = m_ValueStack.Pop().ToScalar();

            if (op.CastToBool() == expectedValueForJump)
                return i.NumVal;

            return instructionPtr;
        }

        private int ExecShortCircuitingOperator(Instruction i, int instructionPtr)
        {
            var expectedValToShortCircuit = i.OpCode == OpCode.JtOrPop;

            var op = m_ValueStack.Peek().ToScalar();

            if (op.CastToBool() == expectedValToShortCircuit)
            {
                return i.NumVal;
            }
            m_ValueStack.Pop();
            return instructionPtr;
        }

        private int ExecAdd(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(ln.Value + rn.Value));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__add", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecSub(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(ln.Value - rn.Value));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__sub", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecMul(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(ln.Value*rn.Value));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__mul", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecMod(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                var mod = Math.IEEERemainder(ln.Value, rn.Value);
                if (mod < 0) mod += rn.Value;
                m_ValueStack.Push(DynValue.NewNumber(mod));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__mod", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecDiv(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(ln.Value/rn.Value));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__div", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecPower(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rn = r.CastToNumber();
            var ln = l.CastToNumber();

            if (ln.HasValue && rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(Math.Pow(ln.Value, rn.Value)));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__pow", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r);
        }

        private int ExecNeg(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var rn = r.CastToNumber();

            if (rn.HasValue)
            {
                m_ValueStack.Push(DynValue.NewNumber(-rn.Value));
                return instructionPtr;
            }
            var ip = Internal_InvokeUnaryMetaMethod(r, "__unm", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ArithmeticOnNonNumber(r);
        }

        private int ExecEq(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            // first we do a brute force equals over the references
            if (ReferenceEquals(r, l))
            {
                m_ValueStack.Push(DynValue.True);
                return instructionPtr;
            }

            // then if they are userdatas, attempt meta
            if (l.Type == DataType.UserData || r.Type == DataType.UserData)
            {
                var ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
                if (ip >= 0) return ip;
            }

            // then if types are different, ret false
            if (r.Type != l.Type)
            {
                if ((l.Type == DataType.Nil && r.Type == DataType.Void) ||
                    (l.Type == DataType.Void && r.Type == DataType.Nil))
                    m_ValueStack.Push(DynValue.True);
                else
                    m_ValueStack.Push(DynValue.False);

                return instructionPtr;
            }

            // then attempt metatables for tables
            if ((l.Type == DataType.Table) && (GetMetatable(l) != null) && (GetMetatable(l) == GetMetatable(r)))
            {
                var ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
                if (ip >= 0) return ip;
            }

            // else perform standard comparison
            m_ValueStack.Push(DynValue.NewBoolean(r.Equals(l)));
            return instructionPtr;
        }

        private int ExecLess(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            if (l.Type == DataType.Number && r.Type == DataType.Number)
            {
                m_ValueStack.Push(DynValue.NewBoolean(l.Number < r.Number));
            }
            else if (l.Type == DataType.String && r.Type == DataType.String)
            {
                m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) < 0));
            }
            else
            {
                var ip = Internal_InvokeBinaryMetaMethod(l, r, "__lt", instructionPtr);
                if (ip < 0)
                    throw ScriptRuntimeException.CompareInvalidType(l, r);
                return ip;
            }

            return instructionPtr;
        }

        private int ExecLessEq(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            if (l.Type == DataType.Number && r.Type == DataType.Number)
            {
                m_ValueStack.Push(DynValue.False);
                m_ValueStack.Push(DynValue.NewBoolean(l.Number <= r.Number));
            }
            else if (l.Type == DataType.String && r.Type == DataType.String)
            {
                m_ValueStack.Push(DynValue.False);
                m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) <= 0));
            }
            else
            {
                var ip = Internal_InvokeBinaryMetaMethod(l, r, "__le", instructionPtr, DynValue.False);
                if (ip < 0)
                {
                    ip = Internal_InvokeBinaryMetaMethod(r, l, "__lt", instructionPtr, DynValue.True);

                    if (ip < 0)
                        throw ScriptRuntimeException.CompareInvalidType(l, r);
                    return ip;
                }
                return ip;
            }

            return instructionPtr;
        }

        private int ExecLen(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();

            if (r.Type == DataType.String)
                m_ValueStack.Push(DynValue.NewNumber(r.String.Length));
            else
            {
                var ip = Internal_InvokeUnaryMetaMethod(r, "__len", instructionPtr);
                if (ip >= 0)
                    return ip;
                if (r.Type == DataType.Table)
                    m_ValueStack.Push(DynValue.NewNumber(r.Table.Length));

                else throw ScriptRuntimeException.LenOnInvalidType(r);
            }

            return instructionPtr;
        }

        private int ExecConcat(Instruction i, int instructionPtr)
        {
            var r = m_ValueStack.Pop().ToScalar();
            var l = m_ValueStack.Pop().ToScalar();

            var rs = r.CastToString();
            var ls = l.CastToString();

            if (rs != null && ls != null)
            {
                m_ValueStack.Push(DynValue.NewString(ls + rs));
                return instructionPtr;
            }
            var ip = Internal_InvokeBinaryMetaMethod(l, r, "__concat", instructionPtr);
            if (ip >= 0) return ip;
            throw ScriptRuntimeException.ConcatOnNonString(l, r);
        }

        private void ExecTblInitI(Instruction i)
        {
            // stack: tbl - val
            var val = m_ValueStack.Pop();
            var tbl = m_ValueStack.Peek();

            if (tbl.Type != DataType.Table)
                throw new InternalErrorException("Unexpected type in table ctor : {0}", tbl);

            tbl.Table.InitNextArrayKeys(val, i.NumVal != 0);
        }

        private void ExecTblInitN(Instruction i)
        {
            // stack: tbl - key - val
            var val = m_ValueStack.Pop();
            var key = m_ValueStack.Pop();
            var tbl = m_ValueStack.Peek();

            if (tbl.Type != DataType.Table)
                throw new InternalErrorException("Unexpected type in table ctor : {0}", tbl);

            tbl.Table.Set(key, val.ToScalar());
        }

        private int ExecIndexSet(Instruction i, int instructionPtr)
        {
            var nestedMetaOps = 100; // sanity check, to avoid potential infinite loop here

            // stack: vals.. - base - index
            var isNameIndex = i.OpCode == OpCode.IndexSetN;
            var isMultiIndex = (i.OpCode == OpCode.IndexSetL);

            var originalIdx = i.Value ?? m_ValueStack.Pop();
            var idx = originalIdx.ToScalar();
            var obj = m_ValueStack.Pop().ToScalar();
            var value = GetStoreValue(i);
            DynValue h = null;

            while (nestedMetaOps > 0)
            {
                --nestedMetaOps;

                if (obj.Type == DataType.Table)
                {
                    if (!isMultiIndex)
                    {
                        if (!obj.Table.Get(idx).IsNil())
                        {
                            obj.Table.Set(idx, value);
                            return instructionPtr;
                        }
                    }

                    h = GetMetamethodRaw(obj, "__newindex");

                    if (h == null || h.IsNil())
                    {
                        if (isMultiIndex)
                            throw new ScriptRuntimeException("cannot multi-index a table. userdata expected");

                        obj.Table.Set(idx, value);
                        return instructionPtr;
                    }
                }
                else if (obj.Type == DataType.UserData)
                {
                    var ud = obj.UserData;

                    if (!ud.Descriptor.SetIndex(GetScript(), ud.Object, originalIdx, value, isNameIndex))
                    {
                        throw ScriptRuntimeException.UserDataMissingField(ud.Descriptor.Name, idx.String);
                    }

                    return instructionPtr;
                }
                else
                {
                    h = GetMetamethodRaw(obj, "__newindex");

                    if (h == null || h.IsNil())
                        throw ScriptRuntimeException.IndexType(obj);
                }

                if (h.Type == DataType.Function || h.Type == DataType.ClrFunction)
                {
                    if (isMultiIndex)
                        throw new ScriptRuntimeException("cannot multi-index through metamethods. userdata expected");

                    m_ValueStack.Push(h);
                    m_ValueStack.Push(obj);
                    m_ValueStack.Push(idx);
                    m_ValueStack.Push(value);
                    return Internal_ExecCall(3, instructionPtr);
                }
                obj = h;
                h = null;
            }
            throw ScriptRuntimeException.LoopInNewIndex();
        }

        private int ExecIndex(Instruction i, int instructionPtr)
        {
            var nestedMetaOps = 100; // sanity check, to avoid potential infinite loop here

            // stack: base - index
            var isNameIndex = i.OpCode == OpCode.IndexN;

            var isMultiIndex = (i.OpCode == OpCode.IndexL);

            var originalIdx = i.Value ?? m_ValueStack.Pop();
            var idx = originalIdx.ToScalar();
            var obj = m_ValueStack.Pop().ToScalar();

            DynValue h = null;

            while (nestedMetaOps > 0)
            {
                --nestedMetaOps;

                if (obj.Type == DataType.Table)
                {
                    if (!isMultiIndex)
                    {
                        var v = obj.Table.Get(idx);

                        if (!v.IsNil())
                        {
                            m_ValueStack.Push(v.AsReadOnly());
                            return instructionPtr;
                        }
                    }

                    h = GetMetamethodRaw(obj, "__index");

                    if (h == null || h.IsNil())
                    {
                        if (isMultiIndex)
                            throw new ScriptRuntimeException("cannot multi-index a table. userdata expected");

                        m_ValueStack.Push(DynValue.Nil);
                        return instructionPtr;
                    }
                }
                else if (obj.Type == DataType.UserData)
                {
                    var ud = obj.UserData;

                    var v = ud.Descriptor.Index(GetScript(), ud.Object, originalIdx, isNameIndex);

                    if (v == null)
                    {
                        throw ScriptRuntimeException.UserDataMissingField(ud.Descriptor.Name, idx.String);
                    }

                    m_ValueStack.Push(v.AsReadOnly());
                    return instructionPtr;
                }
                else
                {
                    h = GetMetamethodRaw(obj, "__index");

                    if (h == null || h.IsNil())
                        throw ScriptRuntimeException.IndexType(obj);
                }

                if (h.Type == DataType.Function || h.Type == DataType.ClrFunction)
                {
                    if (isMultiIndex)
                        throw new ScriptRuntimeException("cannot multi-index through metamethods. userdata expected");
                    m_ValueStack.Push(h);
                    m_ValueStack.Push(obj);
                    m_ValueStack.Push(idx);
                    return Internal_ExecCall(2, instructionPtr);
                }
                obj = h;
                h = null;
            }

            throw ScriptRuntimeException.LoopInIndex();
        }
    }
}


Upon his arrival at Noi Bai International Airport, the Cuban President was greeted by Thi Ngoc Thinh, Vice President of the Socialist Republic of Vietnam, as well as other government leaders.
The Cuban delegation includes Foreign Minister Bruno Rodríguez Parrilla; Council of Ministers Vice President Ricardo Cabrisas Ruiz; Minister of Communications Jorge Luis Perdomo Di-Lella; Deputy Foreign Minister Rogelio Sierra Díaz; and Cuban ambassador Lianys Torres Rivera.
This is the first time Díaz-Canel has visited this sister country, with which Cuba maintains special bilateral relations based on the longstanding ties of friendship and solidarity shared by the two peoples, parties, and governments.


Contact Roberts Farm Equipment for all of your Allis Chalmers Tractor, Model 160, New and Used Hydraulic System needs. We stock and sell tractor parts for all manufacturers from the 1920's vintage to the 2000's, with packages sent worldwide daily.
Gap Tractor Parts, Inc. has been the source for new, used and rebuilt farm tractor parts since 1969.


text:
require 'rails_helper'

describe Staff::Authenticator do
  describe '#authenticate' do
    # 正しいパスワードならtrueを返す
    it 'should return true given valid password' do
      m = build(:staff_member)
      expect(Staff::Authenticator.new(m).authenticate('pw')).to be_truthy
    end

    # 誤ったパスワードならfalseを返す
    it 'should return false given invalid password' do
      m = build(:staff_member)
      expect(Staff::Authenticator.new(m).authenticate('xy')).to be_falsey
    end

    # パスワード未設定ならfalseを返す
    it 'should return false given nil password' do
      m = build(:staff_member)
      expect(Staff::Authenticator.new(m).authenticate(nil)).to be_falsey
    end

    # 停止フラグが立っていればfalseを返す
    it 'should return false given suspended true' do
      m = build(:staff_member, suspended: true)
      expect(Staff::Authenticator.new(m).authenticate('pw')).to be_falsey
    end

    # 開始前ならfalseを返す
    it 'should return true given before start date' do
      m = build(:staff_member, start_date: Date.tomorrow)
      expect(Staff::Authenticator.new(m).authenticate('pw')).to be_falsey
    end

    # 終了後ならfalseを返す
    it 'should return false given after end date' do
      m = build(:staff_member, end_date: Date.today)
      expect(Staff::Authenticator.new(m).authenticate('pw')).to be_falsey
    end
  end
end


text:
Mountain View Cemetery, Longmont, Boulder County, Colorado, USA
Geographische Breite: 40.1795085, Geographische Länge: -105.1039061
22.853 Graves (Sep 2018)
620 11th Avenue, Longmont, Boulder County, Colorado, USA
Cemetery notes and/or description:
Also known as: Longmont Cemetery
Longmont was founded in 1871 by a group of people from Chicago, Illinois as the second colony in Colorado territory. The original date of the Mountain View Cemetery is not known definitively, but the first recorded burial was of John F. Owen in May of 1876, and this is just prior to Colorado becoming the 38th state (the Centennial State) on August 1, 1876.
The cemetery is located at 620 11th Avenue, within the city limits of Longmont, Colorado, and is found less than one mile north of the center of town. The main entrance for the cemetery and the cemetery office are both located on 11th Avenue in the block just west of Main Street (which is also known as Rte 287).
As of 2014, the cemetery has about 22,500 burials and includes a six section Mausoleum and three Columbariums, all accessible from 11th Avenue. The cemetery office is available to assist visitors five days a week, Monday through Friday excluding holidays.
Bowersox, Arlie E.
Bowersox, U. S. Grant
Franklin, William James
Howes, Ethel
Lichtenberger, Nettie I.
Orbach, Elisabetha
Zimbelman, Fred P.
Zimbelman, Harold R.
Zimbelmann, Doris B.
Zimbelmann, Friedrich
1. Bowersox, Arlie E. gest. 1966 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165253
2. Bowersox, Gayle gest. 15 Apr 1985 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165251
3. Bowersox, Dr. U. S. Grant gest. 10 Jan 1958 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165247
4. Franklin, William James gest. 29 Jul 2018 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I183606
5. Howes, Ethel gest. 20 Mrz 1969 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165248
6. Lichtenberger, Nettie I. gest. Sep 1978 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165254
7. Niven, Clarence E. gest. 15 Jan 1991 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I165252
8. Orbach, Elisabetha gest. 19 Jun 1968 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I143525
9. Zimbelman, Doris B. - wife of gest. 30 Mai 1989 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I143533
10. Zimbelman, Fred P. gest. 29 Okt 1988 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I143527
11. Zimbelman, Harold R. gest. 28 Apr 2009 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I143526
12. Zimbelmann, Friedrich gest. Aug 1974 Mountain View Cemetery, Longmont, Boulder County, Colorado, USA I136147

redpajama_set_name: RedPajamaCommonCrawl


text:
Light Earth
For at least the past 40 years, predictions about the fate of the planet have been mostly gloomy. From pollution to the population explosion, depletion of natural resources, and global warming, forecasts have concentrated on an ever-diminishing quality of life for earth's inhabitants.
However, some leading researchers and policy makers see evidence that the future may not be as bleak as we once thought. Environmental thinkers who gathered for a major conference on the planet's future last November saw reasons for optimism. William Clark, an authority on environmental issues at Harvard University and a recipient of a MacArthur Foundation genius grant, pointed to evidence that man is accomplishing more with less stress on the environment. He predicted that population growth will level off by the end of the 21st century.
James Hansen, director of NASA's Goddard Institute for Space Studies, popularized the issue of global warming in his testimony before Congress in 1988. He, too, sees room for optimism. While he believes the next 10 years will be the hottest in United States history, he is encouraged to see that releases of greenhouse gases have slowed in the past 20 years.
Although, they expressed optimism, the conference participants were clear that there are still major concerns, and that much remains to be done. The 20th century has done, by many measures, unprecedented damage to the natural world. The world's population has soared to six billion—four times what it was at the beginning of the century. So many bodies of water have been dammed that geophysicists say it has perceptibly altered the way the earth rotates. The discovery of oil and the development of the modern chemical industry have created both great wealth and major environmental problems. The burning of fossil fuels has increased the atmospheric concentrations of carbon dioxide by 30 percent. More than 70,000 synthetic chemicals have been introduced, some of them highly toxic, that have resulted in hazardous waste sites and pollution of rivers and lakes.
Recognition of the problems, particularly in the industrialized West, has begun to bring improvements and solutions. Food production, for example, has increased dramatically. One hectare of U.S. farmland that once fed three people can now feed 80. Many acres of less-productive farmland have been returned to forestland in places like Massachusetts that were nearly treeless more than a century ago. Simple plumbing changes have significantly reduced the amount of water used. Industrial pollution has dropped steadily as the U.S. has moved from a smokestack economy to a technology-based economy, and has enacted strict environmental standards.
The developing nations have not made the environmental improvements that are seen in the industrialized countries. However, even in the developing world, standards have risen. Infant mortality has dropped, literacy has risen, and real incomes have quadrupled. There are indications that leaders in the developing world understand that economic progress cannot come at the expense of the environment.
In many ways, the optimism of the conference participants hinges on the belief that technology will be able to produce solutions to environmental problems that do not derail the booming world economy. The solutions must involve both the Western world and the developing world, which often have competing interests. Major challenges lie ahead, and progress is not certain. Mikhail Gorbachev, the former leader of the Soviet Union, best summed up the mood of the conference when he suggested that humans can solve even the worst problems—if they choose to do so.


text:
Q: Conditional Formatting for cells that are higher than 50% is also applied to $ values I have code I grabbed from a random place.
I have a spreadsheet with over 100 tabs (or sheets).
I want to highlight all cells that are higher than 50%.
I have some $ values in columns A, B and C.
The code also picks up $0.50 - $1.50 and I don't want that.
Sub AddCF()
    Dim w As Worksheet
    For Each w In Worksheets
        With w.UsedRange.FormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, Formula1:="=0.50", Formula2:="1.50")
            .Font.Color =vbWhite
            .Font.Bold = True
            .Interior.Color = vbRed
        End With
    Next w
End Sub

A: even though it's probably not the most performatic way to do it, try this:
Sub AddCF()
Dim w As Worksheet
For Each w In Worksheets
With w.UsedRange.FormatConditions.Add(Type:=xlCellValue, Operator:=xlBetween, Formula1:="=0.50", Formula2:="<1.00")
    .Font.Color = vbWhite
    .Font.Bold = True
    .Interior.Color = vbRed

End With

With w.Columns("A:C")
.FormatConditions.Delete
End With
Next w
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Luna is a census-designated place in northwestern Catron County, New Mexico, United States. As of the 2010 census it had a population of 158. It is situated on the San Francisco River and U.S. Route 180,  east of the Arizona border and  northwest of Reserve, the Catron county seat.

Demographics

History
In the 19th century Luna was part of the extensive lands of Don Salomon Luna, and the valley was used for sheep ranching. It briefly was an outlaw hide-away, but was settled by Mormon ranchers in 1883 and subject to Chiricahua Apache attacks until the surrender of Geronimo. The town was named after Don Salomon Luna.

The post office was opened in 1886;

Education
It is in the Reserve Independent School District.

Culture

"Mormon Pioneer Day" is celebrated on the Saturday closest to July 24 at the village rodeo grounds with a parade, rodeo and dance.

On the 4th of July, festivities are held as well as a cake making contest.

See also

 List of census-designated places in New Mexico

References

 Pearce, T. M. (1965) "Luna" New Mexico place names; a geographical dictionary University of New Mexico Press, Albuquerque, NM, p. 94, OCLC 420847
 Julyan, Robert Hixson (1998) "Luna" The place names of New Mexico (2nd ed.) University of New Mexico Press, Albuquerque, NM, p. 215,

External links

 Banks, Phyllis Eileen (30 December 2002) "Luna — holding on to history" Southern New Mexico dotcom

Census-designated places in Catron County, New Mexico
Census-designated places in New Mexico
Populated places established in 1883

redpajama_set_name: RedPajamaWikipedia