text
stringlengths
13
30k
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (2).wav", "text": "If a writer of prose knows enough about what he is writing about, \nhe may omit things that he knows and the reader, if the writer is writing truly enough, will have a feeling of those things as strongly as though the writer had stated them. The dignity of movement of an iceberg is due to only one-eighth of it being above water."}
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (4).wav", "text": "He remembered the time he had hooked one of a pair of marlin. The male fish always let the female fish feed first and the hooked fish, the female, made a wild, panic-stricken, despairing fight that soon exhausted her, and all the time the male had stayed with her, crossing the line and circling with her on the surface."}
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (6).wav", "text": "Then, while the old man was clearing the lines and preparing the harpoon, the male fish jumped high into the air beside the boat to see where the female was and then went down deep, his lavender wings, that were his pectoral fins, spread wide and all his wide lavender stripes showing. He was beautiful, the old man remembered, and he had stayed."}
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (7).wav", "text": "If people bring so much courage to this world the world has to kill them to break them,\n so of course it kills them. The world breaks every one and afterward many are strong at the broken places. But those that will not break it kills. It kills the very good and the very gentle and the very brave impartially. If you are none of these you can be sure it will kill you too but there will be no special hurry."}
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (9).wav", "text": "The hallway smelt of boiled cabbage and old rag mats. At one end of it a coloured poster, \ntoo large for indoor display, had been tacked to the wall. It depicted simply an enormous face, more than a metre wide: the face of a man of about forty-five, with a heavy black moustache and ruggedly handsome features."}
{"audio": "/Users/jesse/Google Drive/Elucidate/TCRecoveries/Proof of Concept/Audio_Files/Training/Recording (10).wav", "text": "Winston made for the stairs. It was no use trying the lift. Even at the best\n of times it was seldom working, and at present the electric current was cut off during daylight hours."}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: The Somerset & Dorset Railway Heritage Trust one day hopes to operate steam trains for a mile up to Chilcompton Tunnel but there remains much to do before this can happen .\n\nAnswers: to operate steam trains for a mile up to Chilcompton Tunnel\nwhat is being hoped ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Sanford emphasizes the variety available in their curriculum , allowing each student to discover their own strengths and weaknesses and to construct a rigorous course load to accommodate such .\n\nAnswers: such, their own strengths and weaknesses\nwhat might something accommodate ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: However , these do not sell the full range of tickets , for instance they do not sell Cheap Evening Returns , so that in the evening passengers can pay double the fare that they need to pay for the journey they are making , if they purchase tickets from the machine .\n\nAnswers: they\nwho is making something ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Pitt was a leading advocate of a more hard-line policy against Spain , and often castigated Walpole 's government for its weakness in dealing with Madrid .\n\nAnswers: Pitt\nwho was leading something ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: His son Michael serves as manager of the company , and , after being passed over for a promotion , decides to leave both the company and his family .\n\nAnswers: His son Michael\nwho was passed over for something ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: The semi-aluminum monocoque chassis was epoxy bonded and riveted with an aluminum honeycomb floor pan , and 5,000 aircraft specification rivets were used in the car 's assembly .\n\nAnswers: an aluminum honeycomb floor pan\nwhat was something bonded with ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Iaquinta played 40 matches for the Italy national football team between 2005 and 2010 , scoring six goals .\n\nAnswers: the Italy national football team\nwho did someone play something for ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Set in an alternate near-future Japan , the protagonist of the story , a young woman codenamed `` Kabuki '' , acts as an agent and television law-enforcement personality for a clandestine government body known as `` The Noh '' .\n\nAnswers: an agent, television law-enforcement personality\nwhat is someone acting as ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Each base also had an assigned Naval Air Reserve Training Unit , which until a reorganization of the Naval Air Reserve in 1970 , actually `` owned '' all assigned aircraft .\n\nAnswers: Each base\nwhat had assigned something ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "Generate a plausible question that has the following answers based on the context:\n\nContext: Alan transforms into an alien creature and attacks Ed .\n\nAnswers: Alan\nwho attacks someone ?", "dataset": "qa_srl", "prompt": "generate_question", "label": 1}
{"text": "York"}
{"text": "Tmmy lee Jones super realistic detailed beautiful detailed portrait --test --ar 8:10"}
{"text": "a beautiful rendition of the god of jelly fishes machines, thousands of acid flowers, high voltage magic, ornate, arcane electricity, complex scene , highly detailed. --w 2160 --h 3840"}
{"text": "floating microbacteria, fibers, forming a gigantic human body, standing on a planet, enviroment, nebula, space tunnel, 4k, octane render, houdini particles, high detailed, hyper-realistic, cinematic, epic, moody, Photography by Sarah Morris, Hellen van Meene, Craig Mullens, artstation, nasa, lens dirt, --ar 16:9"}
{"text": "--wallpaper"}
{"text": "polaroid of a mysterious figure ina black flowing in the wind cloak in a detailed dark spooky forest infront of full eclipse in the style of floria sigismondi and matt mahurin and robert mapplethorpe cinematic depth moody dark film emulsion photograph"}
{"q_id": "32wvn8", "title": "what's the difference between a forest and a wood?", "selftext": "", "document": "", "subreddit": "explainlikeimfive", "url": "http://www.reddit.com/r/explainlikeimfive/comments/32wvn8/eli5_whats_the_difference_between_a_forest_and_a/", "answers": {"a_id": ["cqfd1d8"], "score": [2], "text": ["They're used interchangeably a lot. You'll get different answers from different resources, but the general consensus seems to be that woods are smaller than forests.\n\n > A wood is an area covered in trees, larger than a grove or a copse. A forest is also an area covered in trees, but it is larger than a wood\n\n > The U.S. National Vegetation Classification system differentiates them according to their densities: 25 to 60 percent of a a wood is covered by tree canopies, while 60 to 100 percent of a forest is canopied."]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[]]}
{"q_id": "elzx1n", "title": "we do we instinctively grab a part of our body after it is hurt?", "selftext": "I just tweaked my wrist and my immediate reaction was to grasp it. I have no idea if grabbing it actually does anything, but it seems to be a natural reaction for most people when a body part hurts. Why is that?", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/elzx1n/eli5_we_do_we_instinctively_grab_a_part_of_our/", "answers": {"a_id": ["fdlfvnn", "fdltn5j"], "score": [11, 3], "text": ["A) instinct. To protect it from further damage (if the damaging agent is ongoing) or to prevent bleeding and such.\n\nB) pain. Our brain knows that pressure sensation blocks pain sensation from experience. So we reflexively grab the injury site because it alleviates the pain.\n\nEdit: English and clarity", "So you have 2 different types of pressure sensors in your skin, superficial or closer to the surface and deep. Pressure sensors report back to the brain faster than pain sensors do so you can \"jam the signal\" ish by applying pressure. Say you put your hand on a hot burner, the spine has limited commands it can give to the body in case the brain can't give commands (see stroke victims) or to protect the body from further damage. This means that the pain signal follows tracks of nerve impulses to the spine where a quick response is sent back while a detailed report of the pain is sent to the sensory part of the brain for further analysis. The brain follows up the damage report by checking sensation, applying pressure or grabbing the area. Typically you also visually check it as well to see how the skin in the area is doing."]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], []]}
{"q_id": "3lv8jv", "title": "what causes \"flashing lights\", or blurry vision after strenuous physical activity?", "selftext": "Had this happen to my younger brother. My parents are convinced he has a concussion and are having him see multiple doctors and are preventing him from doing any physical activity until further notice, as well as most-likely inhibiting him from joining the wrestling team for his high school. I don't want this to happen.\n\nHe had no significant amount of water before an hour workout that included 10 minutes of jump roping followed by 50 minutes of lifting. \n\nMy brother claims to have seen flashing lights after he stood up from a 10 minute car ride home. \n", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/3lv8jv/eli5_what_causes_flashing_lights_or_blurry_vision/", "answers": {"a_id": ["cv9l5or"], "score": [2], "text": ["**NOTE**: I am not a medical doctor, and this is not a diagnosis; just the best attempt I can at explaining it.\n\nIt's likely caused by the gel inside of his eyes rubbing on or pulling at the retina. If he stood up after a car ride, it can cause a change in blood pressure as well, which would lead to less oxygen going to the brain and some experience flashes of light along with a narrowing of the field of vision."]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[]]}
{"q_id": "1rwxa7", "title": "if an ambulance on its way to a call witnesses an accident, what do they do?", "selftext": "", "document": "", "subreddit": "explainlikeimfive", "url": "http://www.reddit.com/r/explainlikeimfive/comments/1rwxa7/eli5_if_an_ambulance_on_its_way_to_a_call/", "answers": {"a_id": ["cdrqan1", "cdrqmb0"], "score": [9, 3], "text": ["It depends on the severity of the accident compared to the severity of the call they're en route to. If they see a horrible car wreck, and they're on a call for a broken bone, they'll stop for the wreck and radio in to let the dispatcher know to send out a new ambulance for the initial call. However, if they were on their way to a heart attack victim, they'll likely radio in and request a new ambulance for the wreck.", "Paramedic here.\n\nWe stop, have a short look and call dispatch. Ultimately, until we reach the patient it's their call so they set the priorities in such a situation."]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], []]}
{"q_id": "272ed8", "title": "how do i know that i don't have depth perception?", "selftext": "Could I lack depth perception and just not know it?", "document": "", "subreddit": "explainlikeimfive", "url": "http://www.reddit.com/r/explainlikeimfive/comments/272ed8/eli5_how_do_i_know_that_i_dont_have_depth/", "answers": {"a_id": ["chwv0xm"], "score": [2], "text": ["Sure, if you've never experienced true binocularity (brain fusing each eye's image into one that is 3D), you might not realize you don't have it. It's possible to develop that skill so long as both eyes are physically intact and functional and so is your brain. Neuroscience ftw!\n\n A book that discusses this is \"Stereo Sue\" by Sue Barry about a lady scientist who didn't realize that very thing she was in her 50s and was able to regain it. It's an interesting story! "]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[]]}
{"q_id": "8oarq7", "title": "since oil & water don't mix, how are essential oil soaks helpful?", "selftext": "Doesn't the oil just sit on the surface, like it looks, reaching the intended body parts only in the small area that intersects with the top of the water? Or does it slowly mix with the water?", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/8oarq7/eli5_since_oil_water_dont_mix_how_are_essential/", "answers": {"a_id": ["e01xr6g", "e01z28r"], "score": [11, 6], "text": ["As far as I know there is no scientific proof that essential oils work anyway, but yes your skin can only absorb so much.", "Essential oils are worthless for everything but smelling good anyway, so adding water certainly doesn't improve anything"]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], []]}
{"q_id": "75t27i", "title": "if a nuclear bomb is dropped on other nuclear bombs that are idle on the ground, will it create a double explosion or do these weapons need to become 'activated' in order for them to be able to detonate?", "selftext": "", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/75t27i/eli5_if_a_nuclear_bomb_is_dropped_on_other/", "answers": {"a_id": ["do8pkru", "do8pkuz", "do8ps5a", "do8pyoe", "do8q57e", "do8ygs7"], "score": [2, 2, 2, 12, 7, 5], "text": ["a nuclear device functions by joining two or more chunks of radioactive material with explosive force together attaining a critical sustainable mass. A nuke dropped on nukes would not trigger this....the grounded nukes could only, theoretically, add to the radioactive fallout as their unspent nuclear material is scattered about \n\nPs your premise is a bit flawed as MOST nukes are detonated ABOVE a target, not on impact with it. ", "Nuclear bombs need to be set off in a controlled way in order to explode in the massive yield they normally would. However they contain conventional explosives which would certainly spread radioactive material around. But if you are setting them off with a nuke that won't be a big impact.", "In any design that's actually been built the nuclear bomb can't be detonated externally, they must be triggered through a very specific and carefully timed sequence of events.\n\nBombing them would just damage them and possibly scatter radioactive material.", "Depends on a lot of things.\n\nNuclear bombs work by changing the critical mass of the nuclear fuel. \"Critical mass\" is the amount of nuclear material you need to have a sustained nuclear reaction. You can artificially make a smaller-than-critical mass into a critical mass in several ways. One way is to cover it with a material that reflects neutrons (which would cause all the neutrons that would've escaped outwards from the material to reflect back inwards, generally used in nuclear reactors and research), but another way is to change the temperature and pressure of the material (which is done in nuclear weapons by using \"explosive lenses\" which is a fancy way of saying you surround it with conventional explosives).\n\nWithout those explosives going off (and a few other things I'd guess) that nuclear weapon isn't actually fissile (able to undergo fission). A nuclear explosion above the silo where the bombs are stored is just as likely to vaporize the exposive as anything else, not to mention that unless that explosion is able to actually trigger the explosive correctly it's not going to explode. (C4 and TNT for example are completely safe to burn, and only explode with specific stimulii.)\n\n", "Detonating a nuclear bomb is a very precise process, a lot of complicated things have to happen in just the right order. Even the most primitive bombs would be unlikely to go off in a high order explosion just because of a nearby explosion, nuclear or not. Modern nuclear weapons are actually deliberately designed so this is impossible, as a safety measure.", "Nuclear weapons are conceptually simple, you smash together enough U-235 (a 'supercritical mass') and it goes boom. The hard part is making it go boom when you want it to, and NOT melt when it's sitting in a silo.\n\nThere are two kinds of 'explosions' that occur in a nuclear weapon. The most obvious one is the nuclear fission chain reaction that makes a nuke what it is, which I'll call 'nuclear detonation'. The second kind of explosion (technically the first to happen) is what I'll call a 'primary detonation', which is a bunch of high explosives rigged precisely to trigger or 'ignite' the big boom.\n\nThere are two main ways in which these parts are put together, the 'Gun' and the 'implosion' methods. In the gun device, a big slug of U-235 is shot at high speed into another mass of U-235 that fits it like a glove, bringing together a supercritical mass. This device was constructed during the Manhattan Project by essentially strapping a bunch of expensive equipment and U-235 to an artillery piece and firing it. The second method uses a hollow sphere (also known as a pit) made of Uranium. In its hollow shape, the mass is not supercritical, but when it is compressed by the primary detonation into a solid ball, the mass becomes supercritical. It's a lot like crushing a soda can, but your hands are TNT and the soda can is going to blow your block party off the map.\n\nIn both methods of detonation, the critical mass must be brought together very quickly and very precisely. Otherwise, instead of the desired nuclear ignition, a 'premature detonation' will occur, severely reducing the weapon's power (loads better for the world than premature ejaculation ;). \n\nSo, to answer the question, if a nuclear warhead were dropped on a warehouse full of nukes, it would NOT cause nuclear detonations in the other weapons. It would, however, cause lots of bad shit, including:\n\n-Big Boom from the original warhead\n\n-All of the nuclear materials in the bombs is now volatile nuclear waste that may be in various states of criticality and may or may not fissioning and creating more hazardous waste. To get an idea of what this could develop into in the worst case scenario, read up on the elephant's foot at Chernobyl. Its not exactly the same situation, but Chernobyl gives us an idea of how difficult it is to move and protect ourselves from uncontained fission materials.\n\n-Detonation of high explosives from primary detonation systems of other bombs. This is unlikely to cause any nuclear detonations because the precision of the detonation is completely overwhelmed by the initial warhead, but explosives are explosives. TBH the size of these explosions is nothing compared to the initial weapon's power, and amounts to something like a mosquito bite on an arm that a bear just tore off of you.\n\n-WWIII (Assuming some head-ass didn't bomb their own country, which almost happened once in North Carolina I think)\n\n\nTL;DR: No, it won't cause a 'Double Explosion', but it's still a nuke, and it's gonna kill the heck out of you.\n\n\nSide note: For similar reasons, nuking or crashing a plane into a nuclear power plant does not cause a nuclear detonation. Nuclear weapons are devices carefully orchestrated and calibrated to 'make the stars align' so to speak, and create the very narrow conditions that make a nuclear explosion possible. On the other hand, a power plant is designed to generate electricity in a sustained and controlled fashion, which inherently precludes the possibility of a nuclear detonation, simply because the specifications on how to trigger a nuclear detonation are so tight."]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], [], [], [], [], []]}
{"q_id": "7wy34p", "title": "why do bottles of liquid have a dent/semi circle at the bottom of them?", "selftext": "My brother told me a while ago that it prevents it from exploding or something. Is there an act", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/7wy34p/eli5_why_do_bottles_of_liquid_have_a_dentsemi/", "answers": {"a_id": ["du43702", "du44tut", "du45aky", "du47c2j", "du4c6z3"], "score": [31, 11, 9, 5, 3], "text": ["Its to make the plastic stronger. Without it they would have to add much more plastic to make it stable, which is more expensive. The bottle wouldn't explode, but it would cause the thinner areas to sag and deform. That would increase the chance of it bursting apart when force is applied. But with the divot, that sort of outcome is essentially impossible.", "It can be for strength, if the contents are under pressure, or it can just be so it will sit flat on a surface without rocking. You could in theory do that with a perfectly flat bottom, but that requires more precise and expensive molds(have to account for distortion as it cools too). Or it can be to make the bottle look bigger, compared to its volume. \n\n", "If you had a flat bottom it would simply bulge out. Now you would have a shitty bottle that can't stand. The dome simply distributes the forces evenly to the outside ring of the dome. It's the outside ring that has a bit more ridigity that prevents that from deforming.\n\nI suggest you look up the making and design of a soda can on YouTube. It explains the engineering behind it. Pretty cool stuff. ", "The dent and curved rim on the bottom of a can gives it the strength to be stacked on without bursting", "I can't speak much for glass bottles, but plastic bottles and aluminum cans have these features so that if they freeze, the plastic will bulge out and pop into a new position that gives the liquid more free volume to occupy. This prevents a sticky mess on the consumer's garage floor"]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], [], [], [], []]}
{"q_id": "5by6yg", "title": "the dow futures is reported to have dropped 700 points already. what does that mean for retirement funds, the market in general, etc...?", "selftext": "", "document": "", "subreddit": "explainlikeimfive", "url": "https://www.reddit.com/r/explainlikeimfive/comments/5by6yg/eli5_the_dow_futures_is_reported_to_have_dropped/", "answers": {"a_id": ["d9s743x", "d9s7rst", "d9scu9p"], "score": [4, 14, 2], "text": ["It means that Mr. Market is scared, and the future looks really bleak. \n\nThe market believes a recession or worse is coming and that for the foreseeable future, things in an economic sense look bad. \n\nRetirement funds are based heavily on the stock market (not entirely) which will go down correspondingly. However, they are also based to some degree on bonds, which generally go up when stocks go down. \n\nGenerally....\n\nThe thing is, no one really truly knows the answer. And if they did, they could use that knowledge to make money. \n\nWhat it means for you and for me is that most experts foresee bad things happening. ", "What u/Chumkil said but it is unlikely to be a long-lasting drop, the underlying economy is strong and, once the excitement has died down, the markets will return to their original state - i.e. rising.\n\nThe BBC were talking about this yesterday, apparently these flash-crashes are more to do with computer algorithm trading more than human sentiment. Their analyst's advice to investors was \"play the long game and sit tight, use any significant drop to expand your portfolio.\"", "What I don't understand is how the market is falling, when markets have been closed since 4:00pm EST and the first polls don't close until 7....I mean I can see how people will forecast the drop tonight, but wouldn't the market have to open in the morning to actually drop?"]}, "title_urls": [], "selftext_urls": [], "answers_urls": [[], [], []]}
{"text": "Producto"}
{"text": ["NICM.SYS", "driver", "3.0.0.4", "", "as", "used", "in", "Novell", "NetWare", "Client", "4.91", "SP4", "", "allows", "local", "users", "to", "execute", "arbitrary", "code", "by", "opening", "the", "\\\\\\\\.\\\\nicm", "device", "and", "providing", "crafted", "kernel", "addresses", "via", "IOCTLs", "with", "the", "METHOD_NEITHER", "buffering", "mode."], "keyphrase": ["arbitrary code execution"]}
{"text": ["WebKit", "before", "r53525", "", "as", "used", "in", "Google", "Chrome", "before", "4.0.249.89", "", "allows", "remote", "attackers", "to", "execute", "arbitrary", "code", "in", "the", "Chrome", "sandbox", "via", "a", "malformed", "RUBY", "element", "", "as", "demonstrated", "by", "a", "<ruby>><table><rt>", "sequence."], "keyphrase": ["arbitrary code execution"]}
{"text": ["The", "affected", "product", "is", "vulnerable", "to", "an", "out-of-bounds", "write", "while", "processing", "project", "files", "", "which", "allows", "an", "attacker", "to", "craft", "a", "project", "file", "that", "would", "allow", "arbitrary", "code", "execution."], "keyphrase": ["arbitrary code execution"]}
{"text": ["Iris", "3.8", "before", "build", "1548", "", "as", "used", "in", "Xpient", "point", "of", "sale", "(POS)", "systems", "", "allows", "remote", "attackers", "to", "execute", "arbitrary", "commands", "via", "a", "crafted", "request", "to", "TCP", "port", "7510", "", "as", "demonstrated", "by", "opening", "the", "cash", "drawer."], "keyphrase": ["arbitrary command execution"]}
{"text": ["An", "access", "issue", "was", "addressed", "with", "additional", "sandbox", "restrictions.", "This", "issue", "is", "fixed", "in", "iOS", "12.3.", "A", "sandboxed", "process", "may", "be", "able", "to", "circumvent", "sandbox", "restrictions."], "keyphrase": ["circumvent sandbox restrictions"]}
{"text": ["An", "access", "issue", "was", "addressed", "with", "improved", "access", "restrictions.", "This", "issue", "is", "fixed", "in", "macOS", "Big", "Sur", "11.5", "", "Security", "Update", "2021-004", "Catalina", "", "Security", "Update", "2021-005", "Mojave.", "A", "sandboxed", "process", "may", "be", "able", "to", "circumvent", "sandbox", "restrictions."], "keyphrase": ["circumvent sandbox restrictions"]}
{"text": ["The", "affected", "product", "is", "vulnerable", "due", "to", "cleartext", "transmission", "of", "credentials", "seen", "in", "the", "CIMPLICITY", "network", "", "which", "can", "be", "easily", "spoofed", "and", "used", "to", "log", "in", "to", "make", "operational", "changes", "to", "the", "system."], "keyphrase": ["cleartext transmission"]}
{"text": ["A", "vulnerability", "in", "the", "web-based", "management", "interface", "of", "Cisco", "Firepower", "Management", "Center", "(FMC)", "could", "allow", "an", "unauthenticated", "", "remote", "attacker", "to", "conduct", "a", "cross-site", "scripting", "(XSS)", "attack", "against", "a", "user", "of", "the", "web-based", "management", "interface", "of", "an", "affected", "system.", "The", "vulnerability", "is", "due", "to", "insufficient", "validation", "of", "user-supplied", "input", "by", "the", "web-based", "management", "interface", "of", "the", "affected", "system.", "An", "attacker", "could", "exploit", "this", "vulnerability", "by", "persuading", "a", "user", "of", "the", "interface", "to", "click", "a", "maliciously", "crafted", "link.", "A", "successful", "exploit", "could", "allow", "the", "attacker", "to", "execute", "arbitrary", "script", "code", "in", "the", "context", "of", "the", "affected", "interface", "or", "access", "sensitive", "", "browser-based", "information."], "keyphrase": ["cross site scripting vulnerability"]}
{"text": ["SAP", "Information", "Steward", "", "version", "4.2", "", "does", "not", "sufficiently", "encode", "user-controlled", "inputs", "", "resulting", "in", "Cross-Site", "Scripting", "(XSS)", "vulnerability."], "keyphrase": ["cross site scripting vulnerability"]}
{"text": ["A", "persistent", "cross-site", "scripting", "(XSS)", "vulnerability", "in", "the", "Snort", "Rules", "configuration", "of", "Juniper", "ATP", "may", "allow", "authenticated", "user", "to", "inject", "arbitrary", "script", "and", "steal", "sensitive", "data", "and", "credentials", "from", "a", "web", "administration", "session", "", "possibly", "tricking", "a", "follow-on", "administrative", "user", "to", "perform", "administrative", "actions", "on", "the", "device.", "This", "issue", "affects", "Juniper", "ATP", "5.0", "versions", "prior", "to", "5.0.3."], "keyphrase": ["cross site scripting vulnerability"]}
{"aid": "cs9910011", "mid": "2168463568", "abstract": "A statistical model for segmentation and word discovery in child directed speech is presented. An incremental unsupervised learning algorithm to infer word boundaries based on this model is described and results of empirical tests showing that the algorithm is competitive with other models that have been used for similar tasks are also presented.", "related_work": "Model Based Dynamic Programming, hereafter referred to as MBDP-1 @cite_0 , is probably the most recent work that addresses the exact same issue as that considered in this paper. Both the approach presented in this paper and Brent's MBDP-1 are based on explicit probability models. Approaches not based on explicit probability models include those based on information theoretic criteria such as MDL , transitional probability or simple recurrent networks . The maximum likelihood approach due to Olivier:SGL68 is probabilistic in the sense that it is geared towards explicitly calculating the most probable segmentation of each block of input utterances. However, it is not based on a formal statistical model. To avoid needless repetition, we only describe Brent's MBDP-1 below and direct the interested reader at Brent:EPS99 which provides an excellent review of many of the algorithms mentioned above.", "ref_abstract": {"cite_N": ["@cite_0"], "mid": ["2074546930"], "abstract": ["This paper presents a model-based, unsupervised algorithm for recovering word boundaries in a natural-language text from which they have been deleted. The algorithm is derived from a probability model of the source that generated the text. The fundamental structure of the model is specified abstractly so that the detailed component models of phonology, word-order, and word frequency can be replaced in a modular fashion. The model yields a language-independent, prior probability distribution on all possible sequences of all possible words over a given alphabet, based on the assumption that the input was generated by concatenating words from a fixed but unknown lexicon. The model is unusual in that it treats the generation of a complete corpus, regardless of length, as a single event in the probability space. Accordingly, the algorithm does not estimate a probability distribution on wordss instead, it attempts to calculate the prior probabilities of various word sequences that could underlie the observed text. Experiments on phonemic transcripts of spontaneous speech by parents to young children suggest that our algorithm is more effective than other proposed algorithms, at least when utterance boundaries are given and the text includes a substantial number of short utterances."]}}
{"aid": "cs9903014", "mid": "1612660921", "abstract": "We present an open architecture for just-in-time code generation and dynamic code optimization that is flexible, customizable, and extensible. While previous research has primarily investigated functional aspects of such a system, architectural aspects have so far remained unexplored. In this paper, we argue that these properties are important to generate optimal code for a variety of hardware architectures and different processor generations within processor families. These properties are also important to make system-level code generation useful in practice.", "related_work": "Pioneering research in dynamic runtime optimization was done by Hansen @cite_8 who first described a fully automated system for runtime code optimization. His system was similar in structure to our system---it was composed of a loader, a profiler, and an optimizer---but used profiling data only to decide when to optimize and what to optimize, not how to optimize. Also, his system interpreted code prior to optimization, since load time code generation was too memory and time consuming at the time.", "ref_abstract": {"cite_N": ["@cite_8"], "mid": ["2101776604"], "abstract": ["Abstract : This thesis investigates adaptive compiler systems that perform, during program execution, code optimizations based on the dynamic behavior of the program as opposed to current approaches that employ a fixed code generation strategy, i.e., one in which a predetermined set of code optimizations are applied at compile-time to an entire program. The main problems associated with such adaptive systems are studied in general: which optimizations to apply to what parts of the program and when. Two different optimization strategies result: an ideal scheme which is not practical to implement, and a more basic scheme that is. The design of a practical system is discussed for the FORTRAN IV language. The system was implemented and tested with programs having different behavioral characteristics."]}}
{"text": "'''AuthenticationThe Stripe API uses API keys to authenticate requests. You can view and manage your API keys in the Stripe Dashboard.Test mode secret keys have the prefix sk_test_ and live mode secret keys have the prefix sk_live_. Alternatively, you can use restricted API keys for granular permissions.Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth.Use your API key by assigning it to stripe.api_key. The Python library will then automatically send this key in each request.You can also set a per-request key with an option. This is often useful for Connect applications that use multiple API keys during the lifetime of a process. Methods on the returned object reuse the same API key.All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.\n'''import stripe\nimport stripe\ncharge = stripe.Charge.retrieve(\n \"ch_3LSdyT2eZvKYlo2C0gCKd4XD\",\n api_key=\"sk_test_your_key\"\n)\ncharge.save() # Uses the same API Key.Your API KeyA sample test API key is included in all the examples here, so you can test any example right away. Do not submit any personally identifiable information in requests made with this key.To test requests using your account, replace the sample API key with your actual API key or sign in."}
{"text": "'''Connected AccountsClients can make requests as connected accounts using the special header Stripe-Account which should contain a Stripe account ID (usually starting with the prefix acct_).The value is set per-request as shown in the adjacent code sample. Methods on the returned object reuse the same account ID.See also Making API calls for connected accounts\n'''import stripe\ncharge = stripe.Charge.retrieve(\n \"ch_3LSdcO2eZvKYlo2C0QI5DNPX\",\n stripe_account=\"acct_1032D82eZvKYlo2C\"\n)\ncharge.save() # Uses the same account."}
{"text": "'''Handling errorsOur Client libraries raise exceptions for many reasons, such as a failed charge, invalid parameters, authentication errors, and network unavailability. We recommend writing code that gracefully handles all possible API exceptions.\n''''''PythoncURLStripe CLIRubyPythonPHPJavaNode.jsGo.NET12345678910111213141516171819202122232425262728293031try:\n # Use Stripe's library to make requests...\n pass\nexcept stripe.error.CardError as e:\n # Since it's a decline, stripe.error.CardError will be caught\n\n print('Status is: %s' % e.http_status)\n print('Code is: %s' % e.code)\n # param is '' in this case\n print('Param is: %s' % e.param)\n print('Message is: %s' % e.user_message)\nexcept stripe.error.RateLimitError as e:\n # Too many requests made to the API too quickly\n pass\nexcept stripe.error.InvalidRequestError as e:\n # Invalid parameters were supplied to Stripe's API\n pass\nexcept stripe.error.AuthenticationError as e:\n # Authentication with Stripe's API failed\n # (maybe you changed API keys recently)\n pass\nexcept stripe.error.APIConnectionError as e:\n # Network communication with Stripe failed\n pass\nexcept stripe.error.StripeError as e:\n # Display a very generic error to the user, and maybe send\n # yourself an email\n pass\nexcept Exception as e:\n # Something else happened, completely unrelated to Stripe\n pass\n'''"}
{"text": "'''Expanding ResponsesMany objects allow you to request additional information as an expanded response by using the expand request parameter. This parameter is available on all API requests, and applies to the response of that request only. Responses can be expanded in two ways.In many cases, an object contains the ID of a related object in its response properties. For example, a Charge may have an associated Customer ID. Those objects can be expanded inline with the expand request parameter. ID fields that can be expanded into objects are noted in this documentation with theexpandable label.In some cases, such as the Issuing Card object's number and cvc fields, there are available fields that are not included in responses by default. You can request these fields as an expanded response by using the expand request parameter. Fields that can be included in an expanded response are noted in this documentation with the expandable label.You can expand recursively by specifying nested fields after a dot (.). For example, requesting invoice.subscription on a charge will expand the invoice property into a full Invoice object, and will then expand the subscription property on that invoice into a full Subscription object.You can use the expand param on any endpoint which returns expandable fields, including list, create, and update endpoints.Expansions on list requests start with the data property. For example, you would expand data.customers on a request to list charges and associated customers. Many deep expansions on list requests can be slow.Expansions have a maximum depth of four levels (so for example, when listing charges,data.invoice.subscription.default_source is the deepest allowed).You can expand multiple objects at once by identifying multiple items in the expand array.\n'''import stripe\nstripe.api_key = \"sk_test_your_key\"\n\nstripe.Charge.retrieve(\n 'ch_3LSdrM2eZvKYlo2C1A6YRLyL',\n expand=['customer', 'invoice.subscription']\n)\n'''Response {\n \"id\": \"ch_3LSdrM2eZvKYlo2C1A6YRLyL\",\n \"object\": \"charge\",\n \"customer\": {\n \"id\": \"cu_18CHts2eZvKYlo2CbmAAQORe\",\n \"object\": \"customer\",\n ...\n },\n \"invoice\": {\n \"id\": \"in_1LSdrM2eZvKYlo2CdjHtGeNU\",\n \"object\": \"invoice\",\n \"subscription\": {\n \"id\": \"su_1JbiLB2eZvKYlo2CRmgET2WF\",\n \"object\": \"subscription\",\n ...\n },\n ...\n },\n ...\n}'''"}
{"text": "'''Idempotent RequestsThe API supports idempotency for safely retrying requests without accidentally performing the same operation twice. This is useful when an API call is disrupted in transit and you do not receive a response. For example, if a request to create a charge does not respond due to a network connection error, you can retry the request with the same idempotency key to guarantee that no more than one charge is created.To perform an idempotent request, provide an additional idempotency_key element to the request options.Stripe's idempotency works by saving the resulting status code and body of the first request made for any given idempotency key, regardless of whether it succeeded or failed. Subsequent requests with the same key return the same result, including 500 errors.An idempotency key is a unique value generated by the client which the server uses to recognize subsequent retries of the same request. How you create unique keys is up to you, but we suggest using V4 UUIDs, or another random string with enough entropy to avoid collisions. Idempotency keys can be up to 255 characters long.Keys are eligible to be removed from the system automatically after they're at least 24 hours old, and a new request is generated if a key is reused after the original has been pruned. The idempotency layer compares incoming parameters to those of the original request and errors unless they're the same to prevent accidental misuse.Results are only saved if an API endpoint started executing. If incoming parameters failed validation, or the request conflicted with another that was executing concurrently, no idempotent result is saved because no API endpoint began execution. It is safe to retry these requests.All POST requests accept idempotency keys. Sending idempotency keys in GET and DELETE requests has no effect and should be avoided, as these requests are idempotent by definition.\n'''import stripe\nstripe.api_key = \"sk_test_your_key\"\n\ncharge = stripe.Charge.create(\n amount=2000,\n currency=\"usd\",\n description=\"My First Test Charge (created for API docs at https://www.stripe.com/docs/api)\",\n source=\"tok_amex\", # obtained with Stripe.js\n idempotency_key='TR1auKhAiiFBWi5b'\n)"}
{"text": "'''PaginationAll top-level API resources have support for bulk fetches via \"list\" API methods. For instance, you can list charges, list customers, and list invoices. These list API methods share a common structure, taking at least these three parameters: limit, starting_after, and ending_before.Stripe's list API methods utilize cursor-based pagination via the starting_after and ending_before parameters. Both parameters take an existing object ID value (see below) and return objects in reverse chronological order. The ending_before parameter returns objects listed before the named object. The starting_after parameter returns objects listed after the named object. These parameters are mutually exclusive -- only one of starting_after orending_before may be used.Our client libraries offer auto-pagination helpers to easily traverse all pages of a list.\n'''\n'''Response {\n \"object\": \"list\",\n \"url\": \"/v1/customers\",\n \"has_more\": false,\n \"data\": [\n {\n \"id\": \"cus_8TEMHVY5moxIPI\",\n \"object\": \"customer\",\n \"address\": null,\n \"balance\": 0,\n \"created\": 1463528816,\n \"currency\": \"usd\",\n \"default_source\": \"card_18CHs82eZvKYlo2C9BGk8uHq\",\n \"delinquent\": true,\n \"description\": \"Ava Anderson\",\n \"discount\": null,\n \"email\": \"ava.anderson.22@example.com\",\n \"invoice_prefix\": \"F899D8E\",\n \"invoice_settings\": {\n \"custom_fields\": null,\n \"default_payment_method\": null,\n \"footer\": null,\n \"rendering_options\": null\n },\n \"livemode\": false,\n \"metadata\": {},\n \"name\": null,\n \"next_invoice_sequence\": 12,\n \"phone\": null,\n \"preferred_locales\": [],\n \"shipping\": null,\n \"tax_exempt\": \"none\",\n \"test_clock\": null\n },\n {...},\n {...}\n ]\n}'''"}
{"text": "'''Auto-paginationOur libraries support auto-pagination. This feature easily handles fetching large lists of resources without having to manually paginate results and perform subsequent requests.To use the auto-pagination feature in Python, simply issue an initial \"list\" call with the parameters you need, then call auto_paging_iter() on the returned list object to iterate over all objects matching your initial parameters\n'''import stripe\nstripe.api_key = \"sk_test_your_key\"\n\ncustomers = stripe.Customer.list(limit=3)\nfor customer in customers.auto_paging_iter():\n # Do something with customer"}
{"code": "'use strict';\n\nvar clear = require('es5-ext/array/#/clear')\n , eIndexOf = require('es5-ext/array/#/e-index-of')\n , setPrototypeOf = require('es5-ext/object/set-prototype-of')\n , callable = require('es5-ext/object/valid-callable')\n , d = require('d')\n , ee = require('event-emitter')\n , Symbol = require('es6-symbol')\n , iterator = require('es6-iterator/valid-iterable')\n , forOf = require('es6-iterator/for-of')\n , Iterator = require('./lib/iterator')\n , isNative = require('./is-native-implemented')\n\n , call = Function.prototype.call, defineProperty = Object.defineProperty\n , SetPoly, getValues;\n\nmodule.exports = SetPoly = function (/*iterable*/) {\n\tvar iterable = arguments[0];\n\tif (!(this instanceof SetPoly)) return new SetPoly(iterable);\n\tif (this.__setData__ !== undefined) {\n\t\tthrow new TypeError(this + \" cannot be reinitialized\");\n\t}\n\tif (iterable != null) iterator(iterable);\n\tdefineProperty(this, '__setData__', d('c', []));\n\tif (!iterable) return;\n\tforOf(iterable, function (value) {\n\t\tif (eIndexOf.call(this, value) !== -1) return;\n\t\tthis.push(value);\n\t}, this.__setData__);\n};\n\nif (isNative) {\n\tif (setPrototypeOf) setPrototypeOf(SetPoly, Set);\n\tSetPoly.prototype = Object.create(Set.prototype, {\n\t\tconstructor: d(SetPoly)\n\t});\n}\n\nee(Object.defineProperties(SetPoly.prototype, {\n\tadd: d(function (value) {\n\t\tif (this.has(value)) return this;\n\t\tthis.emit('_add', this.__setData__.push(value) - 1, value);\n\t\treturn this;\n\t}),\n\tclear: d(function () {\n\t\tif (!this.__setData__.length) return;\n\t\tclear.call(this.__setData__);\n\t\tthis.emit('_clear');\n\t}),\n\tdelete: d(function (value) {\n\t\tvar index = eIndexOf.call(this.__setData__, value);\n\t\tif (index === -1) return false;\n\t\tthis.__setData__.splice(index, 1);\n\t\tthis.emit('_delete', index, value);\n\t\treturn true;\n\t}),\n\tentries: d(function () { return new Iterator(this, 'key+value'); }),\n\tforEach: d(function (cb/*, thisArg*/) {\n\t\tvar thisArg = arguments[1], iterator, result, value;\n\t\tcallable(cb);\n\t\titerator = this.values();\n\t\tresult = iterator._next();\n\t\twhile (result !== undefined) {\n\t\t\tvalue = iterator._resolve(result);\n\t\t\tcall.call(cb, thisArg, value, value, this);\n\t\t\tresult = iterator._next();\n\t\t}\n\t}),\n\thas: d(function (value) {\n\t\treturn (eIndexOf.call(this.__setData__, value) !== -1);\n\t}),\n\tkeys: d(getValues = function () { return this.values(); }),\n\tsize: d.gs(function () { return this.__setData__.length; }),\n\tvalues: d(function () { return new Iterator(this); }),\n\ttoString: d(function () { return '[object Set]'; })\n}));\ndefineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));\ndefineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));\n", "repo_name": "Socratacom/socrata-europe", "path": "wp-content/themes/sage/node_modules/asset-builder/node_modules/main-bower-files/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/es6-set/polyfill.js", "language": "JavaScript", "license": "gpl-2.0", "size": 2730}
{"code": "'use strict';\n\nconst TYPE = Symbol.for('type');\n\nclass Data {\n\n constructor(options) {\n // File details\n this.filepath = options.filepath;\n\n // Type\n this[TYPE] = 'data';\n\n // Data\n Object.assign(this, options.data);\n }\n}\n\nmodule.exports = Data;\n", "repo_name": "mshick/velvet", "path": "core/classes/data.js", "language": "JavaScript", "license": "isc", "size": 266}
{"code": "package sodium\n\n// #cgo pkg-config: libsodium\n// #include <stdlib.h>\n// #include <sodium.h>\nimport \"C\"\n\nfunc RuntimeHasNeon() bool {\n\treturn C.sodium_runtime_has_neon() != 0\n}\n\nfunc RuntimeHasSse2() bool {\n\treturn C.sodium_runtime_has_sse2() != 0\n}\n\nfunc RuntimeHasSse3() bool {\n\treturn C.sodium_runtime_has_sse3() != 0\n}\n", "repo_name": "GoKillers/libsodium-go", "path": "sodium/runtime.go", "language": "GO", "license": "isc", "size": 322}
{"code": "<?php\n\ninterface Container {\n /**\n * Checks if a $x exists.\n *\n * @param unknown $x\n *\n * @return boolean\n */\n function contains($x);\n}", "repo_name": "guide42/php-immutable", "path": "src/base.php", "language": "PHP", "license": "isc", "size": 165}
{"code": "angular.module('appTesting').service(\"LoginLocalStorage\", function () {\n \"use strict\";\n\n var STORE_NAME = \"login\";\n\n var setUser = function setUser(user) {\n localStorage.setItem(STORE_NAME, JSON.stringify(user));\n }\n\n var getUser = function getUser() {\n var storedTasks = localStorage.getItem(STORE_NAME);\n if (storedTasks) {\n return JSON.parse(storedTasks);\n }\n return {};\n }\n\n return {\n setUser: setUser,\n getUser: getUser\n }\n});", "repo_name": "pikachumetal/cursoangular05", "path": "app/loginModule/services/localstorage.js", "language": "JavaScript", "license": "isc", "size": 515}
{"code": "/* eslint-disable no-console */\nconst buildData = require('./build_data');\nconst buildSrc = require('./build_src');\nconst buildCSS = require('./build_css');\n\nlet _currBuild = null;\n\n// if called directly, do the thing.\nbuildAll();\n\n\nfunction buildAll() {\n if (_currBuild) return _currBuild;\n\n return _currBuild =\n Promise.resolve()\n .then(() => buildCSS())\n .then(() => buildData())\n .then(() => buildSrc())\n .then(() => _currBuild = null)\n .catch((err) => {\n console.error(err);\n _currBuild = null;\n process.exit(1);\n });\n}\n\nmodule.exports = buildAll;\n", "repo_name": "kartta-labs/iD", "path": "build.js", "language": "JavaScript", "license": "isc", "size": 591}
{"code": "function LetterProps(o, sw, sc, fc, m, p) {\r\n this.o = o;\r\n this.sw = sw;\r\n this.sc = sc;\r\n this.fc = fc;\r\n this.m = m;\r\n this.p = p;\r\n this._mdf = {\r\n o: true,\r\n sw: !!sw,\r\n sc: !!sc,\r\n fc: !!fc,\r\n m: true,\r\n p: true,\r\n };\r\n}\r\n\r\nLetterProps.prototype.update = function (o, sw, sc, fc, m, p) {\r\n this._mdf.o = false;\r\n this._mdf.sw = false;\r\n this._mdf.sc = false;\r\n this._mdf.fc = false;\r\n this._mdf.m = false;\r\n this._mdf.p = false;\r\n var updated = false;\r\n\r\n if (this.o !== o) {\r\n this.o = o;\r\n this._mdf.o = true;\r\n updated = true;\r\n }\r\n if (this.sw !== sw) {\r\n this.sw = sw;\r\n this._mdf.sw = true;\r\n updated = true;\r\n }\r\n if (this.sc !== sc) {\r\n this.sc = sc;\r\n this._mdf.sc = true;\r\n updated = true;\r\n }\r\n if (this.fc !== fc) {\r\n this.fc = fc;\r\n this._mdf.fc = true;\r\n updated = true;\r\n }\r\n if (this.m !== m) {\r\n this.m = m;\r\n this._mdf.m = true;\r\n updated = true;\r\n }\r\n if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {\r\n this.p = p;\r\n this._mdf.p = true;\r\n updated = true;\r\n }\r\n return updated;\r\n};\r\n", "repo_name": "damienmortini/dlib", "path": "node_modules/lottie-web/player/js/utils/text/LetterProps.js", "language": "JavaScript", "license": "isc", "size": 1212}
{"code": "// The following are instance methods and variables\nvar Note = Class.create({\n initialize: function(id, is_new, raw_body) {\n if (Note.debug) {\n console.debug(\"Note#initialize (id=%d)\", id)\n }\n\n this.id = id\n this.is_new = is_new\n this.document_observers = [];\n\n // Cache the elements\n this.elements = {\n box: $('note-box-' + this.id),\n corner: $('note-corner-' + this.id),\n body: $('note-body-' + this.id),\n image: $('image')\n }\n\n // Cache the dimensions\n this.fullsize = {\n left: this.elements.box.offsetLeft,\n top: this.elements.box.offsetTop,\n width: this.elements.box.clientWidth,\n height: this.elements.box.clientHeight\n }\n\n // Store the original values (in case the user clicks Cancel)\n this.old = {\n raw_body: raw_body,\n formatted_body: this.elements.body.innerHTML\n }\n for (p in this.fullsize) {\n this.old[p] = this.fullsize[p]\n }\n\n // Make the note translucent\n if (is_new) {\n this.elements.box.setOpacity(0.2)\n } else {\n this.elements.box.setOpacity(0.5)\n }\n\n if (is_new && raw_body == '') {\n this.bodyfit = true\n this.elements.body.style.height = \"100px\"\n }\n\n // Attach the event listeners\n this.elements.box.observe(\"mousedown\", this.dragStart.bindAsEventListener(this))\n this.elements.box.observe(\"mouseout\", this.bodyHideTimer.bindAsEventListener(this))\n this.elements.box.observe(\"mouseover\", this.bodyShow.bindAsEventListener(this))\n this.elements.corner.observe(\"mousedown\", this.resizeStart.bindAsEventListener(this))\n this.elements.body.observe(\"mouseover\", this.bodyShow.bindAsEventListener(this))\n this.elements.body.observe(\"mouseout\", this.bodyHideTimer.bindAsEventListener(this))\n this.elements.body.observe(\"click\", this.showEditBox.bindAsEventListener(this))\n\n this.adjustScale()\n },\n\n // Returns the raw text value of this note\n textValue: function() {\n if (Note.debug) {\n console.debug(\"Note#textValue (id=%d)\", this.id)\n }\n\n return this.old.raw_body.strip()\n },\n\n // Removes the edit box\n hideEditBox: function(e) {\n if (Note.debug) {\n console.debug(\"Note#hideEditBox (id=%d)\", this.id)\n }\n\n var editBox = $('edit-box')\n\n if (editBox != null) {\n var boxid = editBox.noteid\n\n $(\"edit-box\").stopObserving()\n $(\"note-save-\" + boxid).stopObserving()\n $(\"note-cancel-\" + boxid).stopObserving()\n $(\"note-remove-\" + boxid).stopObserving()\n $(\"note-history-\" + boxid).stopObserving()\n $(\"edit-box\").remove()\n }\n },\n\n // Shows the edit box\n showEditBox: function(e) {\n if (Note.debug) {\n console.debug(\"Note#showEditBox (id=%d)\", this.id)\n }\n\n this.hideEditBox(e)\n\n var insertionPosition = Note.getInsertionPosition()\n var top = insertionPosition[0]\n var left = insertionPosition[1]\n var html = \"\"\n\n html += '<div id=\"edit-box\" style=\"top: '+top+'px; left: '+left+'px; position: absolute; visibility: visible; z-index: 100; background: white; border: 1px solid black; padding: 12px;\">'\n html += '<form onsubmit=\"return false;\" style=\"padding: 0; margin: 0;\">'\n html += '<textarea rows=\"7\" id=\"edit-box-text\" style=\"width: 350px; margin: 2px 2px 12px 2px;\">' + this.textValue() + '</textarea>'\n html += '<input type=\"submit\" value=\"Save\" name=\"save\" id=\"note-save-' + this.id + '\">'\n html += '<input type=\"submit\" value=\"Cancel\" name=\"cancel\" id=\"note-cancel-' + this.id + '\">'\n html += '<input type=\"submit\" value=\"Remove\" name=\"remove\" id=\"note-remove-' + this.id + '\">'\n html += '<input type=\"submit\" value=\"History\" name=\"history\" id=\"note-history-' + this.id + '\">'\n html += '</form>'\n html += '</div>'\n\n $(\"note-container\").insert({bottom: html})\n $('edit-box').noteid = this.id\n $(\"edit-box\").observe(\"mousedown\", this.editDragStart.bindAsEventListener(this))\n $(\"note-save-\" + this.id).observe(\"click\", this.save.bindAsEventListener(this))\n $(\"note-cancel-\" + this.id).observe(\"click\", this.cancel.bindAsEventListener(this))\n $(\"note-remove-\" + this.id).observe(\"click\", this.remove.bindAsEventListener(this))\n $(\"note-history-\" + this.id).observe(\"click\", this.history.bindAsEventListener(this))\n $(\"edit-box-text\").focus()\n },\n\n // Shows the body text for the note\n bodyShow: function(e) {\n if (Note.debug) {\n console.debug(\"Note#bodyShow (id=%d)\", this.id)\n }\n\n if (this.dragging) {\n return\n }\n\n if (this.hideTimer) {\n clearTimeout(this.hideTimer)\n this.hideTimer = null\n }\n\n if (Note.noteShowingBody == this) {\n return\n }\n\n if (Note.noteShowingBody) {\n Note.noteShowingBody.bodyHide()\n }\n\n Note.noteShowingBody = this\n\n if (Note.zindex >= 9) {\n /* don't use more than 10 layers (+1 for the body, which will always be above all notes) */\n Note.zindex = 0\n for (var i=0; i< Note.all.length; ++i) {\n Note.all[i].elements.box.style.zIndex = 0\n }\n }\n\n this.elements.box.style.zIndex = ++Note.zindex\n this.elements.body.style.zIndex = 10\n this.elements.body.style.top = 0 + \"px\"\n this.elements.body.style.left = 0 + \"px\"\n\n var dw = document.documentElement.scrollWidth\n this.elements.body.style.visibility = \"hidden\"\n this.elements.body.style.display = \"block\"\n if (!this.bodyfit) {\n this.elements.body.style.height = \"auto\"\n this.elements.body.style.minWidth = \"140px\"\n var w = null, h = null, lo = null, hi = null, x = null, last = null\n w = this.elements.body.offsetWidth\n h = this.elements.body.offsetHeight\n if (w/h < 1.6180339887) {\n /* for tall notes (lots of text), find more pleasant proportions */\n lo = 140, hi = 400\n do {\n last = w\n x = (lo+hi)/2\n this.elements.body.style.minWidth = x + \"px\"\n w = this.elements.body.offsetWidth\n h = this.elements.body.offsetHeight\n if (w/h < 1.6180339887) lo = x\n else hi = x\n } while ((lo < hi) && (w > last))\n } else if (this.elements.body.scrollWidth <= this.elements.body.clientWidth) {\n /* for short notes (often a single line), make the box no wider than necessary */\n // scroll test necessary for Firefox\n lo = 20, hi = w\n\n do {\n x = (lo+hi)/2\n this.elements.body.style.minWidth = x + \"px\"\n if (this.elements.body.offsetHeight > h) lo = x\n else hi = x\n } while ((hi - lo) > 4)\n if (this.elements.body.offsetHeight > h)\n this.elements.body.style.minWidth = hi + \"px\"\n }\n\n if (Prototype.Browser.IE) {\n // IE7 adds scrollbars if the box is too small, obscuring the text\n if (this.elements.body.offsetHeight < 35) {\n this.elements.body.style.minHeight = \"35px\"\n }\n\n if (this.elements.body.offsetWidth < 47) {\n this.elements.body.style.minWidth = \"47px\"\n }\n }\n this.bodyfit = true\n }\n this.elements.body.style.top = (this.elements.box.offsetTop + this.elements.box.clientHeight + 5) + \"px\"\n // keep the box within the document's width\n var l = 0, e = this.elements.box\n do { l += e.offsetLeft } while (e = e.offsetParent)\n l += this.elements.body.offsetWidth + 10 - dw\n if (l > 0)\n this.elements.body.style.left = this.elements.box.offsetLeft - l + \"px\"\n else\n this.elements.body.style.left = this.elements.box.offsetLeft + \"px\"\n this.elements.body.style.visibility = \"visible\"\n },\n\n // Creates a timer that will hide the body text for the note\n bodyHideTimer: function(e) {\n if (Note.debug) {\n console.debug(\"Note#bodyHideTimer (id=%d)\", this.id)\n }\n this.hideTimer = setTimeout(this.bodyHide.bindAsEventListener(this), 250)\n },\n\n // Hides the body text for the note\n bodyHide: function(e) {\n if (Note.debug) {\n console.debug(\"Note#bodyHide (id=%d)\", this.id)\n }\n\n this.elements.body.hide()\n if (Note.noteShowingBody == this) {\n Note.noteShowingBody = null\n }\n },\n\n addDocumentObserver: function(name, func)\n {\n document.observe(name, func);\n this.document_observers.push([name, func]);\n },\n\n clearDocumentObservers: function(name, handler)\n {\n for(var i = 0; i < this.document_observers.length; ++i)\n {\n var observer = this.document_observers[i];\n document.stopObserving(observer[0], observer[1]);\n }\n\n this.document_observers = [];\n },\n\n // Start dragging the note\n dragStart: function(e) {\n if (Note.debug) {\n console.debug(\"Note#dragStart (id=%d)\", this.id)\n }\n\n this.addDocumentObserver(\"mousemove\", this.drag.bindAsEventListener(this))\n this.addDocumentObserver(\"mouseup\", this.dragStop.bindAsEventListener(this))\n this.addDocumentObserver(\"selectstart\", function() {return false})\n\n this.cursorStartX = e.pointerX()\n this.cursorStartY = e.pointerY()\n this.boxStartX = this.elements.box.offsetLeft\n this.boxStartY = this.elements.box.offsetTop\n this.boundsX = new ClipRange(5, this.elements.image.clientWidth - this.elements.box.clientWidth - 5)\n this.boundsY = new ClipRange(5, this.elements.image.clientHeight - this.elements.box.clientHeight - 5)\n this.dragging = true\n this.bodyHide()\n },\n\n // Stop dragging the note\n dragStop: function(e) {\n if (Note.debug) {\n console.debug(\"Note#dragStop (id=%d)\", this.id)\n }\n\n this.clearDocumentObservers()\n\n this.cursorStartX = null\n this.cursorStartY = null\n this.boxStartX = null\n this.boxStartY = null\n this.boundsX = null\n this.boundsY = null\n this.dragging = false\n\n this.bodyShow()\n },\n\n ratio: function() {\n return this.elements.image.width / this.elements.image.getAttribute(\"large_width\")\n // var ratio = this.elements.image.width / this.elements.image.getAttribute(\"large_width\")\n // if (this.elements.image.scale_factor != null)\n // ratio *= this.elements.image.scale_factor;\n // return ratio\n },\n\n // Scale the notes for when the image gets resized\n adjustScale: function() {\n if (Note.debug) {\n console.debug(\"Note#adjustScale (id=%d)\", this.id)\n }\n\n var ratio = this.ratio()\n for (p in this.fullsize) {\n this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'\n }\n },\n\n // Update the note's position as it gets dragged\n drag: function(e) {\n var left = this.boxStartX + e.pointerX() - this.cursorStartX\n var top = this.boxStartY + e.pointerY() - this.cursorStartY\n left = this.boundsX.clip(left)\n top = this.boundsY.clip(top)\n\n this.elements.box.style.left = left + 'px'\n this.elements.box.style.top = top + 'px'\n var ratio = this.ratio()\n this.fullsize.left = left / ratio\n this.fullsize.top = top / ratio\n\n e.stop()\n },\n\n // Start dragging the edit box\n editDragStart: function(e) {\n if (Note.debug) {\n console.debug(\"Note#editDragStart (id=%d)\", this.id)\n }\n\n var node = e.element().nodeName\n if (node != 'FORM' && node != 'DIV') {\n return\n }\n\n this.addDocumentObserver(\"mousemove\", this.editDrag.bindAsEventListener(this))\n this.addDocumentObserver(\"mouseup\", this.editDragStop.bindAsEventListener(this))\n this.addDocumentObserver(\"selectstart\", function() {return false})\n\n this.elements.editBox = $('edit-box');\n this.cursorStartX = e.pointerX()\n this.cursorStartY = e.pointerY()\n this.editStartX = this.elements.editBox.offsetLeft\n this.editStartY = this.elements.editBox.offsetTop\n this.dragging = true\n },\n\n // Stop dragging the edit box\n editDragStop: function(e) {\n if (Note.debug) {\n console.debug(\"Note#editDragStop (id=%d)\", this.id)\n }\n this.clearDocumentObservers()\n\n this.cursorStartX = null\n this.cursorStartY = null\n this.editStartX = null\n this.editStartY = null\n this.dragging = false\n },\n\n // Update the edit box's position as it gets dragged\n editDrag: function(e) {\n var left = this.editStartX + e.pointerX() - this.cursorStartX\n var top = this.editStartY + e.pointerY() - this.cursorStartY\n\n this.elements.editBox.style.left = left + 'px'\n this.elements.editBox.style.top = top + 'px'\n\n e.stop()\n },\n\n // Start resizing the note\n resizeStart: function(e) {\n if (Note.debug) {\n console.debug(\"Note#resizeStart (id=%d)\", this.id)\n }\n\n this.cursorStartX = e.pointerX()\n this.cursorStartY = e.pointerY()\n this.boxStartWidth = this.elements.box.clientWidth\n this.boxStartHeight = this.elements.box.clientHeight\n this.boxStartX = this.elements.box.offsetLeft\n this.boxStartY = this.elements.box.offsetTop\n this.boundsX = new ClipRange(10, this.elements.image.clientWidth - this.boxStartX - 5)\n this.boundsY = new ClipRange(10, this.elements.image.clientHeight - this.boxStartY - 5)\n this.dragging = true\n\n this.clearDocumentObservers()\n this.addDocumentObserver(\"mousemove\", this.resize.bindAsEventListener(this))\n this.addDocumentObserver(\"mouseup\", this.resizeStop.bindAsEventListener(this))\n\n e.stop()\n this.bodyHide()\n },\n\n // Stop resizing teh note\n resizeStop: function(e) {\n if (Note.debug) {\n console.debug(\"Note#resizeStop (id=%d)\", this.id)\n }\n\n this.clearDocumentObservers()\n\n this.boxCursorStartX = null\n this.boxCursorStartY = null\n this.boxStartWidth = null\n this.boxStartHeight = null\n this.boxStartX = null\n this.boxStartY = null\n this.boundsX = null\n this.boundsY = null\n this.dragging = false\n\n e.stop()\n },\n\n // Update the note's dimensions as it gets resized\n resize: function(e) {\n var width = this.boxStartWidth + e.pointerX() - this.cursorStartX\n var height = this.boxStartHeight + e.pointerY() - this.cursorStartY\n width = this.boundsX.clip(width)\n height = this.boundsY.clip(height)\n\n this.elements.box.style.width = width + \"px\"\n this.elements.box.style.height = height + \"px\"\n var ratio = this.ratio()\n this.fullsize.width = width / ratio\n this.fullsize.height = height / ratio\n\n e.stop()\n },\n\n // Save the note to the database\n save: function(e) {\n if (Note.debug) {\n console.debug(\"Note#save (id=%d)\", this.id)\n }\n\n var note = this\n for (p in this.fullsize) {\n this.old[p] = this.fullsize[p]\n }\n this.old.raw_body = $('edit-box-text').value\n this.old.formatted_body = this.textValue()\n // FIXME: this is not quite how the note will look (filtered elems, <tn>...). the user won't input a <script> that only damages him, but it might be nice to \"preview\" the <tn> here\n this.elements.body.update(this.textValue())\n\n this.hideEditBox(e)\n this.bodyHide()\n this.bodyfit = false\n\n var params = {\n \"id\": this.id,\n \"note[x]\": this.old.left,\n \"note[y]\": this.old.top,\n \"note[width]\": this.old.width,\n \"note[height]\": this.old.height,\n \"note[body]\": this.old.raw_body\n }\n\n if (this.is_new) {\n params[\"note[post_id]\"] = Note.post_id\n }\n\n notice(\"Saving note...\")\n\n new Ajax.Request('/note/update.json', {\n parameters: params,\n\n onComplete: function(resp) {\n var resp = resp.responseJSON\n\n if (resp.success) {\n notice(\"Note saved\")\n var note = Note.find(resp.old_id)\n\n if (resp.old_id < 0) {\n note.is_new = false\n note.id = resp.new_id\n note.elements.box.id = 'note-box-' + note.id\n note.elements.body.id = 'note-body-' + note.id\n note.elements.corner.id = 'note-corner-' + note.id\n }\n note.elements.body.innerHTML = resp.formatted_body\n note.elements.box.setOpacity(0.5)\n note.elements.box.removeClassName('unsaved')\n } else {\n notice(\"Error: \" + resp.reason)\n note.elements.box.addClassName('unsaved')\n }\n }\n })\n\n e.stop()\n },\n\n // Revert the note to the last saved state\n cancel: function(e) {\n if (Note.debug) {\n console.debug(\"Note#cancel (id=%d)\", this.id)\n }\n\n this.hideEditBox(e)\n this.bodyHide()\n\n var ratio = this.ratio()\n for (p in this.fullsize) {\n this.fullsize[p] = this.old[p]\n this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'\n }\n this.elements.body.innerHTML = this.old.formatted_body\n\n e.stop()\n },\n\n // Remove all references to the note from the page\n removeCleanup: function() {\n if (Note.debug) {\n console.debug(\"Note#removeCleanup (id=%d)\", this.id)\n }\n\n this.elements.box.remove()\n this.elements.body.remove()\n\n var allTemp = []\n for (i=0; i<Note.all.length; ++i) {\n if (Note.all[i].id != this.id) {\n allTemp.push(Note.all[i])\n }\n }\n\n Note.all = allTemp\n Note.updateNoteCount()\n },\n\n // Removes a note from the database\n remove: function(e) {\n if (Note.debug) {\n console.debug(\"Note#remove (id=%d)\", this.id)\n }\n\n this.hideEditBox(e)\n this.bodyHide()\n this_note = this\n\n if (this.is_new) {\n this.removeCleanup()\n notice(\"Note removed\")\n\n } else {\n notice(\"Removing note...\")\n\n new Ajax.Request('/note/update.json', {\n parameters: {\n \"id\": this.id,\n \"note[is_active]\": \"0\"\n },\n onComplete: function(resp) {\n var resp = resp.responseJSON\n\n if (resp.success) {\n notice(\"Note removed\")\n this_note.removeCleanup()\n } else {\n notice(\"Error: \" + resp.reason)\n }\n }\n })\n }\n\n e.stop()\n },\n\n // Redirect to the note's history\n history: function(e) {\n if (Note.debug) {\n console.debug(\"Note#history (id=%d)\", this.id)\n }\n\n this.hideEditBox(e)\n\n if (this.is_new) {\n notice(\"This note has no history\")\n } else {\n location.href = '/history?search=notes:' + this.id\n }\n\n e.stop()\n }\n})\n\n// The following are class methods and variables\nObject.extend(Note, {\n zindex: 0,\n counter: -1,\n all: [],\n display: true,\n debug: false,\n\n // Show all notes\n show: function() {\n if (Note.debug) {\n console.debug(\"Note.show\")\n }\n\n $(\"note-container\").show()\n },\n\n // Hide all notes\n hide: function() {\n if (Note.debug) {\n console.debug(\"Note.hide\")\n }\n\n $(\"note-container\").hide()\n },\n\n // Find a note instance based on the id number\n find: function(id) {\n if (Note.debug) {\n console.debug(\"Note.find\")\n }\n\n for (var i=0; i<Note.all.size(); ++i) {\n if (Note.all[i].id == id) {\n return Note.all[i]\n }\n }\n\n return null\n },\n\n // Toggle the display of all notes\n toggle: function() {\n if (Note.debug) {\n console.debug(\"Note.toggle\")\n }\n\n if (Note.display) {\n Note.hide()\n Note.display = false\n } else {\n Note.show()\n Note.display = true\n }\n },\n\n // Update the text displaying the number of notes a post has\n updateNoteCount: function() {\n if (Note.debug) {\n console.debug(\"Note.updateNoteCount\")\n }\n\n if (Note.all.length > 0) {\n var label = \"\"\n\n if (Note.all.length == 1)\n label = \"note\"\n else\n label = \"notes\"\n\n $('note-count').innerHTML = \"This post has <a href=\\\"/note/history?post_id=\" + Note.post_id + \"\\\">\" + Note.all.length + \" \" + label + \"</a>\"\n } else {\n $('note-count').innerHTML = \"\"\n }\n },\n\n // Create a new note\n create: function() {\n if (Note.debug) {\n console.debug(\"Note.create\")\n }\n\n\t\tNote.show()\n\n var insertion_position = Note.getInsertionPosition()\n var top = insertion_position[0]\n var left = insertion_position[1]\n var html = ''\n html += '<div class=\"note-box unsaved\" style=\"width: 150px; height: 150px; '\n html += 'top: ' + top + 'px; '\n html += 'left: ' + left + 'px;\" '\n html += 'id=\"note-box-' + Note.counter + '\">'\n html += '<div class=\"note-corner\" id=\"note-corner-' + Note.counter + '\"></div>'\n html += '</div>'\n html += '<div class=\"note-body\" title=\"Click to edit\" id=\"note-body-' + Note.counter + '\"></div>'\n $(\"note-container\").insert({bottom: html})\n var note = new Note(Note.counter, true, \"\")\n Note.all.push(note)\n Note.counter -= 1\n },\n\n // Find a suitable position to insert new notes\n getInsertionPosition: function() {\n if (Note.debug) {\n console.debug(\"Note.getInsertionPosition\")\n }\n\n // We want to show the edit box somewhere on the screen, but not outside the image.\n var scroll_x = $(\"image\").cumulativeScrollOffset()[0]\n var scroll_y = $(\"image\").cumulativeScrollOffset()[1]\n var image_left = $(\"image\").positionedOffset()[0]\n var image_top = $(\"image\").positionedOffset()[1]\n var image_right = image_left + $(\"image\").width\n var image_bottom = image_top + $(\"image\").height\n var left = 0\n var top = 0\n\n if (scroll_x > image_left) {\n left = scroll_x\n } else {\n left = image_left\n }\n\n if (scroll_y > image_top) {\n top = scroll_y\n } else {\n top = image_top + 20\n }\n\n if (top > image_bottom) {\n top = image_top + 20\n }\n\n return [top, left]\n }\n})\n", "repo_name": "rhaphazard/moebooru", "path": "lib/assets/javascripts/moe-legacy/notes.js", "language": "JavaScript", "license": "isc", "size": 21067}
{"code": "// Copyright (c) 2021 The Decred developers\n// Use of this source code is governed by an ISC\n// license that can be found in the LICENSE file.\n\npackage indexers\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/decred/dcrd/blockchain/v4/internal/progresslog\"\n\t\"github.com/decred/dcrd/database/v3\"\n\t\"github.com/decred/dcrd/dcrutil/v4\"\n)\n\n// IndexNtfnType represents an index notification type.\ntype IndexNtfnType int\n\nconst (\n\t// ConnectNtfn indicates the index notification signals a block\n\t// connected to the main chain.\n\tConnectNtfn IndexNtfnType = iota\n\n\t// DisconnectNtfn indicates the index notification signals a block\n\t// disconnected from the main chain.\n\tDisconnectNtfn\n)\n\nvar (\n\t// bufferSize represents the index notification buffer size.\n\tbufferSize = 128\n\n\t// noPrereqs indicates no index prerequisites.\n\tnoPrereqs = \"none\"\n)\n\n// IndexNtfn represents an index notification detailing a block connection\n// or disconnection.\ntype IndexNtfn struct {\n\tNtfnType IndexNtfnType\n\tBlock *dcrutil.Block\n\tParent *dcrutil.Block\n\tPrevScripts PrevScripter\n\tIsTreasuryEnabled bool\n\tDone chan bool\n}\n\n// IndexSubscription represents a subscription for index updates.\ntype IndexSubscription struct {\n\tid string\n\tidx Indexer\n\tsubscriber *IndexSubscriber\n\tmtx sync.Mutex\n\n\t// prerequisite defines the notification processing hierarchy for this\n\t// subscription. It is expected that the subscriber associated with the\n\t// prerequisite provided processes notifications before they are\n\t// delivered by this subscription to its subscriber. An empty string\n\t// indicates the subscription has no prerequisite.\n\tprerequisite string\n\n\t// dependent defines the index subscription that requires the subscriber\n\t// associated with this subscription to have processed incoming\n\t// notifications before it does. A nil dependency indicates the subscription\n\t// has no dependencies.\n\tdependent *IndexSubscription\n}\n\n// newIndexSubscription initializes a new index subscription.\nfunc newIndexSubscription(subber *IndexSubscriber, indexer Indexer, prereq string) *IndexSubscription {\n\treturn &IndexSubscription{\n\t\tid: indexer.Name(),\n\t\tidx: indexer,\n\t\tprerequisite: prereq,\n\t\tsubscriber: subber,\n\t}\n}\n\n// stop prevents any future index updates from being delivered and\n// unsubscribes the associated subscription.\nfunc (s *IndexSubscription) stop() error {\n\n\t// If the subscription has a prerequisite, find it and remove the\n\t// subscription as a dependency.\n\tif s.prerequisite != noPrereqs {\n\t\ts.mtx.Lock()\n\t\tprereq, ok := s.subscriber.subscriptions[s.prerequisite]\n\t\ts.mtx.Unlock()\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"no subscription found with id %s\", s.prerequisite)\n\t\t}\n\n\t\tprereq.mtx.Lock()\n\t\tprereq.dependent = nil\n\t\tprereq.mtx.Unlock()\n\n\t\treturn nil\n\t}\n\n\t// If the subscription has a dependent, stop it as well.\n\tif s.dependent != nil {\n\t\terr := s.dependent.stop()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If the subscription is independent, remove it from the\n\t// index subscriber's subscriptions.\n\ts.mtx.Lock()\n\tdelete(s.subscriber.subscriptions, s.id)\n\ts.mtx.Unlock()\n\n\treturn nil\n}\n\n// IndexSubscriber subscribes clients for index updates.\ntype IndexSubscriber struct {\n\tsubscribers uint32 // update atomically.\n\n\tc chan IndexNtfn\n\tsubscriptions map[string]*IndexSubscription\n\tmtx sync.Mutex\n\tctx context.Context\n\tcancel context.CancelFunc\n\tquit chan struct{}\n}\n\n// NewIndexSubscriber creates a new index subscriber. It also starts the\n// handler for incoming index update subscriptions.\nfunc NewIndexSubscriber(sCtx context.Context) *IndexSubscriber {\n\tctx, cancel := context.WithCancel(sCtx)\n\ts := &IndexSubscriber{\n\t\tc: make(chan IndexNtfn, bufferSize),\n\t\tsubscriptions: make(map[string]*IndexSubscription),\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tquit: make(chan struct{}),\n\t}\n\treturn s\n}\n\n// Subscribe subscribes an index for updates. The returned index subscription\n// has functions to retrieve a channel that produces a stream of index updates\n// and to stop the stream when the caller no longer wishes to receive updates.\nfunc (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexSubscription, error) {\n\tsub := newIndexSubscription(s, index, prerequisite)\n\n\t// If the subscription has a prequisite, find it and set the subscription\n\t// as a dependency.\n\tif prerequisite != noPrereqs {\n\t\ts.mtx.Lock()\n\t\tprereq, ok := s.subscriptions[prerequisite]\n\t\ts.mtx.Unlock()\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"no subscription found with id %s\", prerequisite)\n\t\t}\n\n\t\tprereq.mtx.Lock()\n\t\tdefer prereq.mtx.Unlock()\n\n\t\tif prereq.dependent != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s already has a dependent set: %s\",\n\t\t\t\tprereq.id, prereq.dependent.id)\n\t\t}\n\n\t\tprereq.dependent = sub\n\t\tatomic.AddUint32(&s.subscribers, 1)\n\n\t\treturn sub, nil\n\t}\n\n\t// If the subscription does not have a prerequisite, add it to the index\n\t// subscriber's subscriptions.\n\ts.mtx.Lock()\n\ts.subscriptions[sub.id] = sub\n\ts.mtx.Unlock()\n\n\tatomic.AddUint32(&s.subscribers, 1)\n\n\treturn sub, nil\n}\n\n// Notify relays an index notification to subscribed indexes for processing.\nfunc (s *IndexSubscriber) Notify(ntfn *IndexNtfn) {\n\tsubscribers := atomic.LoadUint32(&s.subscribers)\n\n\t// Only relay notifications when there are subscribed indexes\n\t// to be notified.\n\tif subscribers > 0 {\n\t\tselect {\n\t\tcase <-s.quit:\n\t\tcase s.c <- *ntfn:\n\t\t}\n\t}\n}\n\n// findLowestIndexTipHeight determines the lowest index tip height among\n// subscribed indexes and their dependencies.\nfunc (s *IndexSubscriber) findLowestIndexTipHeight(queryer ChainQueryer) (int64, int64, error) {\n\t// Find the lowest tip height to catch up among subscribed indexes.\n\tbestHeight, _ := queryer.Best()\n\tlowestHeight := bestHeight\n\tfor _, sub := range s.subscriptions {\n\t\ttipHeight, tipHash, err := sub.idx.Tip()\n\t\tif err != nil {\n\t\t\treturn 0, bestHeight, err\n\t\t}\n\n\t\t// Ensure the index tip is on the main chain.\n\t\tif !queryer.MainChainHasBlock(tipHash) {\n\t\t\treturn 0, bestHeight, fmt.Errorf(\"%s: index tip (%s) is not on the \"+\n\t\t\t\t\"main chain\", sub.idx.Name(), tipHash)\n\t\t}\n\n\t\tif tipHeight < lowestHeight {\n\t\t\tlowestHeight = tipHeight\n\t\t}\n\n\t\t// Update the lowest tip height if a dependent has a lower tip height.\n\t\tdependent := sub.dependent\n\t\tfor dependent != nil {\n\t\t\ttipHeight, _, err := sub.dependent.idx.Tip()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, bestHeight, err\n\t\t\t}\n\n\t\t\tif tipHeight < lowestHeight {\n\t\t\t\tlowestHeight = tipHeight\n\t\t\t}\n\n\t\t\tdependent = dependent.dependent\n\t\t}\n\t}\n\n\treturn lowestHeight, bestHeight, nil\n}\n\n// CatchUp syncs all subscribed indexes to the the main chain by connecting\n// blocks from after the lowest index tip to the current main chain tip.\n//\n// This should be called after all indexes have subscribed for updates.\nfunc (s *IndexSubscriber) CatchUp(ctx context.Context, db database.DB, queryer ChainQueryer) error {\n\tlowestHeight, bestHeight, err := s.findLowestIndexTipHeight(queryer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Nothing to do if all indexes are synced.\n\tif bestHeight == lowestHeight {\n\t\treturn nil\n\t}\n\n\t// Create a progress logger for the indexing process below.\n\tprogressLogger := progresslog.NewBlockProgressLogger(\"Indexed\", log)\n\n\t// tip and need to be caught up, so log the details and loop through\n\t// each block that needs to be indexed.\n\tlog.Infof(\"Catching up from height %d to %d\", lowestHeight,\n\t\tbestHeight)\n\n\tvar cachedParent *dcrutil.Block\n\tfor height := lowestHeight + 1; height <= bestHeight; height++ {\n\t\tif interruptRequested(ctx) {\n\t\t\treturn indexerError(ErrInterruptRequested, interruptMsg)\n\t\t}\n\n\t\thash, err := queryer.BlockHashByHeight(height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Ensure the next tip hash is on the main chain.\n\t\tif !queryer.MainChainHasBlock(hash) {\n\t\t\tmsg := fmt.Sprintf(\"the next block being synced to (%s) \"+\n\t\t\t\t\"at height %d is not on the main chain\", hash, height)\n\t\t\treturn indexerError(ErrBlockNotOnMainChain, msg)\n\t\t}\n\n\t\tvar parent *dcrutil.Block\n\t\tif cachedParent == nil && height > 0 {\n\t\t\tparentHash, err := queryer.BlockHashByHeight(height - 1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tparent, err = queryer.BlockByHash(parentHash)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tparent = cachedParent\n\t\t}\n\n\t\tchild, err := queryer.BlockByHash(hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Construct and send the index notification.\n\t\tvar prevScripts PrevScripter\n\t\terr = db.View(func(dbTx database.Tx) error {\n\t\t\tif interruptRequested(ctx) {\n\t\t\t\treturn indexerError(ErrInterruptRequested, interruptMsg)\n\t\t\t}\n\n\t\t\tprevScripts, err = queryer.PrevScripts(dbTx, child)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tisTreasuryEnabled, err := queryer.IsTreasuryAgendaActive(parent.Hash())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tntfn := &IndexNtfn{\n\t\t\tNtfnType: ConnectNtfn,\n\t\t\tBlock: child,\n\t\t\tParent: parent,\n\t\t\tPrevScripts: prevScripts,\n\t\t\tIsTreasuryEnabled: isTreasuryEnabled,\n\t\t}\n\n\t\t// Relay the index update to subscribed indexes.\n\t\tfor _, sub := range s.subscriptions {\n\t\t\terr := updateIndex(ctx, sub.idx, ntfn)\n\t\t\tif err != nil {\n\t\t\t\ts.cancel()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tcachedParent = child\n\n\t\tprogressLogger.LogBlockHeight(child.MsgBlock(), parent.MsgBlock())\n\t}\n\n\tlog.Infof(\"Caught up to height %d\", bestHeight)\n\n\treturn nil\n}\n\n// Run relays index notifications to subscribed indexes.\n//\n// This should be run as a goroutine.\nfunc (s *IndexSubscriber) Run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase ntfn := <-s.c:\n\t\t\t// Relay the index update to subscribed indexes.\n\t\t\tfor _, sub := range s.subscriptions {\n\t\t\t\terr := updateIndex(ctx, sub.idx, &ntfn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t\ts.cancel()\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ntfn.Done != nil {\n\t\t\t\tclose(ntfn.Done)\n\t\t\t}\n\n\t\tcase <-ctx.Done():\n\t\t\tlog.Infof(\"Index subscriber shutting down\")\n\n\t\t\tclose(s.quit)\n\n\t\t\t// Stop all updates to subscribed indexes and terminate their\n\t\t\t// processes.\n\t\t\tfor _, sub := range s.subscriptions {\n\t\t\t\terr := sub.stop()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"unable to stop index subscription: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ts.cancel()\n\t\t\treturn\n\t\t}\n\t}\n}\n", "repo_name": "decred/dcrd", "path": "blockchain/indexers/indexsubscriber.go", "language": "GO", "license": "isc", "size": 10267}
{"question": "Who is mystery man in Karl Stefanovic selfie?", "article": "Karl Stefanovic (left) and new wife Jasmine Yarbrough (second from right) pose for a selfie with friend Lauryn Rakic and her husband while on holiday in Yamba. Unassuming Grafton businessman Mark Hackett photobombed in the background. Karl Stefanovic (left) and new wife Jasmine Yarbrough (second from right) pose for a selfie with friend Lauryn Rakic and her husband while on holiday in Yamba. Unassuming Grafton businessman Mark Hackett photobombed in the background. Instagram / Facebook MARK Hackett is a well known Clarence Valley identity in his own right, but this week he inadvertently photo-bombed two much more famous newlyweds. The Toast Espresso Grafton owner was minding his own business in a Yamba carpark when TV celebrity Karl Stefanovic and Jasmine Yarbrough posed for a selfie with friend Lauryn Rakic and her husband. Yarbrough posted the cheerful snap on her Instagram profile 'jasyarby', attracting more than 2600 likes and gaining the attention of gossip magazines Woman's Day and New Idea. Yarbrough's post read \"Yamba locals ... and what a place\" with an emoticon of a prawn. The Daily Examiner can confirm the man standing in the background in the top right corner of the image is Mr Hackett. \"I was standing in front of my car outside Brgr Spot chatting to a friend about work and accidentally photo-bombed,\" Mr Hackett said. \"I saw some people in front of us who looked like they were having a good time. But I had no idea who they were.\" A friend recognised Mr Hackett in the Instagram photo and shared it to Facebook with the post \"Mark Hackett is that you celebrity stalking in the background\". Mr Hackett has been in Yamba \"house sitting for some friends\" between trips back and forth to Grafton 62km away to oversee his thriving cafe business. \"The weather's been amazing and I've been going to the beach when I can,\" he said. \"There have been big crowds and last night's fireworks were good.\" The sunny seaside town is growing in popularity as a year-round tourist destination and was the scene on a high profile health scare last week when NRL immortal Andrew Johns collapsed at a cafe. Stefanovic, 44, married 34-year-old Yarbrough at an \"extravagant\" ceremony in Mexico on December 8. They were on their honeymoon at American ski resort Aspen when Stefanovic was sensationally dumped from Channel Nine's Today Show after almost 14 years as the troubled breakfast show's co-host.", "url": "https://www.qt.com.au/news/who-is-mystery-man-in-karl-stefanovic-selfie/3612673/"}
{"question": "Where have all the Christmas beetles gone?", "article": "IF you've been wondering where all the Christmas beetles have gone, you're not alone. Anecdotal evidence suggests Australia's endemic Christmas beetle population is on the decline. Entomologist Dr Chris Reid, from the Australian Museum, attributes the drop in sightings to drier than usual spring weather, especially along the coast of NSW. Here on the Coffs Coast the decline hasn't gone unnoticed. \"I usually can't sit outside with the light on this time of year as there's so many (I'm at Corindi) but I've seen only about two this year, and haven't had to keep the outside light off at all,\" Shantell Acebedo posted on the Advocate's Facebook page. \"Thirty years ago, I'd shake the gum tree in my front yard and it would literally rain Christmas beetles. I haven't seen one in years,\" Merilyn Horton wrote. Trish Welsh agreed: \"Haven't seen any in Coffs this year. In previous summers they were literally 'raining' down.\" Sarah Jones reported seeing: \"Thousands on the way to Ebor the other day but they're definitely on the decline in Coffs from what there was twenty years ago.\" NOT SO COMMON: Denise Grimberg captured the first beetle of the season at north Boambee but says they're \"nothing like they used to be.\" The classic habitat for Christmas beetles is woodland with plenty of trees and rich soil. The larvae develop in soil and remain there as curl grubs, feeding on grass and plant roots, as well as the surface roots of eucalypts. As adults they mainly eat eucalyptus leaves but are known to consume the foliage of introduced species, such as the peppercorn tree. These colourful scarabs are associated with the festive season as their larvae hatches around the end of spring and start of summer. \"When we're seeing (the adults) just before Christmas they're at the stage of laying eggs,\" Dr Reid said. In addition to the drier conditions, habitat loss is another factor believed to be linked to the decline. Some Coffs residents fear the use of pesticides might also have something to do with it. \"When I was a kid we had dozens and dozens around. Now I see one every second year. So sad, all that spraying would have to have some effect,\" Helen Rule-Todd posted. \"None around here any more. And since the introduction of blueberry farms in this neighbourhood, other insects such as cicadas and spiders are now on the decline too. Native animals such as tawny frogmouths and bandicoots have vanished altogether,\" Sally Wilson wrote.", "url": "https://www.northernstar.com.au/news/where-have-all-the-christmas-beetles-gone/3612649/"}
{"question": "Will 2019 be the year we make America native again?", "article": "Trump's presidency represents a clear and present danger to Canada, and his disastrous policies have particularly devastating impacts on sovereign Indigenous nations across Turtle Island. Thank you for reading this story... More people are reading rabble.ca than ever and unlike many news organizations, we have never put up a paywall at rabble weve always believed in making our reporting and analysis free to all. But media isnt free to produce. rabbles total budget is likely less than what big corporate media spend on photocopying (we kid you not!) and we do not have any major foundation, sponsor or angel investor. Our only supporters are people and organizations -- like you. This is why we need your help. If everyone who visits rabble and likes it chipped in a couple of dollars per month, our future would be much more secure and we could do much more: like the things our readers tell us they want to see more of: more staff reporters and more work to complete the upgrade of our website. Were asking if you could make a donation, right now, to set rabble on solid footing. Make a donation.Become a monthly supporter.", "url": "http://rabble.ca/multimedia/2018/12/will-2019-be-year-we-make-america-native-again?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+rabble-news+%28rabble.ca+-+News+for+the+rest+of+us%29"}
{"question": "How are the cast of Mrs Browns Boys related?", "article": "When casting the Brown family, Mrs Browns Boys creator Brendan OCarroll didnt need to look far. In fact, he didnt have to look beyond his own living room. Agnes Brown Brendan OCarroll The titular mammy is the daddy of the family and father to Danny OCarroll who plays Buster, and Fiona OCarroll who plays Maria. His sister Eilish plays next door neighbour Winnie, his wife Jennifer plays daughter Cathy, and his real-life grandson, Jamie OCarroll, plays Mrs Browns grandson, Bono. His on screen daughter-in-law Betty (Amanda Woods) is his real life daughter-in-law (shes married to Danny aka Buster), while TV son Trevor (Martin Delany) is actually his son-in-law (married to Fiona OCarroll aka Maria), and his sister-in-law plays Winnies daughter, Sharon. Winnie McGoogan Eilish OCarroll Next door neighbour Winnie may be Agnes best pal on screen but in real life shes Brendan OCarrolls sister. Eilish is Maria (Fiona OCarroll) and Busters (Danny OCarroll) real-life aunt, and Cathy aka Jennifer Gibneys sister-in-law, while her on-screen daughter Sharon, is actually Jennifer Gibneys off screen sister. Shes also grand aunt to Bono Brown (Jamie Carroll). Cathy Brown Jennifer Gibney Mrs Browns on-screen daughter is actually Brendan OCarrolls wife, making her Buster (Danny OCarroll) and Marias real-life stepmother and Bonos off-screen step-grandmother. Winnie (Eilish) is her sister-in-law, Mrs Browns son Trevor is her son-in-law by marriage, and Marks wife Betty is her daughter-in-law by marriage. Plus Winnies daughter, Sharon, is her real-life sister. Buster Brady Danny OCarroll The on-screen troublemaker is Brendan OCarrolls real-life son, making him Marias (Fiona OCarroll) real-life brother, Cathys (Jennifer Gibney) stepson, and Winnies nephew. His wife, Amanda, plays Betty Brown, while his son, Jamie, is Bono Brown, and his real-life brother-in-law Martin Delany plays Mrs Browns youngest son, Trevor. Oh, and his real-life best friend Paddy Houlihan plays Mrs Browns other son, Dermot. Maria Brown Fiona OCarroll Mrs Browns on screen daughter-in-law Maria is actually Brendans daughter, Fiona OCarroll or Fiona Delany to call her by her married name. That makes Jennifer Gibney (Cathy) her stepmum, Eilish OCarroll (Winnie) her aunt and Buster (Danny OCarroll) her brother. Little Bono Brown is actually her nephew, Jamie, while her sister-in-law, Amanda Woods, is Betty Brown. Oh, and her husband, Martin Delany, plays Mrs Browns son Trevor. Trevor Brown Martin Delany Mrs Browns youngest son is played by OCarrolls son-in-law, Martin Delany, who is married to Fiona OCarroll his on-screen sister-in-law. That makes him Busters (Danny OCarroll) brother-in-law and uncle to Bono (Jamie OCarroll) Brown. Betty Brown Amanda Woods Mrs Browns on-screen daughter-in-law is actually Brendans daughter-in-law off screen too, as shes married to Buster (Danny OCarroll) Brady in real life. Shes Maria (Fiona OCarroll) Browns sister-in-law, and shes mum to Bono (Jamie OCarroll) Brown both on and off screen. Bono Brown Jamie OCarroll Mrs Browns grandson, Bono, is Brendan OCarrolls real-life grandson, Jamie OCarroll. His real mum (Amanda Woods) plays his on-screen mum, Betty Brown, while his dad is actually Buster Brady (Danny OCarroll). That makes him Maria (Fiona OCarroll) Browns nephew and Eilish OCarrolls (Winnie) grand-nephew. Rory Brown Damien McKiernan Advertisement The new Rory is played by Damien McKiernan, a friend of the family who took over the role from Rory Cowan in the 2017 Christmas special.", "url": "https://www.radiotimes.com/news/2019-01-01/how-are-the-cast-of-mrs-browns-boys-related/"}
{"question": "When is Catastrophe back on TV?", "article": "Sharon Horgan and Rob Delaneys filthily funny comedy Catastrophe is coming back for a fourth series. Advertisement We will rejoin the couple in their domesticated bliss or not in a new series on Channel 4 that promises to be as brutally honest as ever and explore the reality of sex in long-term relationships. Catastrophe series four begins on Monday 7 January at 10pm on Channel 4. Series three saw Rob unable to repress his struggle with alcoholism, and ended with a dramatic cliffhanger. Refresh your memory on the last moments of the finale here. Catastrophe series four is expected to cover the reality of sex in long-term relationships, as well as bid a final farewell to Carrie Fisher, who played Delaneys mother in the show and who died after filming series three. Co-creators Sharon Horgan and Rob Delaney will be back to reprise their roles as Sharon and Rob. Carrie Fisher will be dearly missed from the new series, but we are hoping to see Mark Bonnar and Ashley Jensen return as Chris and Fran, as well as Jonathon Forbes as Sharons brother. New guest stars joining the Catastrophe clan, meanwhile, are Broadchurch star Julie Hesmondhalgh and Sex and the Citys Chris Noth, alongside Michaela Watkins (Casual), comedian David Alan Grier, Nat Faxon (Friends from College) and Brian Gleeson (Love/Hate). Sharon Horgan has been incredibly busy. Not only did she make her Hollywood debut in Game Night alongside Rachel McAdams and Jason Bateman, she is also set to star in Happy AF, and has been penning the continuing series Motherland and Divorce. Horgan also voices Courtney Portnoy in BoJack Horseman. Aside from being the funniest person on Twitter, Delaney has made a popular appearance in Deadpool 2 and has been touring as a stand-up comedian. Youre in luck series 1-3 of Catastrophe are available to watch on All4.", "url": "https://www.radiotimes.com/news/tv/2019-01-01/catastrophe-series-4-air-date-trailer-cast/"}
{"question": "Is Vince Williams calling out Steelers' teammates who spoke about Antonio Brown?", "article": "Take this one for what its worth but it seems Pittsburgh Steelers linebacker Vince Williams is upset about rats and I dont think he means rodents. Williams took to Twitter Monday night and posted this tweet, which leaves plenty to the imagination. If we assume it is the latter, Williams fails to recognize the damage keeping all this discord in has done to this team. By failing to address the nonsense and drama attributed to a handful of players it spread to everyone within the organization on some level and ultimately played a part in the teams failures this season. Either way, this wont be the last we hear of this situation. Head coach Mike Tomlin will address the media on Wednesday and this latest round of controversy is going to be the main event.", "url": "https://steelerswire.usatoday.com/2018/12/31/is-vince-williams-calling-out-steelers-teammates-who-spoke-about-antonio-brown/"}
{"question": "What went right on the second floor in Parkland?", "article": "Those on the first and third floors of the 1200 Building at Marjory Stoneman Douglas High School got little warning. The second floor was different. Teachers could hear the gunshots below, and they took action. Locks were bolted, lights darkened, windows covered and no one was hurt. The algebra teacher and her students huddled in fear and silence in a corner of the darkened classroom, their only protection the door she had locked and the piece of blue construction paper she had hastily taped over the doors window. Shanthi Viswanathan and the children in her second-floor classroom had heard the unmistakable sound of gunfire from afar and instantly fell into active-shooter mode. Now, they heard their doorknob rattle. He was here. After five seconds that felt like an eternity, he moved on. In the end, Nikolas Cruz shot 34 people in the 1200 building of the Parkland school that day, killing 17 on the first and third floors. But not a single person was hurt on the second floor. Those on the first floor were taken by surprise that day and barely had a chance to react to the blasts of semiautomatic gunfire. On the third floor, students and teachers couldnt clearly hear the gunshots below, and did not know they had a real shooter in their midst. But on the second floor, the sound was unmistakable to many. Students and teachers took action. The second-floor hallway was empty when Cruz ascended to it with his AR-15. A few of the classrooms happened to be unoccupied that afternoon. The students and teachers who were there had heard the definite sound of gunfire as Cruz stormed the first floor, and raced to the safety of locked classrooms. Of the 10 classrooms on the second floor of the 1200 building, three were unoccupied and at least half had their door windows covered so the killer could not see in. Lights were out in at least five of the occupied rooms as students and teachers sheltered silently in safe corners. We had enough time to hide, said second floor teacher Felicia Burgin. We could actually hear the gunshots. She heard them when one of her students went to the restroom, leaving the classroom door propped open. Burgin heard three shots in a row. Then a pause. Then three in a row again. Is that gunshots? she asked aloud. It sounded like gunshots. Ive been to a gun range before. The students heard it, too. They quickly ran to a far corner of the room. One turned off the lights. The door was set to lock when it was closed. They sat huddled. Some cried. Some were silent. Some took out their cell phones. All of her students rushed to the same safe corner. They didnt quite fit and if someone had been able to look through the window in the door they would have been seen, she said. They stayed in place when the shooting set off a fire alarm. Because when amid gunfire, Burgin said, You arent leaving the room no matter what. Things were different on the third floor, where Cruzs initial first bursts of gunfire that day could not so clearly be heard. When the shooting set off the fire alarm throughout the building, students on the third floor swarmed into the open hallway, thinking they were in the midst of a fire drill. Ernest Rospierski, a teacher on the third floor, noted another critical difference that helped those on the second floor smaller class sizes. Most of the second-floor classes were English or math, which are capped by the state at 25 students, said Rospierski, who teaches an Advanced Placement European History class with 37 kids. If I have 35 or more [students], like in classrooms in the first and third floor, there is not enough room to hide, he said. They were able to get away from the window he didnt have any easy targets. Sophomore Brooke Wofchuck, of Coral Springs, was in the second floor of the 1200 building in Mrs. Catherine Britts math class when he heard three pops rang out. Wofchuck said she immediately stared directly at the teacher. Those sound like gunshots, her teacher said, everyone get to the side of the room where we cant be seen. They ran to one side and ducked. Someone turned off the lights. I remember sitting next to someone and we grabbed hands and started to pray, God, please save us. We were beyond low, just whispering. My teacher was holding a bunch of kids in her arms, since so many of the students were crying, she said. She has praise for her teacher: Miss Britt handled it so calm. In Viswanathans second-floor class, their door knob rattled as they huddled tightly in a taped off corner, lights out. He was at my door trying to get in, said Viswanathan, who had guided her students into hiding, largely on a hunch. Mrs. V., as the math teacher is known, had already taken every step possible to protect the children in her classroom even before she knew they were in danger. I was not absolutely sure, but I had a hunch something was wrong, she said. I knew something had to be done quickly. She had locked the door before class that day. Weeks before, she had taped off part of the classroom next to the door to serve a safe space or hard corner for students to hide. When she heard the sound of gunfire, she directed her students to lie on the floor in designated spots. She placed a piece of paper on the rectangular window of the door and blocked the view of anyone trying to look in. Then she turned off the light. The killer moved on to another room. Her actions are considered a textbook example of how to elude an active shooter. Viswanathan said she had received little training but her instincts helped save lives. A Code Red training on Jan. 11, had tipped her off to the idea of covering her door window to obstruct the gunmans view. She had too many students to safely fit into the hard corner, she said. If I had 15 kids maybe I would have been able to hide them all, she said. Instead she directed about a half-dozen students to to lay on the floor on the other side of the class, where she huddled with them.. The only thing protecting them from gunfire was a piece of paper covering the window. Sarah Coco Bentaieb, a junior in Mrs. Vs math class, said she could hear students who were not in their classroom screaming and crying. Knowing there was danger outside of the door, not knowing who was going to shoot through, that was the scariest part, the unknown, she said. A couple doors down, Chris Mathew and his students held their collective breath as the killer paused at their darkened door. Nobody here, Mathew said he heard the killer say.", "url": "https://www.sun-sentinel.com/local/broward/parkland/florida-school-shooting/fl-ne-parkland-second-floor-htmlstory.html"}
{"question": "Is Taco Bell Open on New Years Day 2019?", "article": "New Years Day 2019 is finally here. A new year means a chance to reinvent yourself, explore new things, and soak up all the world has to offer. Whether youre craving a taco after a night of partying or youre looking to add Tex-Mex to your 2019 diet, youre in luck. Most Taco Bell restaurants are open on New Years Day. Before bundling up and heading out, though, be sure to check the location of a Taco Bell near you by clicking here. The Naked Chicken Chalupa is back on the menu for a hot second. Get it ASAP before it disappears again. pic.twitter.com/ovnos9VSPb Taco Bell (@tacobell) December 28, 2018 Taco Bell was founded in 1946, and has been expanding ever since, operating in countries like Australia, Canada, Chile, Cyprus, Greece, India, Japan, and more, today. Everything from tacos, burritos, and quesadillas to nachos, and other items. The very first chain was opened by John Bell in 1962, in California. Bell started out the business selling tacos at a food stand he called Taco-Tia. He went on to grow his business, and founded a series of restaurants called El Taco, which was sold to his partner who built the first ever Taco Bell. Within five years of launching Taco-Tia, there were 100 Taco Bell restaurants across the US. As of 2014, there were over 5,600 Taco Bells across the country. If youre looking for other foods to satisfy you on New Years Day, look no further. Chipotle is one restaurant that wont be shutting its doors to customers on the 1st. Come in and get your burrito fix, or head over to Subway to grab a sandwich if youre on the go. Chilis is also open, along with Applebees, McDonalds, Starbucks, and Burger King, to make sure that you dont go hungry when 2019 rolls in. The first New Years celebration in Times Square took place on December 31, 1904. It was first organized by Adolph Ochs, who owned The New York Times. Around 200,000 people attended the event; a number that grew exponentially in subsequent years. This year, over 1,000,000 people are expected to pack the streets of Times Square on New Years.", "url": "https://heavy.com/entertainment/2018/12/taco-bell-new-years-day-2019-open/"}
{"question": "What will happen to liquor stores now that grocery stores sell full strength beer?", "article": "Please enable Javascript to watch this video DENVER -- 2019 means full-strength beer is finally coming to grocery stores in Colorado. After decades of what many considered antiquated beer laws, 3.2 beer is no more come January 1. Any grocery store that sold 3.2 beer before, can sell full-strength beer after midnight. \"Today we celebrate bringing Colorado beer laws into the 21st century\" David Hosroth, Vice President of King Soopers, said during a New Years Eve event at the Capitol Monday. Big crowd on this cold and snowy day, celebrating the end of prohibition-era beer laws, allowing full strength beer in our grocery stores! Not so fast. That's because wine and liquor are still restricted at grocery stores across the state. \"Wine and liquor are handled separately,\" State Senate Chris Holbert said. Holbert explained that the same bill that allowed 3.2 beer to go away in 2019, also limits how many grocery stores can sell wine and liquor. \"Over a 20 year period the groceries stores will be able to have 20 locations where they will be able to sell everything,\" Holbert added. That means Colorado has until 2036 until grocery stores become true equivalents to a liquor store.", "url": "https://kdvr.com/2018/12/31/what-will-happen-to-liquor-stores-now-that-grocery-stores-sell-full-strength-beer/"}
{"url": "https://www.bookrix.com/_ebook-amardeep-kaur-randhawa-the-girl-next-door/", "text": "Amardeep Kaur Randhawa The Girl Next Door (Help ME) To My Family \n \n \n \n \n \n \n \n \n Publication Date: May 20th 2011 https://www.bookrix.com/-akrjatt47"}
{"repo_name": "132nd-etcher/EMFT", "path": "emft/gui/tab_about.py", "copies": "1", "size": "1269", "content": "# coding=utf-8\n\nfrom emft.core import constant\nfrom emft.core.logging import make_logger\nfrom emft.gui.base import GridLayout, HSpacer, Label, VLayout, VSpacer\nfrom emft.gui.main_ui_tab_widget import MainUiTabChild\n\nLOGGER = make_logger(__name__)\n\n\nclass TabChildAbout(MainUiTabChild):\n def tab_clicked(self):\n pass\n\n @property\n def tab_title(self) -> str:\n return 'About'\n\n def __init__(self, parent=None):\n super(TabChildAbout, self).__init__(parent)\n\n repo_label = Label(\n '''<a href='{link}'>{link}</a>'''.format(link=constant.LINK_REPO)\n )\n repo_label.setOpenExternalLinks(True)\n\n changelog_label = Label(\n '''<a href='{link}'>{link}</a>'''.format(link=constant.LINK_CHANGELOG)\n )\n changelog_label.setOpenExternalLinks(True)\n\n self.setLayout(\n VLayout(\n [\n GridLayout(\n [\n [Label('Github repository: '), repo_label, HSpacer()],\n [Label('Changelog: '), changelog_label, HSpacer()],\n ],\n [0, 0, 1]\n ),\n VSpacer(),\n ]\n )\n )\n", "license": "gpl-3.0"}
{"repo_name": "jfinkels/networkx", "path": "networkx/readwrite/graph6.py", "copies": "3", "size": "7803", "content": "# Original author: D. Eppstein, UC Irvine, August 12, 2003.\n# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.\n# Copyright (C) 2004-2016 by\n# Aric Hagberg <hagberg@lanl.gov>\n# Dan Schult <dschult@colgate.edu>\n# Pieter Swart <swart@lanl.gov>\n# Tomas Gavenciak <gavento@ucw.cz>\n# All rights reserved.\n# BSD license.\n#\n# Authors: Tomas Gavenciak <gavento@ucw.cz>\n# Aric Hagberg <aric.hagberg@lanl.gov>\n\"\"\"Functions for reading and writing graphs in the *graph6* format.\n\nThe *graph6* file format is suitable for small graphs or large dense\ngraphs. For large sparse graphs, use the *sparse6* format.\n\nFor more information, see the `graph6`_ homepage.\n\n.. _graph6: http://users.cecs.anu.edu.au/~bdm/data/formats.html\n\n\"\"\"\nimport networkx as nx\nfrom networkx.exception import NetworkXError\nfrom networkx.utils import open_file, not_implemented_for\n\n__all__ = ['read_graph6', 'parse_graph6', 'generate_graph6', 'write_graph6']\n\n\ndef parse_graph6(string):\n \"\"\"Read a simple undirected graph in graph6 format from string.\n\n Parameters\n ----------\n string : string\n Data in graph6 format\n\n Returns\n -------\n G : Graph\n\n Raises\n ------\n NetworkXError\n If the string is unable to be parsed in graph6 format\n\n Examples\n --------\n >>> G = nx.parse_graph6('A_')\n >>> sorted(G.edges())\n [(0, 1)]\n\n See Also\n --------\n generate_graph6, read_graph6, write_graph6\n\n References\n ----------\n .. [1] Graph6 specification\n <http://users.cecs.anu.edu.au/~bdm/data/formats.html>\n\n \"\"\"\n def bits():\n \"\"\"Return sequence of individual bits from 6-bit-per-value\n list of data values.\"\"\"\n for d in data:\n for i in [5,4,3,2,1,0]:\n yield (d>>i)&1\n\n if string.startswith('>>graph6<<'):\n string = string[10:]\n data = graph6_to_data(string)\n n, data = data_to_n(data)\n nd = (n*(n-1)//2 + 5) // 6\n if len(data) != nd:\n raise NetworkXError(\\\n 'Expected %d bits but got %d in graph6' % (n*(n-1)//2, len(data)*6))\n\n G=nx.Graph()\n G.add_nodes_from(range(n))\n for (i,j),b in zip([(i,j) for j in range(1,n) for i in range(j)], bits()):\n if b:\n G.add_edge(i,j)\n\n return G\n\n@open_file(0,mode='rt')\ndef read_graph6(path):\n \"\"\"Read simple undirected graphs in graph6 format from path.\n\n Parameters\n ----------\n path : file or string\n File or filename to write.\n\n Returns\n -------\n G : Graph or list of Graphs\n If the file contains multiple lines then a list of graphs is returned\n\n Raises\n ------\n NetworkXError\n If the string is unable to be parsed in graph6 format\n\n Examples\n --------\n >>> nx.write_graph6(nx.Graph([(0,1)]), 'test.g6')\n >>> G = nx.read_graph6('test.g6')\n >>> sorted(G.edges())\n [(0, 1)]\n\n See Also\n --------\n generate_graph6, parse_graph6, write_graph6\n\n References\n ----------\n .. [1] Graph6 specification\n <http://users.cecs.anu.edu.au/~bdm/data/formats.html>\n\n \"\"\"\n glist = []\n for line in path:\n line = line.strip()\n if not len(line):\n continue\n glist.append(parse_graph6(line))\n if len(glist) == 1:\n return glist[0]\n else:\n return glist\n\n@not_implemented_for('directed','multigraph')\ndef generate_graph6(G, nodes = None, header=True):\n \"\"\"Generate graph6 format string from a simple undirected graph.\n\n Parameters\n ----------\n G : Graph (undirected)\n\n nodes: list or iterable\n Nodes are labeled 0...n-1 in the order provided. If None the ordering\n given by G.nodes() is used.\n\n header: bool\n If True add '>>graph6<<' string to head of data\n\n Returns\n -------\n s : string\n String in graph6 format\n\n Raises\n ------\n NetworkXError\n If the graph is directed or has parallel edges\n\n Examples\n --------\n >>> G = nx.Graph([(0, 1)])\n >>> nx.generate_graph6(G)\n '>>graph6<<A_'\n\n See Also\n --------\n read_graph6, parse_graph6, write_graph6\n\n Notes\n -----\n The format does not support edge or node labels, parallel edges or\n self loops. If self loops are present they are silently ignored.\n\n References\n ----------\n .. [1] Graph6 specification\n <http://users.cecs.anu.edu.au/~bdm/data/formats.html>\n\n \"\"\"\n if nodes is not None:\n G = G.subgraph(nodes)\n H = nx.convert_node_labels_to_integers(G)\n ns = sorted(H.nodes())\n def bits():\n for (i,j) in [(i,j) for j in range(1,n) for i in range(j)]:\n yield G.has_edge(ns[i],ns[j])\n\n n = G.order()\n data = n_to_data(n)\n d = 0\n flush = False\n for i, b in zip(range(n * n), bits()):\n d |= b << (5 - (i % 6))\n flush = True\n if i % 6 == 5:\n data.append(d)\n d = 0\n flush = False\n if flush:\n data.append(d)\n\n string_data = data_to_graph6(data)\n if header:\n string_data = '>>graph6<<' + string_data\n return string_data\n\n\n@open_file(1, mode='wt')\ndef write_graph6(G, path, nodes = None, header=True):\n \"\"\"Write a simple undirected graph to path in graph6 format.\n\n Parameters\n ----------\n G : Graph (undirected)\n\n path : file or string\n File or filename to write.\n\n nodes: list or iterable\n Nodes are labeled 0...n-1 in the order provided. If None the ordering\n given by G.nodes() is used.\n\n header: bool\n If True add '>>graph6<<' string to head of data\n\n Raises\n ------\n NetworkXError\n If the graph is directed or has parallel edges\n\n Examples\n --------\n >>> G = nx.Graph([(0, 1)])\n >>> nx.write_graph6(G, 'test.g6')\n\n See Also\n --------\n generate_graph6, parse_graph6, read_graph6\n\n Notes\n -----\n The format does not support edge or node labels, parallel edges or\n self loops. If self loops are present they are silently ignored.\n\n References\n ----------\n .. [1] Graph6 specification\n <http://users.cecs.anu.edu.au/~bdm/data/formats.html>\n\n \"\"\"\n path.write(generate_graph6(G, nodes=nodes, header=header))\n path.write('\\n')\n\n# helper functions\n\ndef graph6_to_data(string):\n \"\"\"Convert graph6 character sequence to 6-bit integers.\"\"\"\n v = [ord(c)-63 for c in string]\n if len(v) > 0 and (min(v) < 0 or max(v) > 63):\n return None\n return v\n\ndef data_to_graph6(data):\n \"\"\"Convert 6-bit integer sequence to graph6 character sequence.\"\"\"\n if len(data) > 0 and (min(data) < 0 or max(data) > 63):\n raise NetworkXError(\"graph6 data units must be within 0..63\")\n return ''.join([chr(d+63) for d in data])\n\ndef data_to_n(data):\n \"\"\"Read initial one-, four- or eight-unit value from graph6\n integer sequence.\n\n Return (value, rest of seq.)\"\"\"\n if data[0] <= 62:\n return data[0], data[1:]\n if data[1] <= 62:\n return (data[1]<<12) + (data[2]<<6) + data[3], data[4:]\n return ((data[2]<<30) + (data[3]<<24) + (data[4]<<18) +\n (data[5]<<12) + (data[6]<<6) + data[7], data[8:])\n\ndef n_to_data(n):\n \"\"\"Convert an integer to one-, four- or eight-unit graph6 sequence.\"\"\"\n if n < 0:\n raise NetworkXError(\"Numbers in graph6 format must be non-negative.\")\n if n <= 62:\n return [n]\n if n <= 258047:\n return [63, (n>>12) & 0x3f, (n>>6) & 0x3f, n & 0x3f]\n if n <= 68719476735:\n return [63, 63,\n (n>>30) & 0x3f, (n>>24) & 0x3f, (n>>18) & 0x3f,\n (n>>12) & 0x3f, (n>>6) & 0x3f, n & 0x3f]\n raise NetworkXError(\"Numbers above 68719476735 are not supported by graph6\")\n\n\ndef teardown_module(module):\n import os\n if os.path.isfile('test.g6'):\n os.unlink('test.g6')\n", "license": "bsd-3-clause"}
{"repo_name": "imply/chuu", "path": "ppapi/generators/idl_lexer.py", "copies": "62", "size": "9292", "content": "#!/usr/bin/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\" Lexer for PPAPI IDL \"\"\"\n\n#\n# IDL Lexer\n#\n# The lexer is uses the PLY lex library to build a tokenizer which understands\n# WebIDL tokens.\n#\n# WebIDL, and WebIDL regular expressions can be found at:\n# http://dev.w3.org/2006/webapi/WebIDL/\n# PLY can be found at:\n# http://www.dabeaz.com/ply/\n\nimport os.path\nimport re\nimport sys\n\n#\n# Try to load the ply module, if not, then assume it is in the third_party\n# directory, relative to ppapi\n#\ntry:\n from ply import lex\nexcept:\n module_path, module_name = os.path.split(__file__)\n third_party = os.path.join(module_path, '..', '..', 'third_party')\n sys.path.append(third_party)\n from ply import lex\n\nfrom idl_option import GetOption, Option, ParseOptions\n\n\nOption('output', 'Generate output.')\n\n#\n# IDL Lexer\n#\nclass IDLLexer(object):\n # 'tokens' is a value required by lex which specifies the complete list\n # of valid token types.\n tokens = [\n # Symbol and keywords types\n 'COMMENT',\n 'DESCRIBE',\n 'ENUM',\n 'LABEL',\n 'SYMBOL',\n 'INLINE',\n 'INTERFACE',\n 'STRUCT',\n 'TYPEDEF',\n\n # Extra WebIDL keywords\n 'CALLBACK',\n 'DICTIONARY',\n 'OPTIONAL',\n 'STATIC',\n\n # Invented for apps use\n 'NAMESPACE',\n\n # Data types\n 'FLOAT',\n 'OCT',\n 'INT',\n 'HEX',\n 'STRING',\n\n # Operators\n 'LSHIFT',\n 'RSHIFT'\n ]\n\n # 'keywords' is a map of string to token type. All SYMBOL tokens are\n # matched against keywords, to determine if the token is actually a keyword.\n keywords = {\n 'describe' : 'DESCRIBE',\n 'enum' : 'ENUM',\n 'label' : 'LABEL',\n 'interface' : 'INTERFACE',\n 'readonly' : 'READONLY',\n 'struct' : 'STRUCT',\n 'typedef' : 'TYPEDEF',\n\n 'callback' : 'CALLBACK',\n 'dictionary' : 'DICTIONARY',\n 'optional' : 'OPTIONAL',\n 'static' : 'STATIC',\n 'namespace' : 'NAMESPACE',\n }\n\n # 'literals' is a value expected by lex which specifies a list of valid\n # literal tokens, meaning the token type and token value are identical.\n literals = '\"*.(){}[],;:=+-/~|&^?'\n\n # Token definitions\n #\n # Lex assumes any value or function in the form of 't_<TYPE>' represents a\n # regular expression where a match will emit a token of type <TYPE>. In the\n # case of a function, the function is called when a match is made. These\n # definitions come from WebIDL.\n\n # 't_ignore' is a special match of items to ignore\n t_ignore = ' \\t'\n\n # Constant values\n t_FLOAT = r'-?(\\d+\\.\\d*|\\d*\\.\\d+)([Ee][+-]?\\d+)?|-?\\d+[Ee][+-]?\\d+'\n t_INT = r'-?[0-9]+[uU]?'\n t_OCT = r'-?0[0-7]+'\n t_HEX = r'-?0[Xx][0-9A-Fa-f]+'\n t_LSHIFT = r'<<'\n t_RSHIFT = r'>>'\n\n # A line ending '\\n', we use this to increment the line number\n def t_LINE_END(self, t):\n r'\\n+'\n self.AddLines(len(t.value))\n\n # We do not process escapes in the IDL strings. Strings are exclusively\n # used for attributes, and not used as typical 'C' constants.\n def t_STRING(self, t):\n r'\"[^\"]*\"'\n t.value = t.value[1:-1]\n self.AddLines(t.value.count('\\n'))\n return t\n\n # A C or C++ style comment: /* xxx */ or //\n def t_COMMENT(self, t):\n r'(/\\*(.|\\n)*?\\*/)|(//.*(\\n[ \\t]*//.*)*)'\n self.AddLines(t.value.count('\\n'))\n return t\n\n # Return a \"preprocessor\" inline block\n def t_INLINE(self, t):\n r'\\#inline (.|\\n)*?\\#endinl.*'\n self.AddLines(t.value.count('\\n'))\n return t\n\n # A symbol or keyword.\n def t_KEYWORD_SYMBOL(self, t):\n r'_?[A-Za-z][A-Za-z_0-9]*'\n\n # All non-keywords are assumed to be symbols\n t.type = self.keywords.get(t.value, 'SYMBOL')\n\n # We strip leading underscores so that you can specify symbols with the same\n # value as a keywords (E.g. a dictionary named 'interface').\n if t.value[0] == '_':\n t.value = t.value[1:]\n return t\n\n def t_ANY_error(self, t):\n msg = \"Unrecognized input\"\n line = self.lexobj.lineno\n\n # If that line has not been accounted for, then we must have hit\n # EoF, so compute the beginning of the line that caused the problem.\n if line >= len(self.index):\n # Find the offset in the line of the first word causing the issue\n word = t.value.split()[0]\n offs = self.lines[line - 1].find(word)\n # Add the computed line's starting position\n self.index.append(self.lexobj.lexpos - offs)\n msg = \"Unexpected EoF reached after\"\n\n pos = self.lexobj.lexpos - self.index[line]\n file = self.lexobj.filename\n out = self.ErrorMessage(file, line, pos, msg)\n sys.stderr.write(out + '\\n')\n self.lex_errors += 1\n\n\n def AddLines(self, count):\n # Set the lexer position for the beginning of the next line. In the case\n # of multiple lines, tokens can not exist on any of the lines except the\n # last one, so the recorded value for previous lines are unused. We still\n # fill the array however, to make sure the line count is correct.\n self.lexobj.lineno += count\n for i in range(count):\n self.index.append(self.lexobj.lexpos)\n\n def FileLineMsg(self, file, line, msg):\n if file: return \"%s(%d) : %s\" % (file, line + 1, msg)\n return \"<BuiltIn> : %s\" % msg\n\n def SourceLine(self, file, line, pos):\n caret = '\\t^'.expandtabs(pos)\n # We decrement the line number since the array is 0 based while the\n # line numbers are 1 based.\n return \"%s\\n%s\" % (self.lines[line - 1], caret)\n\n def ErrorMessage(self, file, line, pos, msg):\n return \"\\n%s\\n%s\" % (\n self.FileLineMsg(file, line, msg),\n self.SourceLine(file, line, pos))\n\n def SetData(self, filename, data):\n # Start with line 1, not zero\n self.lexobj.lineno = 1\n self.lexobj.filename = filename\n self.lines = data.split('\\n')\n self.index = [0]\n self.lexobj.input(data)\n self.lex_errors = 0\n\n def __init__(self):\n self.lexobj = lex.lex(object=self, lextab=None, optimize=0)\n\n\n\n#\n# FilesToTokens\n#\n# From a set of source file names, generate a list of tokens.\n#\ndef FilesToTokens(filenames, verbose=False):\n lexer = IDLLexer()\n outlist = []\n for filename in filenames:\n data = open(filename).read()\n lexer.SetData(filename, data)\n if verbose: sys.stdout.write(' Loaded %s...\\n' % filename)\n while 1:\n t = lexer.lexobj.token()\n if t is None: break\n outlist.append(t)\n return outlist\n\n\ndef TokensFromText(text):\n lexer = IDLLexer()\n lexer.SetData('unknown', text)\n outlist = []\n while 1:\n t = lexer.lexobj.token()\n if t is None: break\n outlist.append(t.value)\n return outlist\n\n#\n# TextToTokens\n#\n# From a block of text, generate a list of tokens\n#\ndef TextToTokens(source):\n lexer = IDLLexer()\n outlist = []\n lexer.SetData('AUTO', source)\n while 1:\n t = lexer.lexobj.token()\n if t is None: break\n outlist.append(t.value)\n return outlist\n\n\n#\n# TestSame\n#\n# From a set of token values, generate a new source text by joining with a\n# single space. The new source is then tokenized and compared against the\n# old set.\n#\ndef TestSame(values1):\n # Recreate the source from the tokens. We use newline instead of whitespace\n # since the '//' and #inline regex are line sensitive.\n text = '\\n'.join(values1)\n values2 = TextToTokens(text)\n\n count1 = len(values1)\n count2 = len(values2)\n if count1 != count2:\n print \"Size mismatch original %d vs %d\\n\" % (count1, count2)\n if count1 > count2: count1 = count2\n\n for i in range(count1):\n if values1[i] != values2[i]:\n print \"%d >>%s<< >>%s<<\" % (i, values1[i], values2[i])\n\n if GetOption('output'):\n sys.stdout.write('Generating original.txt and tokenized.txt\\n')\n open('original.txt', 'w').write(src1)\n open('tokenized.txt', 'w').write(src2)\n\n if values1 == values2:\n sys.stdout.write('Same: Pass\\n')\n return 0\n\n print \"****************\\n%s\\n%s***************\\n\" % (src1, src2)\n sys.stdout.write('Same: Failed\\n')\n return -1\n\n\n#\n# TestExpect\n#\n# From a set of tokens pairs, verify the type field of the second matches\n# the value of the first, so that:\n# INT 123 FLOAT 1.1\n# will generate a passing test, where the first token is the SYMBOL INT,\n# and the second token is the INT 123, third token is the SYMBOL FLOAT and\n# the fourth is the FLOAT 1.1, etc...\ndef TestExpect(tokens):\n count = len(tokens)\n index = 0\n errors = 0\n while index < count:\n type = tokens[index].value\n token = tokens[index + 1]\n index += 2\n\n if type != token.type:\n sys.stderr.write('Mismatch: Expected %s, but got %s = %s.\\n' %\n (type, token.type, token.value))\n errors += 1\n\n if not errors:\n sys.stdout.write('Expect: Pass\\n')\n return 0\n\n sys.stdout.write('Expect: Failed\\n')\n return -1\n\n\ndef Main(args):\n filenames = ParseOptions(args)\n\n try:\n tokens = FilesToTokens(filenames, GetOption('verbose'))\n values = [tok.value for tok in tokens]\n if GetOption('output'): sys.stdout.write(' <> '.join(values) + '\\n')\n if GetOption('test'):\n if TestSame(values):\n return -1\n if TestExpect(tokens):\n return -1\n return 0\n\n except lex.LexError as le:\n sys.stderr.write('%s\\n' % str(le))\n return -1\n\n\nif __name__ == '__main__':\n sys.exit(Main(sys.argv[1:]))\n", "license": "bsd-3-clause"}
{"repo_name": "sanger-pathogens/gff3toembl", "path": "gff3toembl/EMBLConverter.py", "copies": "3", "size": "1946", "content": "import gff3toembl\nfrom gt import CustomVisitor\nfrom gff3toembl.EMBLContig import EMBLContig\n\nclass EMBLConverter(CustomVisitor):\n\n def __init__(self, locus_tag=None, translation_table=11):\n CustomVisitor.__init__(self)\n self.contigs = {}\n self.locus_tag = locus_tag\n self.translation_table = translation_table\n\n def visit_feature_node(self, feature_node):\n sequence_id = feature_node.get_seqid()\n contig = self.contigs.get(sequence_id)\n if contig: # contig already exists, just try and update it\n contig.add_feature(sequence_id = sequence_id, feature_type = feature_node.get_type(), start = feature_node.get_start(),\n end = feature_node.get_end(), strand = feature_node.get_strand(),\n feature_attributes = feature_node.attribs,\n locus_tag = self.locus_tag, translation_table = self.translation_table)\n else:\n contig = EMBLContig()\n successfully_added_feature = contig.add_feature(sequence_id = sequence_id, feature_type = feature_node.get_type(), start = feature_node.get_start(),\n end = feature_node.get_end(), strand = feature_node.get_strand(),\n feature_attributes = feature_node.attribs,\n locus_tag = self.locus_tag, translation_table = self.translation_table)\n if successfully_added_feature:\n self.contigs[sequence_id] = contig\n else:\n pass # discard the contig because we didn't add a feature so it is empty\n\n def visit_region_node(self, region_node):\n pass # for now\n\n def visit_comment_node(self, comment_node):\n pass # for now\n\n def visit_sequence_node(self, sequence_node):\n sequence_id = sequence_node.get_description()\n contig = self.contigs.setdefault(sequence_id, EMBLContig())\n contig.add_sequence(sequence_node.get_sequence())\n", "license": "gpl-3.0"}
{"repo_name": "SanPen/GridCal", "path": "src/GridCal/Engine/Sparse/utils.py", "copies": "1", "size": "2463", "content": "# This file is part of GridCal.\n#\n# GridCal is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# GridCal is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GridCal. If not, see <http://www.gnu.org/licenses/>.\n\nimport numpy as np\n\n\ndef slice_to_range(sl: slice, n):\n \"\"\"\n Turn a slice into a range\n :param sl: slice object\n :param n: total number of items\n :return: range object, if the slice is not supported an exception is raised\n \"\"\"\n if sl.start is None and sl.step is None and sl.start is None: # (:)\n return range(n)\n\n elif sl.start is not None and sl.step is None and sl.start is None: # (a:)\n return range(sl.start, n)\n\n elif sl.start is not None and sl.step is not None and sl.start is None: # (?)\n raise Exception('Invalid slice')\n elif sl.start is not None and sl.step is None and sl.start is not None: # (a:b)\n return range(sl.start, sl.stop)\n\n elif sl.start is not None and sl.step is not None and sl.start is not None: # (a:s:b)\n return range(sl.start, sl.stop, sl.step)\n\n elif sl.start is None and sl.step is None and sl.start is not None: # (:b)\n return range(sl.stop)\n\n else:\n raise Exception('Invalid slice')\n\n\ndef dense_to_str(mat: np.ndarray):\n \"\"\"\n Turn dense 2D numpy array into a string\n :param mat: 2D numpy array\n :return: string\n \"\"\"\n rows, cols = mat.shape\n val = \"Matrix (\" + (\"%d\" % rows) + \" x \" + (\"%d\" % cols) + \")\\n\"\n val += str(mat).replace('. ', ' ').replace('[', ' ').replace(']', '').replace('0 ', '_ ').replace('0.', '_ ')\n # for i in range(0, rows):\n # for j in range(0, cols):\n # x = mat[i, j]\n # if x is not None:\n # if x == 0:\n # val += '{:<4}'.format(0)\n # else:\n # val += '{:<4}'.format(x)\n # else:\n # val += \"\"\n # val += '\\n'\n\n # for rows in M:\n # print(*['{:<4}'.format(each) for each in rows])\n\n return val\n\n", "license": "gpl-3.0"}
{"repo_name": "trashkalmar/omim", "path": "tools/python/mwm/dump_mwm.py", "copies": "10", "size": "1418", "content": "#!/usr/bin/python\nimport sys, os.path, random\nimport json\nfrom mwm import MWM\n\nif len(sys.argv) < 2:\n print('Dumps some MWM structures.')\n print('Usage: {0} <country.mwm>'.format(sys.argv[0]))\n sys.exit(1)\n\nmwm = MWM(open(sys.argv[1], 'rb'))\nmwm.read_types(os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..', 'data', 'types.txt'))\nprint('Tags:')\ntvv = sorted([(k, v[0], v[1]) for k, v in mwm.tags.items()], key=lambda x: x[1])\nfor tv in tvv:\n print(' {0:<8}: offs {1:9} len {2:8}'.format(tv[0], tv[1], tv[2]))\nv = mwm.read_version()\nprint('Format: {0}, version: {1}'.format(v['fmt'], v['date'].strftime('%Y-%m-%d %H:%M')))\nprint('Header: {0}'.format(mwm.read_header()))\nprint('Region Info: {0}'.format(mwm.read_region_info()))\nprint('Metadata count: {0}'.format(len(mwm.read_metadata())))\n\ncross = mwm.read_crossmwm()\nif cross:\n print('Outgoing points: {0}, incoming: {1}'.format(len(cross['out']), len(cross['in'])))\n print('Outgoing regions: {0}'.format(set(cross['neighbours'])))\n\n# Print some random features using reservoir sampling\ncount = 5\nsample = []\nfor i, feature in enumerate(mwm.iter_features()):\n if i < count:\n sample.append(feature)\n elif random.randint(0, i) < count:\n sample[random.randint(0, count-1)] = feature\n\nprint('Feature count: {0}'.format(i))\nprint('Sample features:')\nfor feature in sample:\n print(json.dumps(feature, ensure_ascii=False))\n", "license": "apache-2.0"}
{"repo_name": "vergecurrency/electrum-xvg", "path": "gui/qt/version_getter.py", "copies": "2", "size": "4598", "content": "#!/usr/bin/env python\n#\n# Electrum - lightweight Bitcoin client\n# Copyright (C) 2012 thomasv@gitorious\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport threading, re, socket\nimport webbrowser\nimport requests\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nimport PyQt4.QtCore as QtCore\n\nfrom electrum_xvg.i18n import _\nfrom electrum_xvg import ELECTRUM_VERSION, print_error\n\nclass VersionGetter(threading.Thread):\n\n def __init__(self, label):\n threading.Thread.__init__(self)\n self.label = label\n self.daemon = True\n\n def run(self):\n try:\n res = requests.request(\"GET\", \"http://electrum-verge.xyz/version\")\n except:\n print_error(\"Could not retrieve version information\")\n return\n\n if res.status_code == 200:\n latest_version = res.text\n latest_version = latest_version.replace(\"\\n\",\"\")\n if(re.match('^\\d+(\\.\\d+)*$', latest_version)):\n self.label.callback(latest_version)\n\nclass UpdateLabel(QLabel):\n def __init__(self, config, sb):\n QLabel.__init__(self)\n self.new_version = False\n self.sb = sb\n self.config = config\n self.current_version = ELECTRUM_VERSION\n self.connect(self, QtCore.SIGNAL('new_electrum_version'), self.new_electrum_version)\n # prevent HTTP leaks if a proxy is set\n if self.config.get('proxy'):\n return\n VersionGetter(self).start()\n\n def callback(self, version):\n self.latest_version = version\n if(self.compare_versions(self.latest_version, self.current_version) == 1):\n latest_seen = self.config.get(\"last_seen_version\",ELECTRUM_VERSION)\n if(self.compare_versions(self.latest_version, latest_seen) == 1):\n self.new_version = True\n self.emit(QtCore.SIGNAL('new_electrum_version'))\n\n def new_electrum_version(self):\n if self.new_version:\n self.setText(_(\"New version available\") + \": \" + self.latest_version)\n self.sb.insertPermanentWidget(1, self)\n\n def compare_versions(self, version1, version2):\n def normalize(v):\n return [int(x) for x in re.sub(r'(\\.0+)*$','', v).split(\".\")]\n try:\n return cmp(normalize(version1), normalize(version2))\n except:\n return 0\n\n def ignore_this_version(self):\n self.setText(\"\")\n self.config.set_key(\"last_seen_version\", self.latest_version, True)\n QMessageBox.information(self, _(\"Preference saved\"), _(\"Notifications about this update will not be shown again.\"))\n self.dialog.done(0)\n\n def ignore_all_version(self):\n self.setText(\"\")\n self.config.set_key(\"last_seen_version\", \"9.9.9\", True)\n QMessageBox.information(self, _(\"Preference saved\"), _(\"No more notifications about version updates will be shown.\"))\n self.dialog.done(0)\n\n def open_website(self):\n webbrowser.open(\"http://electrum-verge.xyz/download.html\")\n self.dialog.done(0)\n\n def mouseReleaseEvent(self, event):\n dialog = QDialog(self)\n dialog.setWindowTitle(_('Electrum-XVG update'))\n dialog.setModal(1)\n\n main_layout = QGridLayout()\n main_layout.addWidget(QLabel(_(\"A new version of Electrum-XVG is available:\")+\" \" + self.latest_version), 0,0,1,3)\n\n ignore_version = QPushButton(_(\"Ignore this version\"))\n ignore_version.clicked.connect(self.ignore_this_version)\n\n ignore_all_versions = QPushButton(_(\"Ignore all versions\"))\n ignore_all_versions.clicked.connect(self.ignore_all_version)\n\n open_website = QPushButton(_(\"Goto download page\"))\n open_website.clicked.connect(self.open_website)\n\n main_layout.addWidget(ignore_version, 1, 0)\n main_layout.addWidget(ignore_all_versions, 1, 1)\n main_layout.addWidget(open_website, 1, 2)\n\n dialog.setLayout(main_layout)\n\n self.dialog = dialog\n\n if not dialog.exec_(): return\n", "license": "gpl-3.0"}
{"repo_name": "lambeau/ansible-modules-core", "path": "cloud/openstack/_quantum_router.py", "copies": "37", "size": "7032", "content": "#!/usr/bin/python\n#coding: utf-8 -*-\n\n# (c) 2013, Benno Joy <benno@ansible.com>\n#\n# This module is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This software is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this software. If not, see <http://www.gnu.org/licenses/>.\n\ntry:\n try:\n from neutronclient.neutron import client\n except ImportError:\n from quantumclient.quantum import client\n from keystoneclient.v2_0 import client as ksclient\n HAVE_DEPS = True\nexcept ImportError:\n HAVE_DEPS = False\n\nDOCUMENTATION = '''\n---\nmodule: quantum_router\nversion_added: \"1.2\"\nauthor: \"Benno Joy (@bennojoy)\"\ndeprecated: Deprecated in 2.0. Use os_router instead\nshort_description: Create or Remove router from openstack\ndescription:\n - Create or Delete routers from OpenStack\noptions:\n login_username:\n description:\n - login username to authenticate to keystone\n required: true\n default: admin\n login_password:\n description:\n - Password of login user\n required: true\n default: 'yes'\n login_tenant_name:\n description:\n - The tenant name of the login user\n required: true\n default: 'yes'\n auth_url:\n description:\n - The keystone url for authentication\n required: false\n default: 'http://127.0.0.1:35357/v2.0/'\n region_name:\n description:\n - Name of the region\n required: false\n default: None\n state:\n description:\n - Indicate desired state of the resource\n choices: ['present', 'absent']\n default: present\n name:\n description:\n - Name to be give to the router\n required: true\n default: None\n tenant_name:\n description:\n - Name of the tenant for which the router has to be created, if none router would be created for the login tenant.\n required: false\n default: None\n admin_state_up:\n description:\n - desired admin state of the created router .\n required: false\n default: true\nrequirements:\n - \"python >= 2.6\"\n - \"python-neutronclient or python-quantumclient\"\n - \"python-keystoneclient\"\n'''\n\nEXAMPLES = '''\n# Creates a router for tenant admin\n- quantum_router: state=present\n login_username=admin\n login_password=admin\n login_tenant_name=admin\n name=router1\"\n'''\n\n_os_keystone = None\n_os_tenant_id = None\n\ndef _get_ksclient(module, kwargs):\n try:\n kclient = ksclient.Client(username=kwargs.get('login_username'),\n password=kwargs.get('login_password'),\n tenant_name=kwargs.get('login_tenant_name'),\n auth_url=kwargs.get('auth_url'))\n except Exception, e:\n module.fail_json(msg = \"Error authenticating to the keystone: %s \" % e.message)\n global _os_keystone\n _os_keystone = kclient\n return kclient\n\n\ndef _get_endpoint(module, ksclient):\n try:\n endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL')\n except Exception, e:\n module.fail_json(msg = \"Error getting network endpoint: %s\" % e.message)\n return endpoint\n\ndef _get_neutron_client(module, kwargs):\n _ksclient = _get_ksclient(module, kwargs)\n token = _ksclient.auth_token\n endpoint = _get_endpoint(module, _ksclient)\n kwargs = {\n 'token': token,\n 'endpoint_url': endpoint\n }\n try:\n neutron = client.Client('2.0', **kwargs)\n except Exception, e:\n module.fail_json(msg = \"Error in connecting to neutron: %s \" % e.message)\n return neutron\n\ndef _set_tenant_id(module):\n global _os_tenant_id\n if not module.params['tenant_name']:\n _os_tenant_id = _os_keystone.tenant_id\n else:\n tenant_name = module.params['tenant_name']\n\n for tenant in _os_keystone.tenants.list():\n if tenant.name == tenant_name:\n _os_tenant_id = tenant.id\n break\n if not _os_tenant_id:\n module.fail_json(msg = \"The tenant id cannot be found, please check the parameters\")\n\ndef _get_router_id(module, neutron):\n kwargs = {\n 'name': module.params['name'],\n 'tenant_id': _os_tenant_id,\n }\n try:\n routers = neutron.list_routers(**kwargs)\n except Exception, e:\n module.fail_json(msg = \"Error in getting the router list: %s \" % e.message)\n if not routers['routers']:\n return None\n return routers['routers'][0]['id']\n\ndef _create_router(module, neutron):\n router = {\n 'name': module.params['name'],\n 'tenant_id': _os_tenant_id,\n 'admin_state_up': module.params['admin_state_up'],\n }\n try:\n new_router = neutron.create_router(dict(router=router))\n except Exception, e:\n module.fail_json( msg = \"Error in creating router: %s\" % e.message)\n return new_router['router']['id']\n\ndef _delete_router(module, neutron, router_id):\n try:\n neutron.delete_router(router_id)\n except:\n module.fail_json(\"Error in deleting the router\")\n return True\n\ndef main():\n argument_spec = openstack_argument_spec()\n argument_spec.update(dict(\n name = dict(required=True),\n tenant_name = dict(default=None),\n state = dict(default='present', choices=['absent', 'present']),\n admin_state_up = dict(type='bool', default=True),\n ))\n module = AnsibleModule(argument_spec=argument_spec)\n if not HAVE_DEPS:\n module.fail_json(msg='python-keystoneclient and either python-neutronclient or python-quantumclient are required')\n\n neutron = _get_neutron_client(module, module.params)\n _set_tenant_id(module)\n\n if module.params['state'] == 'present':\n router_id = _get_router_id(module, neutron)\n if not router_id:\n router_id = _create_router(module, neutron)\n module.exit_json(changed=True, result=\"Created\", id=router_id)\n else:\n module.exit_json(changed=False, result=\"success\" , id=router_id)\n\n else:\n router_id = _get_router_id(module, neutron)\n if not router_id:\n module.exit_json(changed=False, result=\"success\")\n else:\n _delete_router(module, neutron, router_id)\n module.exit_json(changed=True, result=\"deleted\")\n\n# this is magic, see lib/ansible/module.params['common.py\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.openstack import *\nif __name__ == '__main__':\n main()\n\n", "license": "gpl-3.0"}
{"repo_name": "regionbibliotekhalland/digitalasagor", "path": "edittabvideo.py", "copies": "1", "size": "4897", "content": "# Copyright 2013 Regionbibliotek Halland\r\n#\r\n# This file is part of Digitala sagor.\r\n#\r\n# Digitala sagor is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# Digitala sagor is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with Digitala sagor. If not, see <http://www.gnu.org/licenses/>.\r\nfrom Tkinter import *\r\nimport ttk\r\n\r\nfrom tooltip import ToolTip\r\n\r\nfrom language import lang\r\nimport language as lng\r\nfrom playerdlg import showPlayerDialog\r\nfrom datamodel import tpVideo\r\nimport tkFileDialog\r\nimport os\r\nimport os.path\r\nimport shutil\r\nimport spmanager as spm\r\nfrom edittab import EditTab\r\n\r\n_videoFileFormats = [('mp4', '*.mp4'), ('avi', '*.avi'), ('wmv', '*.wmv'), ('mpeg', '*.mpeg'), ('mov', '*.mov')]\r\n\r\nclass EditTabVideo(EditTab):\r\n \"\"\"A Frame for editing video based stories\"\"\"\r\n def __init__(self, parent, wdir, datamodel, psize):\r\n \"\"\"Initiate\r\n \r\n Arguments\r\n parent -- parent tkinter item\r\n wdir -- working directory\r\n datamodel -- the database that is edited by the program\r\n psize -- tuple defining preview size of videos\r\n \r\n \"\"\"\r\n EditTab.__init__(self, parent, wdir, datamodel, psize)\r\n\r\n self._mediatype = tpVideo\r\n\r\n #Create variables for common data\r\n self._svVideo = StringVar()\r\n\r\n #Make the first row expandable \r\n self.rowconfigure(0, weight = 1)\r\n\r\n #Add frame from super class\r\n self._superFrame.grid(row = 0, column = 0, sticky = W + N)\r\n\r\n #Create the right column\r\n rightLf = ttk.LabelFrame(self, text = ' ' + lang[lng.txtVideo] + ' ')\r\n rightLf.grid(row = 0, column = 1, pady = 10, sticky = W + N)\r\n rightFrame = Frame(rightLf)\r\n rightFrame.grid()\r\n\r\n e = Entry(rightFrame, w = 32, textvariable = self._svVideo, state = \"readonly\")\r\n e.grid(row = 0, column = 0, padx = 10, pady = 5, sticky = W);\r\n\r\n tt = ToolTip(e, '', textvariable = self._svVideo, wraplength = parent.winfo_screenwidth() * 4 / 5)\r\n\r\n b = Button(rightFrame, text = lang[lng.txtSelect] + '...', command = self._ehGetVideo)\r\n b.grid(row = 0, column = 1, padx = 10, pady = 5)\r\n\r\n b = Button(rightFrame, text = lang[lng.txtWatch], command = self._ehWatch)\r\n b.grid(row = 0, column = 2, padx = 10, pady = 5)\r\n\r\n def open(self, slideshow, prepared = False):\r\n \"\"\"Open a slideshow for editing\r\n \r\n Arguments\r\n slideshow -- the slideshow\r\n prepared -- if true, all media data is already copied to the working folder\r\n (i.e. the slideshow has been created automatically)\r\n \r\n \"\"\"\r\n EditTab.open(self, slideshow, prepared = False)\r\n\r\n if(not prepared):\r\n if(slideshow.video != ''):\r\n shutil.copyfile(slideshow.getPath(slideshow.video), os.path.join(self._wdir, slideshow.video))\r\n\r\n self._svVideo.set(slideshow.video)\r\n\r\n def clear(self):\r\n \"\"\"Clear the edit tab\"\"\"\r\n EditTab.clear(self)\r\n self._svVideo.set('')\r\n\r\n def _getCurrentSlideshow(self):\r\n \"\"\"Create and return a slideshow representing the currently edited slideshow.\"\"\"\r\n slideshow = EditTab._getCurrentSlideshow(self)\r\n slideshow.video = self._svVideo.get()\r\n\r\n return slideshow \r\n \r\n #Event handlers\r\n def _ehGetVideo(self):\r\n \"\"\"Event handler for assigning a video\"\"\"\r\n initdir = spm.spmanager.getFirstPath([spm.VideoFolder, \r\n spm.MostRecentFolder])\r\n \r\n filenamepath = tkFileDialog.askopenfilename(initialdir = initdir, filetypes = _videoFileFormats)\r\n \r\n if(len(filenamepath) > 0):\r\n filename = os.path.basename(filenamepath)\r\n\r\n try:\r\n shutil.copyfile(filenamepath, os.path.join(self._wdir, filename))\r\n except IOError:\r\n showerror(lang[lng.txtCopyError], lang[lng.txtCouldNotCopy] + os.path.basename(filename))\r\n return\r\n\r\n self._svVideo.set(filename)\r\n self.setDirty(True)\r\n spm.spmanager.setPath(spm.VideoFolder, os.path.dirname(filenamepath))\r\n\r\n def _ehWatch(self):\r\n \"\"\"Event handler for preview of the video\"\"\"\r\n media = self._getCurrentSlideshow()\r\n showPlayerDialog(self._parent, self._psize, media)\r\n", "license": "gpl-3.0"}
{"repo_name": "devalbo/mm_anywhere", "path": "google/protobuf/internal/encoder.py", "copies": "484", "size": "25695", "content": "# Protocol Buffers - Google's data interchange format\n# Copyright 2008 Google Inc. All rights reserved.\n# http://code.google.com/p/protobuf/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Code for encoding protocol message primitives.\n\nContains the logic for encoding every logical protocol field type\ninto one of the 5 physical wire types.\n\nThis code is designed to push the Python interpreter's performance to the\nlimits.\n\nThe basic idea is that at startup time, for every field (i.e. every\nFieldDescriptor) we construct two functions: a \"sizer\" and an \"encoder\". The\nsizer takes a value of this field's type and computes its byte size. The\nencoder takes a writer function and a value. It encodes the value into byte\nstrings and invokes the writer function to write those strings. Typically the\nwriter function is the write() method of a cStringIO.\n\nWe try to do as much work as possible when constructing the writer and the\nsizer rather than when calling them. In particular:\n* We copy any needed global functions to local variables, so that we do not need\n to do costly global table lookups at runtime.\n* Similarly, we try to do any attribute lookups at startup time if possible.\n* Every field's tag is encoded to bytes at startup, since it can't change at\n runtime.\n* Whatever component of the field size we can compute at startup, we do.\n* We *avoid* sharing code if doing so would make the code slower and not sharing\n does not burden us too much. For example, encoders for repeated fields do\n not just call the encoders for singular fields in a loop because this would\n add an extra function call overhead for every loop iteration; instead, we\n manually inline the single-value encoder into the loop.\n* If a Python function lacks a return statement, Python actually generates\n instructions to pop the result of the last statement off the stack, push\n None onto the stack, and then return that. If we really don't care what\n value is returned, then we can save two instructions by returning the\n result of the last statement. It looks funny but it helps.\n* We assume that type and bounds checking has happened at a higher level.\n\"\"\"\n\n__author__ = 'kenton@google.com (Kenton Varda)'\n\nimport struct\nfrom google.protobuf.internal import wire_format\n\n\n# This will overflow and thus become IEEE-754 \"infinity\". We would use\n# \"float('inf')\" but it doesn't work on Windows pre-Python-2.6.\n_POS_INF = 1e10000\n_NEG_INF = -_POS_INF\n\n\ndef _VarintSize(value):\n \"\"\"Compute the size of a varint value.\"\"\"\n if value <= 0x7f: return 1\n if value <= 0x3fff: return 2\n if value <= 0x1fffff: return 3\n if value <= 0xfffffff: return 4\n if value <= 0x7ffffffff: return 5\n if value <= 0x3ffffffffff: return 6\n if value <= 0x1ffffffffffff: return 7\n if value <= 0xffffffffffffff: return 8\n if value <= 0x7fffffffffffffff: return 9\n return 10\n\n\ndef _SignedVarintSize(value):\n \"\"\"Compute the size of a signed varint value.\"\"\"\n if value < 0: return 10\n if value <= 0x7f: return 1\n if value <= 0x3fff: return 2\n if value <= 0x1fffff: return 3\n if value <= 0xfffffff: return 4\n if value <= 0x7ffffffff: return 5\n if value <= 0x3ffffffffff: return 6\n if value <= 0x1ffffffffffff: return 7\n if value <= 0xffffffffffffff: return 8\n if value <= 0x7fffffffffffffff: return 9\n return 10\n\n\ndef _TagSize(field_number):\n \"\"\"Returns the number of bytes required to serialize a tag with this field\n number.\"\"\"\n # Just pass in type 0, since the type won't affect the tag+type size.\n return _VarintSize(wire_format.PackTag(field_number, 0))\n\n\n# --------------------------------------------------------------------\n# In this section we define some generic sizers. Each of these functions\n# takes parameters specific to a particular field type, e.g. int32 or fixed64.\n# It returns another function which in turn takes parameters specific to a\n# particular field, e.g. the field number and whether it is repeated or packed.\n# Look at the next section to see how these are used.\n\n\ndef _SimpleSizer(compute_value_size):\n \"\"\"A sizer which uses the function compute_value_size to compute the size of\n each value. Typically compute_value_size is _VarintSize.\"\"\"\n\n def SpecificSizer(field_number, is_repeated, is_packed):\n tag_size = _TagSize(field_number)\n if is_packed:\n local_VarintSize = _VarintSize\n def PackedFieldSize(value):\n result = 0\n for element in value:\n result += compute_value_size(element)\n return result + local_VarintSize(result) + tag_size\n return PackedFieldSize\n elif is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n result += compute_value_size(element)\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n return tag_size + compute_value_size(value)\n return FieldSize\n\n return SpecificSizer\n\n\ndef _ModifiedSizer(compute_value_size, modify_value):\n \"\"\"Like SimpleSizer, but modify_value is invoked on each value before it is\n passed to compute_value_size. modify_value is typically ZigZagEncode.\"\"\"\n\n def SpecificSizer(field_number, is_repeated, is_packed):\n tag_size = _TagSize(field_number)\n if is_packed:\n local_VarintSize = _VarintSize\n def PackedFieldSize(value):\n result = 0\n for element in value:\n result += compute_value_size(modify_value(element))\n return result + local_VarintSize(result) + tag_size\n return PackedFieldSize\n elif is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n result += compute_value_size(modify_value(element))\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n return tag_size + compute_value_size(modify_value(value))\n return FieldSize\n\n return SpecificSizer\n\n\ndef _FixedSizer(value_size):\n \"\"\"Like _SimpleSizer except for a fixed-size field. The input is the size\n of one value.\"\"\"\n\n def SpecificSizer(field_number, is_repeated, is_packed):\n tag_size = _TagSize(field_number)\n if is_packed:\n local_VarintSize = _VarintSize\n def PackedFieldSize(value):\n result = len(value) * value_size\n return result + local_VarintSize(result) + tag_size\n return PackedFieldSize\n elif is_repeated:\n element_size = value_size + tag_size\n def RepeatedFieldSize(value):\n return len(value) * element_size\n return RepeatedFieldSize\n else:\n field_size = value_size + tag_size\n def FieldSize(value):\n return field_size\n return FieldSize\n\n return SpecificSizer\n\n\n# ====================================================================\n# Here we declare a sizer constructor for each field type. Each \"sizer\n# constructor\" is a function that takes (field_number, is_repeated, is_packed)\n# as parameters and returns a sizer, which in turn takes a field value as\n# a parameter and returns its encoded size.\n\n\nInt32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize)\n\nUInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize)\n\nSInt32Sizer = SInt64Sizer = _ModifiedSizer(\n _SignedVarintSize, wire_format.ZigZagEncode)\n\nFixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4)\nFixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8)\n\nBoolSizer = _FixedSizer(1)\n\n\ndef StringSizer(field_number, is_repeated, is_packed):\n \"\"\"Returns a sizer for a string field.\"\"\"\n\n tag_size = _TagSize(field_number)\n local_VarintSize = _VarintSize\n local_len = len\n assert not is_packed\n if is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n l = local_len(element.encode('utf-8'))\n result += local_VarintSize(l) + l\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n l = local_len(value.encode('utf-8'))\n return tag_size + local_VarintSize(l) + l\n return FieldSize\n\n\ndef BytesSizer(field_number, is_repeated, is_packed):\n \"\"\"Returns a sizer for a bytes field.\"\"\"\n\n tag_size = _TagSize(field_number)\n local_VarintSize = _VarintSize\n local_len = len\n assert not is_packed\n if is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n l = local_len(element)\n result += local_VarintSize(l) + l\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n l = local_len(value)\n return tag_size + local_VarintSize(l) + l\n return FieldSize\n\n\ndef GroupSizer(field_number, is_repeated, is_packed):\n \"\"\"Returns a sizer for a group field.\"\"\"\n\n tag_size = _TagSize(field_number) * 2\n assert not is_packed\n if is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n result += element.ByteSize()\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n return tag_size + value.ByteSize()\n return FieldSize\n\n\ndef MessageSizer(field_number, is_repeated, is_packed):\n \"\"\"Returns a sizer for a message field.\"\"\"\n\n tag_size = _TagSize(field_number)\n local_VarintSize = _VarintSize\n assert not is_packed\n if is_repeated:\n def RepeatedFieldSize(value):\n result = tag_size * len(value)\n for element in value:\n l = element.ByteSize()\n result += local_VarintSize(l) + l\n return result\n return RepeatedFieldSize\n else:\n def FieldSize(value):\n l = value.ByteSize()\n return tag_size + local_VarintSize(l) + l\n return FieldSize\n\n\n# --------------------------------------------------------------------\n# MessageSet is special.\n\n\ndef MessageSetItemSizer(field_number):\n \"\"\"Returns a sizer for extensions of MessageSet.\n\n The message set message looks like this:\n message MessageSet {\n repeated group Item = 1 {\n required int32 type_id = 2;\n required string message = 3;\n }\n }\n \"\"\"\n static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +\n _TagSize(3))\n local_VarintSize = _VarintSize\n\n def FieldSize(value):\n l = value.ByteSize()\n return static_size + local_VarintSize(l) + l\n\n return FieldSize\n\n\n# ====================================================================\n# Encoders!\n\n\ndef _VarintEncoder():\n \"\"\"Return an encoder for a basic varint value (does not include tag).\"\"\"\n\n local_chr = chr\n def EncodeVarint(write, value):\n bits = value & 0x7f\n value >>= 7\n while value:\n write(local_chr(0x80|bits))\n bits = value & 0x7f\n value >>= 7\n return write(local_chr(bits))\n\n return EncodeVarint\n\n\ndef _SignedVarintEncoder():\n \"\"\"Return an encoder for a basic signed varint value (does not include\n tag).\"\"\"\n\n local_chr = chr\n def EncodeSignedVarint(write, value):\n if value < 0:\n value += (1 << 64)\n bits = value & 0x7f\n value >>= 7\n while value:\n write(local_chr(0x80|bits))\n bits = value & 0x7f\n value >>= 7\n return write(local_chr(bits))\n\n return EncodeSignedVarint\n\n\n_EncodeVarint = _VarintEncoder()\n_EncodeSignedVarint = _SignedVarintEncoder()\n\n\ndef _VarintBytes(value):\n \"\"\"Encode the given integer as a varint and return the bytes. This is only\n called at startup time so it doesn't need to be fast.\"\"\"\n\n pieces = []\n _EncodeVarint(pieces.append, value)\n return \"\".join(pieces)\n\n\ndef TagBytes(field_number, wire_type):\n \"\"\"Encode the given tag and return the bytes. Only called at startup.\"\"\"\n\n return _VarintBytes(wire_format.PackTag(field_number, wire_type))\n\n# --------------------------------------------------------------------\n# As with sizers (see above), we have a number of common encoder\n# implementations.\n\n\ndef _SimpleEncoder(wire_type, encode_value, compute_value_size):\n \"\"\"Return a constructor for an encoder for fields of a particular type.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\n encode_value: A function which encodes an individual value, e.g.\n _EncodeVarint().\n compute_value_size: A function which computes the size of an individual\n value, e.g. _VarintSize().\n \"\"\"\n\n def SpecificEncoder(field_number, is_repeated, is_packed):\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n size = 0\n for element in value:\n size += compute_value_size(element)\n local_EncodeVarint(write, size)\n for element in value:\n encode_value(write, element)\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n encode_value(write, element)\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeField(write, value):\n write(tag_bytes)\n return encode_value(write, value)\n return EncodeField\n\n return SpecificEncoder\n\n\ndef _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value):\n \"\"\"Like SimpleEncoder but additionally invokes modify_value on every value\n before passing it to encode_value. Usually modify_value is ZigZagEncode.\"\"\"\n\n def SpecificEncoder(field_number, is_repeated, is_packed):\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n size = 0\n for element in value:\n size += compute_value_size(modify_value(element))\n local_EncodeVarint(write, size)\n for element in value:\n encode_value(write, modify_value(element))\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n encode_value(write, modify_value(element))\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeField(write, value):\n write(tag_bytes)\n return encode_value(write, modify_value(value))\n return EncodeField\n\n return SpecificEncoder\n\n\ndef _StructPackEncoder(wire_type, format):\n \"\"\"Return a constructor for an encoder for a fixed-width field.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\n format: The format string to pass to struct.pack().\n \"\"\"\n\n value_size = struct.calcsize(format)\n\n def SpecificEncoder(field_number, is_repeated, is_packed):\n local_struct_pack = struct.pack\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n local_EncodeVarint(write, len(value) * value_size)\n for element in value:\n write(local_struct_pack(format, element))\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n write(local_struct_pack(format, element))\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeField(write, value):\n write(tag_bytes)\n return write(local_struct_pack(format, value))\n return EncodeField\n\n return SpecificEncoder\n\n\ndef _FloatingPointEncoder(wire_type, format):\n \"\"\"Return a constructor for an encoder for float fields.\n\n This is like StructPackEncoder, but catches errors that may be due to\n passing non-finite floating-point values to struct.pack, and makes a\n second attempt to encode those values.\n\n Args:\n wire_type: The field's wire type, for encoding tags.\n format: The format string to pass to struct.pack().\n \"\"\"\n\n value_size = struct.calcsize(format)\n if value_size == 4:\n def EncodeNonFiniteOrRaise(write, value):\n # Remember that the serialized form uses little-endian byte order.\n if value == _POS_INF:\n write('\\x00\\x00\\x80\\x7F')\n elif value == _NEG_INF:\n write('\\x00\\x00\\x80\\xFF')\n elif value != value: # NaN\n write('\\x00\\x00\\xC0\\x7F')\n else:\n raise\n elif value_size == 8:\n def EncodeNonFiniteOrRaise(write, value):\n if value == _POS_INF:\n write('\\x00\\x00\\x00\\x00\\x00\\x00\\xF0\\x7F')\n elif value == _NEG_INF:\n write('\\x00\\x00\\x00\\x00\\x00\\x00\\xF0\\xFF')\n elif value != value: # NaN\n write('\\x00\\x00\\x00\\x00\\x00\\x00\\xF8\\x7F')\n else:\n raise\n else:\n raise ValueError('Can\\'t encode floating-point values that are '\n '%d bytes long (only 4 or 8)' % value_size)\n\n def SpecificEncoder(field_number, is_repeated, is_packed):\n local_struct_pack = struct.pack\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n local_EncodeVarint(write, len(value) * value_size)\n for element in value:\n # This try/except block is going to be faster than any code that\n # we could write to check whether element is finite.\n try:\n write(local_struct_pack(format, element))\n except SystemError:\n EncodeNonFiniteOrRaise(write, element)\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n try:\n write(local_struct_pack(format, element))\n except SystemError:\n EncodeNonFiniteOrRaise(write, element)\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeField(write, value):\n write(tag_bytes)\n try:\n write(local_struct_pack(format, value))\n except SystemError:\n EncodeNonFiniteOrRaise(write, value)\n return EncodeField\n\n return SpecificEncoder\n\n\n# ====================================================================\n# Here we declare an encoder constructor for each field type. These work\n# very similarly to sizer constructors, described earlier.\n\n\nInt32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder(\n wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize)\n\nUInt32Encoder = UInt64Encoder = _SimpleEncoder(\n wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize)\n\nSInt32Encoder = SInt64Encoder = _ModifiedEncoder(\n wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize,\n wire_format.ZigZagEncode)\n\n# Note that Python conveniently guarantees that when using the '<' prefix on\n# formats, they will also have the same size across all platforms (as opposed\n# to without the prefix, where their sizes depend on the C compiler's basic\n# type sizes).\nFixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<I')\nFixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<Q')\nSFixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, '<i')\nSFixed64Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED64, '<q')\nFloatEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED32, '<f')\nDoubleEncoder = _FloatingPointEncoder(wire_format.WIRETYPE_FIXED64, '<d')\n\n\ndef BoolEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a boolean field.\"\"\"\n\n false_byte = chr(0)\n true_byte = chr(1)\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n local_EncodeVarint(write, len(value))\n for element in value:\n if element:\n write(true_byte)\n else:\n write(false_byte)\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n if element:\n write(true_byte)\n else:\n write(false_byte)\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)\n def EncodeField(write, value):\n write(tag_bytes)\n if value:\n return write(true_byte)\n return write(false_byte)\n return EncodeField\n\n\ndef StringEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a string field.\"\"\"\n\n tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n local_len = len\n assert not is_packed\n if is_repeated:\n def EncodeRepeatedField(write, value):\n for element in value:\n encoded = element.encode('utf-8')\n write(tag)\n local_EncodeVarint(write, local_len(encoded))\n write(encoded)\n return EncodeRepeatedField\n else:\n def EncodeField(write, value):\n encoded = value.encode('utf-8')\n write(tag)\n local_EncodeVarint(write, local_len(encoded))\n return write(encoded)\n return EncodeField\n\n\ndef BytesEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a bytes field.\"\"\"\n\n tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n local_len = len\n assert not is_packed\n if is_repeated:\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag)\n local_EncodeVarint(write, local_len(element))\n write(element)\n return EncodeRepeatedField\n else:\n def EncodeField(write, value):\n write(tag)\n local_EncodeVarint(write, local_len(value))\n return write(value)\n return EncodeField\n\n\ndef GroupEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a group field.\"\"\"\n\n start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)\n end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)\n assert not is_packed\n if is_repeated:\n def EncodeRepeatedField(write, value):\n for element in value:\n write(start_tag)\n element._InternalSerialize(write)\n write(end_tag)\n return EncodeRepeatedField\n else:\n def EncodeField(write, value):\n write(start_tag)\n value._InternalSerialize(write)\n return write(end_tag)\n return EncodeField\n\n\ndef MessageEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a message field.\"\"\"\n\n tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n assert not is_packed\n if is_repeated:\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag)\n local_EncodeVarint(write, element.ByteSize())\n element._InternalSerialize(write)\n return EncodeRepeatedField\n else:\n def EncodeField(write, value):\n write(tag)\n local_EncodeVarint(write, value.ByteSize())\n return value._InternalSerialize(write)\n return EncodeField\n\n\n# --------------------------------------------------------------------\n# As before, MessageSet is special.\n\n\ndef MessageSetItemEncoder(field_number):\n \"\"\"Encoder for extensions of MessageSet.\n\n The message set message looks like this:\n message MessageSet {\n repeated group Item = 1 {\n required int32 type_id = 2;\n required string message = 3;\n }\n }\n \"\"\"\n start_bytes = \"\".join([\n TagBytes(1, wire_format.WIRETYPE_START_GROUP),\n TagBytes(2, wire_format.WIRETYPE_VARINT),\n _VarintBytes(field_number),\n TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)])\n end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP)\n local_EncodeVarint = _EncodeVarint\n\n def EncodeField(write, value):\n write(start_bytes)\n local_EncodeVarint(write, value.ByteSize())\n value._InternalSerialize(write)\n return write(end_bytes)\n\n return EncodeField\n", "license": "agpl-3.0"}
{"id": 2, "tokens": ["Halo", "dok", ",", "sy", "nurul", "sy", "sedang", "hamil", "10week", ".", "Saya", "mau", "tanya", "apakah", "facial", "wash", "dengan", "kandungan", "sbb", "boleh", "digunakan", "untuk", "ibu", "hamil", "?", "Facial", "Wash", "Sukin", "Signature", "Water", "(", "Aqua", ")", "Aloe", "Barbadensis", "Leaf", "Juice", "Sesamum", "Indicum", "(", "Sesame", ")", "Seed", "Oil", "Cetearyl", "Alcohol", "Glycerin", "Cetyl", "Alcohol", "Ceteareth-20", "Rosa", "Canina", "Fruit", "Oil", "(", "Rose", "Hip", ")", "Theobroma", "Cacao", "(", "Cocoa", ")", "Seed", "Butter", "Butyrospermum", "Parkii", "(", "Shea", "Butter", ")", "Simmondsia", "Chinensis", "(", "Jojoba", ")", "Seed", "Oil", "Persea", "Gratissima", "(", "Avocado", ")", "Oil", "Triticum", "Vulgare", "(", "Wheat", ")", "Germ", "Oil", "Tocopherol", "(", "Vitamin", "E", ")", "Equisetum", "Arvense", "Extract", "(", "Horsetail", ")", "Arctium", "Lappa", "Root", "Extract", "(", "Burdock", ")", "Urtica", "Dioica", "(", "Nettle", ")", "Leaf", "Extract", "Citrus", "Tangerina", "(", "Tangerine", ")", "Peel", "Oil", "Citrus", "Nobilis", "(", "Mandarin", "Orange", ")", "Peel", "Oil", "Lavandula", "Angustifolia", "(", "Lavender", ")", "Oil", "Vanillin", "Vanilla", "Planifolia", "Fruit", "Extract", "Citrus", "Paradisi", "(", "Grapefruit", ")", "Seed", "Extract", "Citric", "Acid", "Phenoxyethanol", "Benzyl", "Alcohol", "Limonene", "*", "Linalool", "Natural", "component", "of", "essential", "oils", "."], "ner_tags": [0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 18, 0, 0, 17, 18, 0, 0, 0, 0, 0, 11, 12, 11, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 17, 18, 0, 17, 0, 0, 0, 11, 0, 11, 12, 0, 17, 18, 0, 0, 17, 0, 17, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 0, 0, 17, 18, 0, 0, 0, 0, 11, 17, 18, 0, 0, 17, 18, 0, 17, 0, 0, 0, 11, 12, 11, 11, 12, 11, 0, 11, 0, 0, 0, 0, 0, 0]}
{"text": "When you were here before\nCouldnt look you in the eye\nYoure just like an angel\nYour skin makes me cry\nYou float like a feather\nIn a beautiful world\nI wish I was special\nYoure so fuckin special\nBut Im a creep\nIm a weirdo\nWhat the hell am I doing here?\nI dont belong here\nI dont care if it hurts\nI wanna have control\nI want a perfect body\nI want a perfect soul\nI want you to notice\nWhen Im not around\nYoure so fuckin special\nI wish I was special\nBut Im a creep\nIm a weirdo\nWhat the hell am I doing here?\nI dont belong here\nOh, oh\nShes running out the door\nShes running out\nShe run, run, run, run\nRun\nWhatever makes you happy\nWhatever you want\nYoure so fuckin special\nI wish I was special\nBut Im a creep\nIm a weirdo\nWhat the hell am I doing here?\nI dont belong here\nI dont belong here"}
{"text": "Karma police, arrest this man\nHe talks in maths, he buzzes like a fridge\nHes like a detuned radio\nKarma police, arrest this girl\nHer Hitler hairdo is making me feel ill\nAnd we have crashed her party\nThis is what youll get\nThis is what youll get\nThis is what youll get\nWhen you mess with us\nKarma police, Ive given all I can\nIts not enough, Ive given all I can\nBut were still on the payroll\nThis is what youll get\nThis is what youll get\nThis is what youll get\nWhen you mess with us\nFor a minute there\nI lost myself, I lost myself\nPhew, for a minute there\nI lost myself, I lost myself\nFor a minute there\nI lost myself, I lost myself\nPhew, for a minute there\nI lost myself, I lost myself"}
{"text": "A heart thats full up like a landfill\nA job that slowly kills you\nBruises that wont heal\nYou look so tired, unhappy\nBring down the government\nThey dont, they dont speak for us\nIll take a quiet life\nA handshake of carbon monoxide\nAnd no alarms and no surprises\nNo alarms and no surprises\nNo alarms and no surprises\nSilent, silent\nThis is my final fit\nMy final bellyache with\nNo alarms and no surprises\nNo alarms and no surprises\nNo alarms and no surprises, please\nSuch a pretty house\nAnd such a pretty garden\nNo alarms and no surprises\nNo alarms and no surprises\nNo alarms and no surprises, please"}
{"text": "Please, could you stop the noise?\nIm trying to get some rest\nFrom all the unborn chicken voices\nIn my head\nWhats that?\nWhats that?\nWhen I am king\nYou will be first against the wall\nWith your opinion\nWhich is of no consequence at all\nWhats that?\nWhats that?\nAmbition makes you look pretty ugly\nKicking, squealing, Gucci little piggy\nYou dont remember, you dont remember\nWhy dont you remember my name?\nOff with his head, man, off with his head, man\nWhy dont you remember my name?\nI guess he does\nRain down, rain down\nCome on, rain down on me\nFrom a great height\nFrom a great height, height\nRain down, rain down\nCome on, rain down on me\nFrom a great height\nFrom a great height, height\nThats it, sir, youre leaving \nThe crackle of pigskin \nThe dust and the screaming \nThe yuppies networking \nThe panic, the vomit \nThe panic, the vomit \nGod loves his children\nGod loves his children, yeah"}
{"text": "Wake from your sleep\nThe drying of your tears\nToday we escape, we escape\nPack and get dressed\nBefore your father hears us\nBefore all hell breaks loose\nBreathe, keep breathing\nDont lose your nerve\nBreathe, keep breathing\nI cant do this alone\nSing us a song\nA song to keep us warm\nTheres such a chill\nSuch a chill\nAnd you can laugh a spineless laugh\nWe hope your rules and wisdom choke you\nNow we are one in everlasting peace\nWe hope that you choke, that you choke\nWe hope that you choke\nThat you choke\nWe hope that you choke\nThat you choke"}
{"text": "A green plastic watering can\nFor a fake Chinese rubber plant\nIn a fake plastic earth\nThat she bought from a rubber man\nIn a town full of rubber plans\nTo get rid of itself\nIt wears her out\nIt wears her out\nIt wears her out\nIt wears her out\nShe lives with a broken man\nA cracked polystyrene man\nWho just crumbles and burns\nHe used to do surgery\nFor girls in the eighties\nBut gravity always wins\nAnd it wears him out\nIt wears him out\nIt wears him out\nIt wears\nShe looks like the real thing\nShe tastes like the real thing\nMy fake plastic love\nBut I cant help the feeling\nI could blow through the ceiling\nIf I just turn and run\nAnd it wears me out\nIt wears me out\nIt wears me out\nIt wears me out\nAnd if I could be who you wanted\nIf I could be who you wanted\nAll the time\nAll the time"}
{"text": "Im the next act\nWaiting in the wings\nIm an animal\nTrapped in your hot car\nI am all the days\nThat you choose to ignore\nYou are all I need\nYoure all I need\nIm in the middle of your picture\nLying in the reeds\nIm a moth\nWho just wants to share your light\nIm just an insect\nTrying to get out of the night\nI only stick with you\nBecause there are no others\nYou are all I need\nYoure all I need\nIm in the middle of your picture\nLying in the reeds\nIts all wrong, its all wrong, its all wrong\nIts all right, its all right, its all right\nIts all wrong, its all right\nIts all right, its all right"}
{"text": "In the deepest ocean\nThe bottom of the sea\nYour eyes\nThey turn me\nWhy should I stay here?\nWhy should I stay?\nId be crazy not to follow\nFollow where you lead\nYour eyes\nThey turn me\nTurn me on to phantoms \nI follow to the edge \nOf the earth \nAnd fall off\nYeah, everybody leaves \nIf they get the chance \nAnd this \nIs my chance\nI get eaten by the worms\nAnd weird fishes\nPicked over by the worms\nAnd weird fishes\nWeird fishes\nWeird fishes\nYeah, I...\nIll hit the bottom\nHit the bottom and escape\nEscape\nAnd I...\nIll hit the bottom\nHit the bottom and escape\nEscape"}
{"id": "r100621", "text": "Works fine for my new Samsung Galaxy S3\n\nWorks great. No problems with my Samsung Galaxy S3. It charges with no problems. It lights up when it is charging.", "label": "helpful"}
{"id": "r14077", "text": "Good phone\n\nFirst of all it is a good phone but I will tell what is lacks. It could have a few more features that can make it the best in the market. First no voice dial most new phones have it the phone. I had a panasonic in 2001 which had it. The external display can show a few more details than it does. It doesnot display the missed calls for more than 30 secs. One doesnt realise that they have missed call unless they open the phone. This is annoying. The manual is abysmally inadequate. It doesnt tell how to take self potraits or use the IR port. It doesnot tell how to delete wall papers or ringtones uploaded. Well I guess people like me who like to do things wihtout reading the manual can have a field day with this phone. Also it has a lot of ringtones, but i guess samsung has the impression that every body wants musical ringtones, and there are no ringtones in built which dont use its 40 polyphonic chord ringer except for the silly tmobile jingle. The pictures taken by the phone in low light have a reddish tinge to them.The display is very vibrant and is very bright. The sound quality is also very good. It has a great antenna (internal) I have crystal clear calls even in my basement where most of my other phones have lost the signal. The phone also has a very loud ringer which has an adjustable volume. The camera is great, the best I have seen on any phone. It has almost 9 megs of memory on but it is not shared among ringtones, the photos and the messages. I wish it had a memory card slot so that I could take a few more pictures at max resolution.Well if you want a fancy looking phone with loads of features i would recommend the Sony Ericsson T610. That phone leaves the sgh-e715 eating its dust. Also it is as heavy as this one and it has a lot of desirable features and it is cheaper than this one. But in spite of the all the things I do not like about the phone I will not return this phone because of the manual. It really allows me to play with the phone to discover new things. I really wanted to give it 3.5 * but amazon doesnt let me do that.", "label": "helpful"}
{"id": "r1452564", "text": "If you have a charger already...\n\nBought this SPECIFICALLY because I have a Motorola car charger already, AND a 3.5 mm AUX cable, so who needs to pay for ANOTHER one? I didn't. Don't know why folks are complaining, comes WITH a 3M foam backed dash mounting disk, and EVERYTHING you need to mount your phone. My Droid Razr Maxx, went in, the car nav/music big clunky button app came up, and I was, pardon the pun, READY TO ROLL! Anyway, if you want a place to put your Razr Maxx in the car, you HAVE all the cables, THIS is it! Exceeded expectations...and the rest of you folks...READ THE PRODUCT DESCRIPTION FIRST!", "label": "helpful"}
{"id": "r2937757", "text": "Terrible fit\n\nVery disappointed in the fit of this case. I would not recommend....... I will not make the mistake in not reading the reviews for the next purchase I make.", "label": "helpful"}
{"id": "r3149675", "text": "Nice\n\nSnug fit. Sharp looking. Nice grip. Not thrilled with the screen protector. It bubbles quite a bit but replacing this part is no big deal. Here's a tip: If you're going to take this case off then start at a corner at the top and pop it off. Then go to the bottom and pop off another corner of the case. This will help to lessen your chances of breaking the case as mentioned in some other reviews.", "label": "helpful"}
{"id": "r3165870", "text": "Didn't work right out of the package\n\nI bought these to use with an iPad. First, they didn't go into the Lightning port when it was in the case. (The Lightning end is too big for the opening in the case.) Okay, take it out of the case and try again. The cable went all the way in, but no indication the iPad was plugged in. Swapped it for my old cable and everything was fine.Nice idea, solid-looking cables, but they just didn't work.", "label": "unhelpful"}
{"id": "r1817906", "text": "Really good for Tracfone but some weird quirks\n\nI ordered this phone here on Amazon and soon after activating it and transferring my phone number and minutes, I had a weird \"black screen of death\" as I like to call it. It was a black screen with orange letters going on about an error code. I could not get the phone to respond to me at all, then eventually, it would reboot itself and all was fine. After this kept happening I got fed up and contacted Tracfone and they kindly replaced the phone for me. My replacement arrived quickly and I sent back the defective phone.My replacement phone works great. I love how slim it feels. I like the keys and find it much easier to text with than the LG800G I had before. THe LG800G was dying and no longer covered by Tracfone so I needed a new phone.WiFi works great. I have not had any major problems with it. You just need to activate the wifi and connect to a wireless network, otherwise you use your minutes to connect instead. I was able to transfer files via bluetooth easily to and from my old phone, from my boyfriend's phone and from my MacBook.Pros:- Light, slim, nice qwerty keys, great for phone calls and texting, bluetooth works great, camera is nice, wifi works great. It is pretty sturdy. I have dropped it a couple times and it held up well. Triple minutes for life!Cons:- Sometimes, when I dial a phone number, the numbers change order randomly. I have to scroll through to put them back in the order I need. Odd glitch that only happens with certain number combinations. Very odd.- When the phone is locked, 911 is dialed if 000 is hit and then OK. This setting cannot be changed. I always keep my phone locked in my purse or pocket and have had my phone put calls into 911 at least 3 times from my purse. I have had to call them back and apologize and am lucky they didn't get angry for the false calls.******************Update as of 2/20/13*******************I had way too many pocket or purse dials to the emergency line so I contacted Tracfone. First, they didn't understand what I was saying and had me reset factory settings on the phone. Then they said I needed to call them back when I had a 2nd line to go through troubleshooting steps. I called them back to be told, oh this is a feature of the phone and it can't be turned off. Isn't that what I tried to tell them in the first place? Ugh. They said there was nothing they could do so I told them, it looks like I need to buy a new phone. I am bummed because I really like a lot about this phone but I just can't deal with the quirk that frankly, can get me in a lot of trouble if I don't stop purse-dialing 911.", "label": "helpful"}
{"id": "r2315952", "text": "Where have you been my whole life?!\n\nI am so incredibly impressed with this product. I was actually surprised on how much I love it. I was at first dismayed at the lack of color choices for the SIII (I mean really, how typical that Apple users get all the cool colors and us Android folks are left with boring white. Unfair!) Aside from lack of case options I have absolutely no regrets. The pad itself is really small and sleek. It looks GOOD on the table next to the door. It has little stickies on the bottom to keep it in place which is also nice. The wire that leads from the charging pad to the wall is unobtrusive and even has a little built in cord winder which I thought was a great touch.Aside from that it is super easy to set up- plug in the pad, stick on the case and you're good to go. If you're on the fence and hate wires I would strongly suggest that you buy this- it's amazing!", "label": "helpful"}
{"id": "r2965553", "text": "home video (cheap) solution\n\nFor the kids school concerts/events this lens gets me close enough for home video footage. I didn't want to buy a separate video camera just for those \"distant\" events, since it's just one more thing to lug around and keep track of. I have a \"Windows\" HTC Arrive phone with some video stabilization, which is definitely needed for 8X optical zoom. I don't see any distortion or lighting issues that others have mentioned, although any zoom lens will typically require more light. My phone may automatically adjust for this and so I don't notice it.The spring loaded lens holder is not very tight and will move if bumped (thus not 5 stars)...and is difficult to re-align without unscrewing the lens and then screwing it back on again. To solve this problem I drew a few lines on my phone with a black marker and use those to re-align and it seems to work fine.When done, I pull off the holder and lens and put it in a zip-lock sandwich bag in my pocket.", "label": "helpful"}
{"id": "r806757", "text": "As Expected!\n\nRecived this phone. Works perfect. No problems. Have not yet checked the unlocked part as I plan to use internationally when I travel with other countries sim cards in the phone I. Works perfect with the prepaid tmob acct- $70/month for unlimited data, text, talk. Thats the best deal around. Buy an iphone and pay perhaps $120 or more for the same services (probably much more actally) or this. Pay for the phone in a few months. Insurder it for $58/yr with ensquared. DId an amazing amount of research and feel this is the best bang for the buck. The near $400 is tough upfront, but its the best investment youll make. Have to admit comming from Itunes and iphone, Android is not as easy and more fiddly, but also more customizable. My previous tmobile pay as you go sim went right in and then I upgraded that acct to the all you can have acct online without talking to anyone. Very easy and quick, same number and all. Would recommend this phone and plan.", "label": "helpful"}
{"id": "QuaRel_V1_Fr_0223", "answer_index": 1, "logical_forms": ["(infer (speed higher world1) (smoothness higher world2) (smoothness higher world1))", "(infer (speed higher world2) (smoothness higher world1) (smoothness higher world2))"], "logical_form_pretty": "qrel(speed, higher, world1) -> qrel(smoothness, higher, world2) ; qrel(smoothness, higher, world1)", "world_literals": {"world1": ["ice"], "world2": ["snow"]}, "question": "Mike was snowboarding on the snow and hit a piece of ice. He went much faster on the ice because _____ is smoother. (A) snow (B) ice"}