content
stringlengths 7
2.61M
|
---|
We all know that the Khan family really loves spending time to keep themselves fit. In fact, Kareena Kapoor Khan hit the gym soon after she delivered Taimur Ali Khan to lose the pregnancy fat and the actress was back in shape in no time. She continues to follow a healthy lifestyle and Saif Ali Khan too is quite like her when it comes to physical training and this gym selfie is a proof!
Recently, her nutritionist Rujuta Diwekar shared a picture of Kareena Kapoor Khan taking a selfie. Interestingly, the picture also features a rather dedicated Saif Ali Khan concentrating on weights. But what surprised everyone was the presence of Taimur Ali Khan who seems to be exploring the place and walking towards his father. While we had seen the little prince accompanying his dad for the latter’s gym sessions, here’s yet another proof of how the entire family likes to spend time at the gym.
Besides sharing this picture, Rujuta Diwekar also shared some tips that Kareena Kapoor Khan follows in real life to maintain her healthy lifestyle.
Coming to the film front, Kareena Kapoor Khan recently wrapped up work on Good News which also stars Akshay Kumar, Kiara Advani and Diljit Dosanjh. The film, directed by Raj Mehta, is produced by Karan Johar and is slated to release on September 6, 2019. Besides that she will also be a part of another Karan film Takht which stars Ranveer Singh, Vicky Kaushal, Alia Bhatt, Bhumi Pednekar, Janhvi Kapoor and Anil Kapoor.
On the other hand, Saif Ali Khan is busy with Hunter, Bhoot Police, Jawani Jaaneman, and Go Goa Gone 2 amongst others. The actor is also expected to return with Sacred Games 2 on Netflix.
Also Read: This Kareena Kapoor Khan and Saif Ali Khan ad will definitely leave you with a smile! |
Samuel Chase (New York politician)
Biography
Chase was born in Cooperstown, New York in 1789. He was educated locally, studied law, and was admitted to the bar in 1815. In 1818, he studied at the Litchfield Law School.
In addition to practicing law in Richfield, Chase was active in other business ventures; he was part-owner of a hotel and tavern, and was one of the original incorporators of the Otsego County Bank. He held various positions in local and county government, including postmaster of Richfield and the judicial position of Master in Chancery. From 1821 to 1829 he was District Attorney of Otsego County.
In 1826, Chase was elected to the 20th Congress as a supporter of John Quincy Adams. He served one term, 1827 to 1829, after which he returned to his Otsego County law practice.
Death and burial
Chase died in Richfield on August 3, 1838, and was buried at Lakeview Cemetery in Richfield. Chase's grave marker indicates that he died in 1839; this is clearly in error, since contemporary newspaper accounts and the probate process for his estate give his year of death as 1838.
Family
In 1828, Chase married in Washington, DC Mary Frances Whetcroft, the daughter of William Whetcroft and Anne Winchester Whetcroft of Annapolis, Maryland. After Chase's death, Mary Whetcroft married Philetus Allen of Springville.
Chase's children included Frank Chase (September 18, 1838—January 14, 1902), who was born the month following Chase's death. Frank Chase was a graduate of Albany Law School, and resided in Concord and Springville. In addition to practicing law, he was involved in local politics and government, including service as Springville's town supervisor and a justice of the peace. |
How flies are flirting on the fly Background Flies have some of the most elaborate visual systems in the Insecta, often featuring large, sexually dimorphic eyes with specialized bright zones that may have a functional role during mate-seeking behavior. The fast visual system of flies is considered to be an adaptation in support of their advanced flight abilities. Here, we show that the immense processing speed of the flies photoreceptors plays a crucial role in mate recognition. Results Video-recording wing movements of abdomen-mounted common green bottle flies, Lucilia sericata, under direct light at 15,000 frames per second revealed that wing movements produce a single, reflected light flash per wing beat. Such light flashes were not evident when we video-recorded wing movements under diffuse light. Males of L. sericata are strongly attracted to wing flash frequencies of 178 Hz, which are characteristic of free-flying young females (prospective mates), significantly more than to 212, 235, or 266 Hz, characteristic of young males, old females, and old males, respectively. In the absence of phenotypic traits of female flies, and when given a choice between light emitting diodes that emitted either constant light or light pulsed at a frequency of 110, 178, 250, or 290 Hz, males show a strong preference for the 178-Hz pulsed light, which most closely approximates the wing beat frequency of prospective mates. Conclusions We describe a previously unrecognized visual mate recognition system in L. sericata. The system depends upon the sex- and age-specific frequencies of light flashes reflecting off moving wings, and the ability of male flies to distinguish between the frequency of light flashes produced by rival males and prospective mates. Our findings imply that insect photoreceptors with fast processing speed may not only support agile flight with advanced maneuverability but may also play a supreme role in mate recognition. The low mating propensity of L. sericata males on cloudy days, when light flashes from the wings of flying females are absent, seems to indicate that these flies synchronize sexual communication with environmental conditions that optimize the conspicuousness of their communication signals, as predicted by sensory drive theory. Electronic supplementary material The online version of this article (doi:10.1186/s12915-016-0342-6) contains supplementary material, which is available to authorized users. Background Mate-seeking animals typically rely on sexual communication signals that facilitate mate encounters. While these signals can be diverse (olfactory, visual, acoustic, vibratory, tactile) and may involve multiple sensory modalities, certain taxonomic groups use specific primary modalities of communication. Flies (Diptera) have some of the most advanced visual systems in the Insecta, often featuring large, sexually dimorphic eyes with specialized "bright zones" that may have a functional role during mate-seeking behavior. The fast visual system of flies is considered an adaptation that evolved in support of their advanced flight abilities, demanding superb visual acuity to gauge distance traveled and to avoid collisions. Blow flies (Calliphoridae) exploit visual cues when they forage, seek oviposition resources, or pursue prospective mates. Males have larger eyes than females, suggesting that females send and males perceive the visual signals or cues. Occupying vantage points in their territories, males survey rapid flybys of females and males, and then decide whether to fend off rival males or pursue prospective female mates. The design and processing speed of the flies' compound eyes allow us to infer functional linkage of the visual communication signals that females send and males perceive. Blow flies possess rapid temporal visual discrimination; the flicker fusion threshold (the frequency at which blinking lights are perceived to be constant ) of the common green bottle fly Lucilia sericata (Diptera: Calliphoridae) exceeds 180 Hz, and may double at temperatures above 30°C, as shown for the blue bottle fly Calliphora vicina, enabling these flies to resolve extremely fast or brief visual stimuli. This ability has been interpreted as an adaptation to support the flies' advanced flight and collision-avoidance capabilities. If this adaptation were to function also in mate recognition, one would expect an extremely fast and specific visual signal produced by females. We show that L. sericata males distinguish between the rates of light flashes reflected off the moving wings of female and male flies, and are most strongly attracted to flash frequencies characteristic of young females that are prospective mates. Results Our search for visual mate recognition cues took into account that mate-seeking males pursue flying females. To test whether wing movement of females affects mate recognition by males, we mounted two live females side by side (Fig. 1a), immobilized the wings of one randomly assigned female and recorded the number of alighting responses by males on or near each female. Significantly more alighting responses by males on or near females that could move their wings than on females that could not (mean ± SE: 34.10 ± 3.76 vs. 20.60 ± 3.79; n = 10, t = -4.43, t crit. two-tail = 2.26, P = 0.002; Fig. 2a; Additional file 1: Data S1) revealed that wing movements by females contribute to mate selection by males. To visualize optic effects associated with moving wings of L. sericata females, we video-recorded the wing movement of abdomen-mounted flies under direct light at 15,000 frames per second (Fig. 1b), and found that wing movements produce a single, reflected, light flash per wing beat (Fig. 3a-d). Such light flashes (strong light reflections) were not evident ( Fig. 3e-h) when we videorecorded wing movements under diffuse light (Fig. 1c), or when we took photographs of L. sericata wings outdoors under a cloudy sky (Fig. 4a). Butterflies and blow flies (, this study) exhibit low mating propensity on overcast days when otherwise direct illumination from the sun becomes diffuse, and thus reduces flash effects. These observations support the hypothesis that light reflected from the wings produces beacons that contribute to mate recognition. Fig. 1 Graphical illustrations of experimental designs. a T-bar (vertical stand: 3.5 cm tall; horizontal bar: 7.5 cm long) with two Lucilia sericata flies mounted on their abdominal ventrum to leave their legs without support and thus induce a wing fanning response. b, c Set-up for high-speed video recordings of an abdomen-mounted, wing-fanning fly under direct light (b) or diffuse light (c) provided by one or four 100-watt cool lightemitting diodes (LEDs; see Methods for further details). d Mounted LEDs producing pulsed or constant light directed on to the immobilized wings of paired abdomen-mounted flies. e Black acrylic sphere holding a white-light LED directed upward; sanding the lens ensured that the emitted light was visible to flies from many viewing angles rather than from the narrow viewing angle that the lens otherwise creates We tested this hypothesis using two approaches. First, we mounted two live female flies on an aluminum T-bar (Fig. 1d), immobilized their wings, and illuminated each female by a light emitting diode (LED) (Additional file 2: Figure S1a), one that produced light pulses at 190 Hz approximating the wing flash frequency of a flying female, and the other that produced constant light at the same intensity. Second, we isolated the pulsed-light effects from phenotypic traits of female flies by mounting one live female fly and one live male fly side by side (Fig. 1d), immobilizing their wings and illuminating the wings of the male by the 190-Hz light pulses while keeping the wings of the paired female under constant illumination. In both experiments, we placed the T-bar with the two mounted flies into a bioassay cage containing 50 male flies and recorded the numbers of alighting responses on either fly in each pair. In both experiments, the female or male fly exposed to pulsed light (190 Hz) received many more alighting responses (mean ± SE) by males than did the fly illuminated by constant light (Exp. 2: 27.8 ± 4.32 vs. 0.9 ± 0.31; n = 10, t crit. two-tail = 2.26, t = 6.44, P < 0.001; Exp. 3: 18.1 ± 2.98 vs. 0.8 ± 0.29; n = 10, t crit. two-tail = 2.26, t = 5.54, P < 0.001; Figs. 2b, c; Additional file 1: Data S1). (Fig. 1a) that were able, or not, to move their wings (a), or that could not move their wings and were illuminated by pulsed or constant light ( Fig. 1d) (b, c). In each experiment, an asterisk (*) indicates a significant preference for a test stimulus (t-test; P < 0.05) While these results support the hypothesis that light pulses contribute to mate recognition, such signals or cues can be functional in mate recognition only if they differ in frequency by sex and age of free-flying individuals. Only then would a male fly be able to distinguish between rival males and prospective mates traversing his territory. We tested this hypothesis by filming young and old male and female flies in free flight, using a Phantom Miro 3 high-speed camera at a rate of 15,325 frames per sec. For each recording event, we placed 50 young or 50 old male or female flies into a wire mesh cage fitted with a cool-white LED. Following each recording, which typically captured 1-6 flies in free flight, we proceeded to the next recording with a new set of flies in another cage. Analyzing the video-recorded data files (e.g.; Additional file 3: Video S1; Additional file 4: Video S2), we found differences in the frequency of light flashes reflected off the wings of free-flying young and old females and young and old males (one-way ANOVA; F 3,46 = 96.22, P < 0.001; Additional file 1: Data S1). Young females had a mean (± SE) flash frequency of 178.72 Hz (±2.86 Hz), which was significantly lower than that of young males (212.0 ± 4.18 Hz), old females (235.08 ± 2.58 Hz), and old males (265.78 ± 4.53 Hz) (Fig. 5a). Because L. sericata males seek young (2-to 4-day-old) females as prospective mates, the slower wing flash frequency from young females than from young males, or older individuals of either sex, could be a phenotypic trait of reproductively capable females. If the lower wing flash frequency of young females is the key signal or cue for mate recognition by mateseeking males, one would expect males to respond to this frequency even in the absence of live females and to distinguish between flash frequencies that are true mate cues (178 Hz; see above) and those that are not. By eliminating females from the experimental design, we isolated the light flash effect as the test variable. We ran four experiments in parallel and recorded alighting responses by males on paired black acrylic spheres (Fig. 1e) instead of paired mounted female flies. Each sphere in each pair held a white-light LED, one emitting constant light, the other emitting light pulses at a frequency of Fig. 4 Photographs of Lucilia sericata wings mounted on hemostatic clamps and exposed to diffuse sunlight (a) and direct sunlight (b-f) on a day with periods of sunshine and clouds. In sub-panels b-f, note the bright sunlight reflected off the right wing in each pair 290, 250, 178, or 110 Hz. The 250-Hz pulses represent light flashes produced by flying old females and males (see above). We selected 290-and 110-Hz pulses to test the response of males to pulse frequencies that are well above or below the wing flash frequencies produced by flying conspecifics. Males did not respond to light pulsed at 290 or 110 Hz in greater numbers than to constant light (Fig. 5b). Spheres holding an LED emitting 250-Hz light pulses received twice as many alighting responses by males than did the spheres with an LED emitting constant light (Exp. 6: 37.5 ± 4.97 vs. 19.37 ± 2.54; n = 8, t crit. two-tail = 2.37, t = 4.59, P = 0.003; Fig. 5b). Spheres with an LED emitting the 178-Hz pulses indicative of prospective mates received not only 4.2 times more alighting responses by males than did the paired spheres with an LED emitting constant light (Exp. 7: 70.3 ± 8.93 vs. 15.67 ± 3.08; n = 9, t crit. two-tail = 2.31, t = 7.21, P < 0.001) (Fig. 5b), but they also received significantly more alighting responses than any of the other light-pulsing LEDs (one-way ANOVA; F 3,31 = 13.55, P < 0.001; Additional file 1: Data S1). Together, these results reveal that L. sericata males do not simply prefer pulsed light to a constant light, but also prefer pulsed light that occurs at frequencies corresponding to the wing flash frequency of young females that are prospective mates. To ascertain that L. sericata wing flashes are clearly visible even in diverse natural habitats and thus can indeed function in mate recognition, we took photographs of L. sericata wings exposed to direct sunlight in outdoor settings, and video-recorded at high speed free flying L. sericata exposed to direct sunlight. Sunlightreflecting stationary (mounted) wings produced bright visible cues (Fig. 4b-f ), appearing 2-3 times brighter than the paired wing positioned at an angle not conducive to reflecting the sunlight (Additional file 2: Figure S1b). In laboratory measurements, the spectral power distribution of light reflected by L. sericata wings closely resembled that of the incident light (Additional file 2: Figure S1c). Moreover, wings of L. sericata females free flying in an outdoor setting produced repeated flashes of light that contrasted well even against a complex background of plant foliage (Additional file 5: Video S3; Additional file 6: Video S4). Discussion Moving wings are thought to mediate long-range detection of potential mates in some butterflies and damselflies. In these insects, light flash effects coupled with other visual effects of moving wings such as iridescence, UV, and polarized light reflections are hypothesized to contribute to mate recognition. In our study, we have decoupled light flash effects from other effects of moving wings, demonstrating that male flies respond to the light flashes per se when they seek prospective mates. By showing that L. sericata males respond to LED light pulses in the absence of females, we provide evidence that the frequency of pulsed light is the key mate recognition cue in L. sericata and that this cue is independent of structural and color characteristics of female wings. Unlike static signals or cues, flashing signals affect improved visibility. This is evident, for example, in Morpho butterflies whose wings produce light flashes that are reported to be visible from low-flying aircraft and in Heliconius butterflies whose wings produce polarized light flashes that stand out in complex forest habitats. Compared to these butterfly light flashes, the light flashes produced by L. sericata wings are not only highly visible in direct sunlight ( Fig. 4; Additional file 5: Video S3; Additional file 6: Video S4), they are also very rich in information content. Divergent flash rates produced by young and old females (Fig. 5a), and the males' ability to "read" these rates (Fig. 5b), allow for the conveyance of information that enables informed mate assessment. Exploitation of "rate-based" signals or cues may, in fact, be commonplace in the Insecta. For example, rates of flashing light signals produced by bioluminescent fireflies likely convey important information about mate suitability. Sensory perception of light flashes produced by moving wings seems to be facilitated by the functional design, neural circuitry, and processing speed found in the sexually dimorphic compound eyes of several species of flies. For example, males but not females of the blow fly Chrysomya megacephala and the hover fly Eristalis tenax have large ommatidial facets in their dorsal frontal eye region that form a "bright zone" believed to be capable of increased light capture. This bright zone is not linked to enhanced resolution, but is deemed to allow males to search for females at low light or from great distances in bright light. We hypothesize that this bright zone may also help males detect the flashing lights of prospective mates. Moreover, the fast photoreceptors of calliphorid flies may not only underlie adaptations of a visual system that has evolved to support advanced flight and collision-avoidance capabilities, but also may enable a superior function in mate recognition. The temporal encoding ability of L. sericata males was amply sufficient to distinguish between light flash frequencies of prospective mates (178 Hz) and rival males (250 Hz) (Fig. 5b). While numerical competence is known for mammals, amphibians, birds, fish, and some invertebrates such as ants, the numerical recognition and signal-processing speed exhibited by L. sericata males seem to top currently known records. The logical framework offered by the sensory drive theory predicts functional links between signal design and presentation such that signal conspicuousness is maximized relative to background noise or environmental conditions. Our data on L. sericata are in complete agreement with this prediction. Unlike the iridescent light flashes produced by Hypolimnas bolina butterfly wings that are most conspicuous only from a narrow perspective, the wing flashes produced by flying L. sericata females are visible beacons ( Fig. 4; Additional file 5: Video S3; Additional file 6: Video S4) that are detectable from all directions, allowing a territorial male fly to rapidly notice a female irrespective of her flight trajectory, particularly when he is perching at a vantage point that optimizes contrast between fly flash signals and background. Remarkably, the flash frequency is so informative that it allows the territorial male to distinguish between old and young females, and to pursue primarily young females that are preferred mates. Furthermore, the low mating propensity of L. sericata on overcast days, when diffuse sunlight renders light reflections off wings inconspicuous (Fig. 4a), appears to show that these flies time their sexual communication and mating activities in accordance with environmental conditions that optimize the conspicuousness of their sexual communication signals. Conclusion In conclusion, we describe a previously unidentified visual mate recognition system in the common green bottle fly. The system depends upon both the sex-and agespecific frequencies of light flashes reflecting off moving wings, and the ability of male flies to distinguish between the frequency of light flashes produced by rival males and prospective mates. Our findings imply that insect photoreceptors with fast processing speed may not only support agile flight with advanced maneuverability but may also play a supreme role in mate recognition. With emerging evidence that light flash mate cues also occur in other insects (unpublished data), there may be an opportunity for optimizing light traps for capture of specific nuisance insects in urban and industrial settings. Experimental insects We reared L. sericata in the insectary at Simon Fraser University, starting a new colony with field-collected wild flies every 12 months. We cold-sedated flies within 24 h following eclosion, separated them by sex, and kept them in groups of 50 males or 50 females in separate wire mesh cages (45 45 45 cm; BioQuip®, Compton, CA, USA) under a L16:D8 photoperiod, 30-40% relative humidity, and 23-25°C. We provisioned flies with water, milk powder, sugar, and liver ad libitum and used 2-to 7-day-old flies in bioassays. Responses by males to mounted females, one able to wing-fan, the other with wings glued to her body For each replicate of Experiment 1 (n = 10), we CO 2 -sedated two live female flies for 30 s, and then mounted them with cyanoacrylate adhesive on their abdominal ventrum, at opposite ends of a 7.5-cm-long aluminum T-bar (Fig. 1a). We applied a small amount of cyanoacrylate to the wing base of one randomly assigned female to immobilize her wings, and applied the same amount of adhesive to the abdomen of the other female, allowing her wings to move freely. We placed the T-bar with the two females in a wire mesh bioassay cage (45 45 45 cm; BioQuip®) containing 50 male flies. The cage was illuminated from above with a full spectrum light source (two horizontal fluorescent bulbs: Philips, plant & aquarium (40 W); Sylvania, Daylight Deluxe (40 W)) (Additional file 2: Figure S1a). To minimize light reflection, we covered the metal cage floor and T-bar stand with SunWorks® black construction paper and black velvet (Suzhou Joytex International Co. Ltd., Jiangsu, China), respectively. During each 40-min bioassay, we recorded the number of alighting events by males on or near a female followed by physical contact with her. We analyzed the mean numbers of alighting responses by males on females with wings either mobile or immobilized by a paired two sample for means t-test. Do moving wings produce flashes of reflected light under point source illumination? We recorded the wing movement of abdomen-mounted male and female flies (Fig. 1b) in slow motion using a Phantom Miro 4 camera (Vision Research, Wayne, NJ, USA), recording at 15,000 frames per second, a 512 512 pixel resolution, and a 20-s exposure time. To illuminate the mounted fly, we used a white 100-watt LED (6500 K; Zongshan Ltd., Guangdong, China) mounted to a computer CPU heat sink for cooling (Thermaltake Heatpipe, Thermaltake Technology Co. Ltd, Taipei, Taiwan), and powered via a 32 V 5A stabilized, adjustable DC power supply (Gopher Technologies, Yantian, Fenggang, Dongguan, Guangdong, China). Do moving wings produce flashes of reflected light under diffuse illumination? We used the same high-speed video technology as described above, except that we exposed the mounted fly to diffuse instead of point source light. We placed the fly inside a ping pong ball "diffuser" (Fig. 1c) and illuminated it by four cool white 100-watt LEDs (see above). Responses by males to paired mounted females, both with their wings immobilized but one with pulsed light reflecting off her wings For each replicate (n = 13) of Experiment 2, we mounted two live female flies on an aluminum T-bar (Fig. 1d) and immobilized the wings of each female with cyanoacrylate adhesive. We illuminated one randomly assigned female from above by a light emitting diode (LED, Optek Technology Inc., Carrollton, Texas 75006, USA) (Additional file 2: Figure S1a) mounted 3 cm above the female (Fig. 1d) and which produced 5-Volt, white-light pulses at a frequency of 190 Hz and a duty cycle of 3%. The pulse frequency of 190 Hz was approximately mid-way between the light-flash frequencies of flying 2-day-old female and male flies. We illuminated the control female by a second LED of the same type that produced constant light. We considered two alternative approaches to the illumination design of this experiment. We could have set the pulsed-light LED and the constant-light LED to deliver either equal total light intensity (root mean squared) or equal maximum light intensity (peak voltage). We chose the latter (conservative) approach because, at a 3% duty cycle ("on" vs. "off" ratio), the pulsed-light LED delivers only about 3% of the total light that the constant-light LED delivers. Thus, to the human eye, the pulsed-light LED appears as a constant dim light, whereas the constant-light LED appears as a constant bright light; to fly photoreceptors, in contrast, the pulsed-light LED appears as an intermittent (pulsing) light with a light intensity matching that of the constantlight LED. For each replicate, we placed the T-bar with the two females into a wire mesh bioassay cage containing 50 male flies. During 40 min in each replicate, we recorded the numbers of alighting responses by these 50 male flies on each female, and analyzed the mean numbers of alighting responses by a paired two sample for means t-test. Responses by males to paired male and female flies, both with their wings immobilized, and pulsed light reflecting off the male's wings In each replicate of Experiment 3 (n = 10), we mounted one live female fly and one live male fly 7 cm apart on an aluminum T-bar (Fig. 1d), and immobilized the wings of each fly with cyanoacrylate adhesive. We illuminated the male from above by an LED (Fig. 1d) that produced 5-Volt, white-light pulses at a frequency of 190 Hz and a duty cycle of 3%. We illuminated the female by a second LED of the same type that produced constant light at equal maximum intensity as the first LED. During 40 min in each replicate, we recorded the number of alighting responses by 50 males on the mounted male and female fly, analyzing the mean number of alighting responses on the male and female by a t-test. Light flash frequencies associated with age and sex of flying individuals The objective of Experiment 4 was to determine whether the numbers of light flashes reflected off the wings of free-flying flies differ in accordance with age or sex. We filmed 2-day-old (young) and 7-day-old (old) male and female flies in free flight using a Phantom Miro 3 highspeed camera (Vision Research) at a rate of 15,325 frames per second and a 34-s exposure time imaged through a Canon 100-mm f2.8 L macro lens (Canon Canada Inc., Vancouver, BC V6C-3 J1, Canada) fitted to a 36-mm extension tube. For each recording event, we placed 50 young or 50 old male or female flies into a wire mesh cage (45 45 45 cm) housing a 100-Watt (approximately 9000 Lumen), cool-white (5000-6000 Kelvin) LED, which was driven by a 32-Volt switchingpower supply (model CPS-3010, Gopher Technologies, Yantian, Fenggang Town, Dongguan, Guangdong, China). Once the camera and light were turned on, we lightly tapped the cage to induce take-off and flight by resting flies. In video-recorded data files, we counted the number of light flashes reflected within one second off the wings of free-flying young females (n = 11), young males (n = 12), old females (n = 18), and old males (n = 9), and analyzed light-flash frequencies of young and old females and of young and old males by one-way ANOVA followed by the Tukey test for comparisons of means. Ability of males to discriminate between LED-pulsed light of varying frequencies To determine whether mate-seeking males can distinguish between different frequencies of pulsed light, parallel-run behavioral Experiments 5-8 (n = 9, 8, 9, and 9, respectively) tested alighting responses by males on paired black acrylic spheres (1.77 cm diameter; supplier unknown; Fig. 1e). We mounted the spheres on clamps 12 cm apart and 12 cm above the floor of the bioassay cage containing 50 male flies. A central hole (0.52 cm) in each sphere accommodated an upward pointing LED (Fig. 1e), the rounded lens of which was sanded down to be flush with the sphere's surface. Sanding the lens ensured that the emitted light was visible to flies from many viewing angles rather than from the narrow viewing angle that the lens otherwise creates. By random assignment, one LED in each pair emitted constant light; the other emitted light pulsed at 290 Hz (Experiment 5), 250 Hz (Experiment 6), 178 Hz (Experiment 7), or 110 Hz (Experiment 8). We selected the frequencies of 290 Hz and 110 Hz to test the response of males to pulse frequencies that are well above or below the wing flash frequencies produced by flying common green bottle flies. In each of Experiments 5-8, we analyzed the mean numbers of alighting responses by males on paired spheres holding LEDs emitting constant light or pulsing light by a paired two sample for means t-test. We analyzed differences in alighting responses based on the frequency of pulsed light by one-way ANOVA followed by the Tukey test for comparisons of means. Visibility of light flashes reflected off the wings of freeflying flies video recorded outdoors under direct sunlight To document the effect of sunlight reflecting off the wings of a free flying L. sericata, we took high-speed video recordings of flies traversing a south-facing slope with plant cover under direct, mid-day sun under a partially cloudy sky. For these recordings, we used a FAS-TCAM Mini AX200 type 900 K-M camera (Photron USA Inc., San Diego, CA 92126, USA) fitted with a Canon macro lens (100 mm; f2.8 L) at f5.6, capturing images at 15,000 frames per second, a 1/15000 exposure time, and a 768 512 pixel resolution. Effect of natural sunlight reflecting, or not, off L. sericata wings We carefully removed wings from a 1-day-old female fly, mounted them on hemostatic clamps positioned by articulated holders (Noga Engineering Ltd., Shlomi 22832, Israel), and angled the wings such that the right wing, but not the left wing, reflected sunlight back toward the camera. We photographed the wings under cloudy conditions (Fig. 4a) and under sunny conditions (Fig. 4b-f), keeping the wings near minimum focus from the lens, with various distances to background foliage. We took the photographs with a Canon EOS 5D Mark II Full Frame DSLR camera fitted with a Canon EF 100 mm f2.8 L macro lens, using the following parameters: 1/ 50 sec exposure, f29; 1/160 sec exposure, f18; 1/ 160 sec exposure, f22; 1/80 sec exposure, f29; 1/ 125 sec exposure, f29; and 1/60 sec exposure, f 29. We converted RAW images to 16-bit uncompressed TIFF files using open-source RAW image-decoding software (DCRAW; ) in a manner that maintained pixel linearity. We then examined the images in ImageJ, separated the green color channel, manually selected wings, and graphed histograms of pixel values. |
Analysis of the Large-Signal Circuit Model for Quantum Cascade Laser A large-signal circuit model of QCL is described, which is based on a set of rate equations by analyzing the unipolar behavior of electrons in quantum well, and the frequency response characteristic of QCL is got by the circuit simulation of PSPICE Program. Consequently some factors that can affect the modulation characteristic of QCL have been analyzed. |
<filename>src/broker/types.rs
use colored::Colorize;
use std::marker::Send;
use crate::common::{Arc, Keychain, Mutex, Error};
use crate::contacts::{Address, AddressType, GrinboxAddress};
use crate::wallet::api::{Foreign, Owner};
use crate::wallet::types::{NodeClient, Slate, VersionedSlate, TxProof, WalletBackend};
use crate::wallet::Container;
use crate::cli_message;
pub enum CloseReason {
Normal,
Abnormal(Error),
}
pub trait Publisher: Send {
fn post_slate(&self, slate: &VersionedSlate, to: &Address) -> Result<(), Error>;
}
pub trait Subscriber {
fn start<W, C, K, P>(&mut self, handler: Controller<W, C, K, P>) -> Result<(), Error>
where
W: WalletBackend<C, K>,
C: NodeClient,
K: Keychain,
P: Publisher,
;
fn stop(&self);
fn is_running(&self) -> bool;
}
pub trait SubscriptionHandler: Send {
fn on_open(&self);
fn on_slate(&self, from: &Address, slate: &VersionedSlate, proof: Option<&mut TxProof>);
fn on_close(&self, result: CloseReason);
fn on_dropped(&self);
fn on_reestablished(&self);
}
pub struct Controller<W, C, K, P>
where
W: WalletBackend<C, K>,
C: NodeClient,
K: Keychain,
P: Publisher,
{
name: String,
owner: Owner<W, C, K>,
foreign: Foreign<W, C, K>,
publisher: P,
}
impl<W, C, K, P> Controller<W, C, K, P>
where
W: WalletBackend<C, K>,
C: NodeClient,
K: Keychain,
P: Publisher,
{
pub fn new(
name: &str,
container: Arc<Mutex<Container<W, C, K>>>,
publisher: P,
) -> Result<Self, Error> {
Ok(Self {
name: name.to_string(),
owner: Owner::new(container.clone()),
foreign: Foreign::new(container),
publisher,
})
}
fn process_incoming_slate(
&self,
address: Option<String>,
slate: &mut Slate,
tx_proof: Option<&mut TxProof>,
) -> Result<bool, Error> {
if slate.num_participants > slate.participant_data.len() {
if slate.tx.inputs().len() == 0 {
// TODO: invoicing
} else {
*slate = self.foreign.receive_tx(slate, None, address, None)?;
}
Ok(false)
} else {
self.owner.finalize_tx(slate, tx_proof)?;
Ok(true)
}
}
}
impl<W, C, K, P> SubscriptionHandler for Controller<W, C, K, P>
where
W: WalletBackend<C, K>,
C: NodeClient,
K: Keychain,
P: Publisher,
{
fn on_open(&self) {
// cli_message!("Listener for {} started", self.name.bright_green());
}
fn on_slate(&self, from: &Address, slate: &VersionedSlate, tx_proof: Option<&mut TxProof>) {
let version = slate.version();
let mut slate: Slate = slate.clone().into();
/*if slate.num_participants > slate.participant_data.len() {
cli_message!(
"Slate [{}] received from [{}] for [{}] grins",
slate.id.to_string().bright_green(),
display_from.bright_green(),
amount_to_hr_string(slate.amount, false).bright_green()
);
} else {
cli_message!(
"Slate [{}] received back from [{}] for [{}] grins",
slate.id.to_string().bright_green(),
display_from.bright_green(),
amount_to_hr_string(slate.amount, false).bright_green()
);
};*/
if from.address_type() == AddressType::Grinbox {
GrinboxAddress::from_str(&from.to_string()).expect("invalid grinbox address");
}
let result = self
.process_incoming_slate(Some(from.to_string()), &mut slate, tx_proof)
.and_then(|is_finalized| {
if !is_finalized {
let id = slate.id.clone();
let slate = VersionedSlate::into_version(slate, version);
self.publisher
.post_slate(&slate, from)
.map_err(|e| {
cli_message!("{}: {}", "ERROR".bright_red(), e);
e
})
.expect("failed posting slate!");
cli_message!(
"Slate {} sent back to {} successfully",
id.to_string().bright_green(),
from.stripped().bright_green()
);
}
/*else {
cli_message!(
"Slate [{}] finalized successfully",
slate.id.to_string().bright_green()
);
}*/
Ok(())
});
match result {
Ok(()) => {}
Err(e) => cli_message!("{}", e),
}
}
fn on_close(&self, reason: CloseReason) {
match reason {
CloseReason::Normal => {
//println!("Listener for {} stopped", self.name.bright_green())
},
CloseReason::Abnormal(_) => cli_message!(
"Listener {} stopped unexpectedly",
self.name.bright_green()
),
}
}
fn on_dropped(&self) {
cli_message!("Listener {} lost connection. it will keep trying to restore connection in the background.", self.name.bright_green())
}
fn on_reestablished(&self) {
cli_message!(
"Listener {} reestablished connection.",
self.name.bright_green()
)
}
} |
<reponame>thinkoid/Sprout
/*=============================================================================
Copyright (c) 2011-2019 <NAME>
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_RANGE_ALGORITHM_IS_INCREASING_HPP
#define SPROUT_RANGE_ALGORITHM_IS_INCREASING_HPP
#include <sprout/config.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/algorithm/is_increasing.hpp>
namespace sprout {
namespace range {
//
// is_increasing
//
template<typename ForwardRange>
inline SPROUT_CONSTEXPR bool
is_increasing(ForwardRange const& range) {
return sprout::is_increasing(sprout::begin(range), sprout::end(range));
}
} // namespace range
} // namespace sprout
#endif // #ifndef SPROUT_RANGE_ALGORITHM_IS_INCREASING_HPP
|
Visual Humor through Internet Memes (II) From harmless humour to the discriminatory potential of (anti)memes. Case Study: The Transgender Bathroom Debate After pointing out - in the first part of this study - the persuasive quality of memes, once they are created, re-mixed and shared publicly, we attempt to further analyze and discuss the social and ethical implications of this type of humour, meant for mainstream entertainment and specific to the digital era, while insisting on the relevance of its reception; when the derision hides, in fact, hostility, the use of humour can affect the image of vulnerable groups and can contribute to the exclusion of their members. The attached case study presents and analyses anti-trans memes created and shared during a notorious legislative episode in the United States, referring to the use of gender-inclusive public restrooms. This episode has provoked controversies in the American public space and has served as a new reason for discriminatory manifestations online, using internet memes. |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.designer.taskforms.builder;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.bpmn2.Definitions;
import org.kie.workbench.common.forms.bpmn.BPMNFormBuilderService;
import org.kie.workbench.common.forms.commons.layout.FormLayoutTemplateGenerator;
import org.kie.workbench.common.forms.jbpm.model.authoring.JBPMFormModel;
import org.kie.workbench.common.forms.jbpm.server.service.BPMNFormModelGenerator;
import org.kie.workbench.common.forms.model.FieldDefinition;
import org.kie.workbench.common.forms.model.FormDefinition;
import org.kie.workbench.common.forms.model.FormModel;
import org.kie.workbench.common.forms.serialization.FormDefinitionSerializer;
import org.kie.workbench.common.forms.service.FormModelHandler;
import org.kie.workbench.common.forms.service.FormModelHandlerManager;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.Path;
import org.uberfire.io.IOService;
@Dependent
public class BPMNKieWorkbenchFormBuilderService implements BPMNFormBuilderService<Definitions> {
private IOService ioService;
protected FormModelHandlerManager formModelHandlerManager;
protected BPMNFormModelGenerator generator;
protected FormDefinitionSerializer serializer;
protected FormLayoutTemplateGenerator layoutTemplateGenerator;
@Inject
public BPMNKieWorkbenchFormBuilderService(
@Named( "ioStrategy" ) IOService ioService,
FormModelHandlerManager formModelHandlerManager,
BPMNFormModelGenerator generator,
FormDefinitionSerializer serializer,
FormLayoutTemplateGenerator layoutTemplateGenerator) {
this.ioService = ioService;
this.formModelHandlerManager = formModelHandlerManager;
this.generator = generator;
this.serializer = serializer;
this.layoutTemplateGenerator = layoutTemplateGenerator;
}
@Override
public String buildFormContent( Path formPath,
Definitions definition,
String taskId ) throws Exception {
JBPMFormModel model;
if ( StringUtils.isEmpty( taskId ) ) {
model = generator.generateProcessFormModel( definition );
} else {
model = generator.generateTaskFormModel( definition, taskId );
}
if ( model == null ) {
throw new IllegalArgumentException( "Unable to generate form '" + formPath.getFileName() + "'" );
}
FormDefinition form = generateFormForModel( model, formPath );
return serializer.serialize( form );
}
protected FormDefinition generateFormForModel( FormModel model, Path formPath ) {
org.uberfire.java.nio.file.Path kiePath = Paths.convert( formPath );
FormModelHandler modelHandler = formModelHandlerManager.getFormModelHandler( model.getClass() );
modelHandler.init( model, formPath );
List<FieldDefinition> modelFields = modelHandler.getAllFormModelFields();
FormDefinition form;
if ( ioService.exists( kiePath ) ) {
form = serializer.deserialize( ioService.readAllString( kiePath ) );
form.getFields().forEach( originalField -> {
boolean found = false;
for ( Iterator<FieldDefinition> it = modelFields.iterator(); it.hasNext() && !found; ) {
FieldDefinition modelField = it.next();
if ( modelField.getBinding().equals( originalField.getBinding() ) ) {
found = true;
originalField.setName( modelField.getName() );
originalField.setStandaloneClassName( modelField.getStandaloneClassName() );
it.remove();
}
}
if ( !found ) {
originalField.setBinding( null );
}
} );
form.getFields().addAll( modelFields );
layoutTemplateGenerator.updateLayoutTemplate( form, modelFields );
} else {
form = getNewFormInstance();
form.setName( formPath.getFileName() );
form.getFields().addAll( modelFields );
layoutTemplateGenerator.generateLayoutTemplate( form );
}
form.setModel( model );
return form;
}
@Override
public String buildEmptyFormContent( String fileName ) throws Exception {
FormDefinition form = getNewFormInstance();
form.setName( fileName );
return serializer.serialize( form );
}
protected FormDefinition getNewFormInstance() {
FormDefinition form = new FormDefinition();
form.setId( UUID.randomUUID().toString() );
layoutTemplateGenerator.generateLayoutTemplate( form );
return form;
}
@Override
public String getFormExtension() {
return "frm";
}
}
|
package com.fangyuzhong.intelliJ.hadoop.core.ui;
import com.fangyuzhong.intelliJ.hadoop.core.Colors;
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.lang.reflect.Method;
import java.util.EventListener;
/**
* Created by fangyuzhong on 17-7-14.
*/
public class GUIUtil
{
public static final Font REGULAR_FONT =com.intellij.util.ui.UIUtil.getLabelFont(); ;
public static final Font BOLD_FONT = new Font(REGULAR_FONT.getName(), 1, REGULAR_FONT.getSize());
public static final String DARK_LAF_NAME = "Darcula";
public static void updateSplitterProportion(JComponent root, final float proportion)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if ((root instanceof Splitter))
{
Splitter splitter = (Splitter) root;
splitter.setProportion(proportion);
} else
{
Component[] components = root.getComponents();
for (Component component : components)
{
if ((component instanceof JComponent))
{
GUIUtil.updateSplitterProportion((JComponent) component, proportion);
}
}
}
}
});
}
public static void stopTableCellEditing(JComponent root)
{
if ((root instanceof JTable))
{
JTable table = (JTable) root;
TableCellEditor cellEditor = table.getCellEditor();
if (cellEditor != null)
{
cellEditor.stopCellEditing();
}
} else
{
Component[] components = root.getComponents();
for (Component component : components)
{
if ((component instanceof JComponent))
{
stopTableCellEditing((JComponent) component);
}
}
}
}
public static Point getRelativeMouseLocation(Component component)
{
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
if (pointerInfo == null)
{
return new Point();
}
Point mouseLocation = pointerInfo.getLocation();
return getRelativeLocation(mouseLocation, component);
}
public static Point getRelativeLocation(Point locationOnScreen, Component component)
{
Point componentLocation = component.getLocationOnScreen();
Point relativeLocation = locationOnScreen.getLocation();
relativeLocation.move((int) (locationOnScreen.getX() - componentLocation.getX()), (int) (locationOnScreen.getY() - componentLocation.getY()));
return relativeLocation;
}
public static boolean isChildOf(Component component, Component child)
{
Component parent = child == null ? null : child.getParent();
while (parent != null)
{
if (parent == component)
{
return true;
}
parent = parent.getParent();
}
return false;
}
public static boolean isFocused(Component component, boolean recoursive)
{
if (component.isFocusOwner())
{
return true;
}
if ((recoursive) && ((component instanceof JComponent)))
{
JComponent parentComponent = (JComponent) component;
for (Component childComponent : parentComponent.getComponents())
{
if (isFocused(childComponent, recoursive))
{
return true;
}
}
}
return false;
}
public static boolean isDarkLookAndFeel()
{
return UIManager.getLookAndFeel().getName().contains("Darcula");
}
public static boolean supportsDarkLookAndFeel()
{
if (isDarkLookAndFeel())
{
return true;
}
for (UIManager.LookAndFeelInfo lookAndFeelInfo : UIManager.getInstalledLookAndFeels())
{
if (lookAndFeelInfo.getName().contains("Darcula"))
{
return true;
}
}
return false;
}
public static void updateBorderTitleForeground(JPanel panel)
{
Border border = panel.getBorder();
if ((border instanceof TitledBorder))
{
TitledBorder titledBorder = (TitledBorder) border;
titledBorder.setTitleColor(Colors.HINT_COLOR);
}
}
public static void removeListeners(Component comp)
{
Method[] methods = comp.getClass().getMethods();
for (Method method : methods)
{
String name = method.getName();
if ((name.startsWith("remove")) && (name.endsWith("Listener")))
{
Class[] params = method.getParameterTypes();
if (params.length == 1)
{
EventListener[] listeners;
try
{
listeners = comp.getListeners(params[0]);
} catch (Exception e)
{
System.out.println("Listener " + params[0] + " does not extend EventListener");
continue;
}
for (EventListener listener : listeners)
{
try
{
method.invoke(comp, new Object[]{listener});
} catch (Exception e)
{
System.out.println("Cannot invoke removeListener method " + e);
}
}
} else if (!name.equals("removePropertyChangeListener"))
{
System.out.println(" Wrong number of Args " + name);
}
}
}
}
public static void showUnderneathOf(@NotNull JBPopup popup, @NotNull Component sourceComponent, int verticalShift, int maxHeight)
{
if (popup == null)
{
throw new IllegalArgumentException(String.format("Argument for @NotNull parameter '%s' of %s.%s must not be null", new Object[]{"popup", "com/dci/intellij/dbn/core/ui/GUIUtil", "showUnderneathOf"}));
}
if (sourceComponent == null)
{
throw new IllegalArgumentException(String.format("Argument for @NotNull parameter '%s' of %s.%s must not be null", new Object[]{"sourceComponent", "com/dci/intellij/dbn/core/ui/GUIUtil", "showUnderneathOf"}));
}
JComponent popupContent = popup.getContent();
Dimension preferredSize = popupContent.getPreferredSize();
int width = Math.max((int) preferredSize.getWidth(), sourceComponent.getWidth());
int height = (int) Math.min(maxHeight, preferredSize.getHeight());
if ((popup instanceof ListPopupImpl))
{
ListPopupImpl listPopup = (ListPopupImpl) popup;
JList list = listPopup.getList();
int listHeight = (int) list.getPreferredSize().getHeight();
if (listHeight > height)
{
height = Math.min(maxHeight, listHeight);
}
}
popupContent.setPreferredSize(new Dimension(width, height));
popup.show(new RelativePoint(sourceComponent, new Point(0, sourceComponent.getHeight() + verticalShift)));
}
public static Color adjustColor(Color color, double shift)
{
if (isDarkLookAndFeel())
{
shift = -shift;
}
int red = (int) Math.round(Math.min(255.0D, color.getRed() + 255.0D * shift));
int green = (int) Math.round(Math.min(255.0D, color.getGreen() + 255.0D * shift));
int blue = (int) Math.round(Math.min(255.0D, color.getBlue() + 255.0D * shift));
red = Math.max(Math.min(255, red), 0);
green = Math.max(Math.min(255, green), 0);
blue = Math.max(Math.min(255, blue), 0);
int alpha = color.getAlpha();
return new Color(red, green, blue, alpha);
}
public static Font getEditorFont()
{
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
return new Font(scheme.getEditorFontName(), 0, UIUtil.getLabelFont().getSize());
}
public static void paintFocusRing(Graphics g, Rectangle bounds)
{
try
{
Method paintFocusRing = DarculaUIUtil.class.getMethod("paintFocusRing", new Class[]{Graphics.class, Rectangle.class});
paintFocusRing.invoke(null, new Object[]{g, bounds});
} catch (Throwable e)
{
try
{
Method paintFocusRing = DarculaUIUtil.class.getMethod("paintFocusRing", new Class[]{Graphics.class, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE});
paintFocusRing.invoke(null, new Object[]{g, Integer.valueOf((int) bounds.getX()), Integer.valueOf((int) bounds.getY()), Integer.valueOf((int) bounds.getWidth()), Integer.valueOf((int) bounds.getHeight())});
} catch (Throwable ignore)
{
}
}
}
}
|
const plugin: Fig.Plugin = {
icon: "🧑💻",
name: "caniuse.plugin.zsh_walesmd",
displayName: "Caniuse",
type: "shell",
description:
"This oh-my-zsh plugin brings CanIUse (http://caniuse.com) to your terminal.",
authors: [
{
name: "walesmd",
github: "walesmd",
},
],
github: "walesmd/caniuse.plugin.zsh",
license: ["MIT"],
shells: ["zsh"],
categories: ["Other"],
installation: {
origin: "github",
sourceFiles: ["caniuse.plugin.zsh"],
},
};
export default plugin;
|
Kevin Hart, for yet another week, leads the chart, which ranks the most popular funnymen and women based on data from Facebook, Instagram, Twitter, YouTube and Google Plus.
Chris Hardwick debuts on The Hollywood Reporter’s Top Comedians chart at No. 7, while Kevin Hart retains his stranglehold on the top spot.
The Top Comedians chart is a ranking of the most popular comedians on Facebook, Instagram, Twitter, YouTube and Google Plus, with global data provided by social media analytics company MVPindex. The chart’s methodology blends social engagement on the platforms along with weekly additions of followers/subscribers. The latest tracking week ended July 25.
Hart has led the chart each week since its inception and gains 89 percent in overall social media conversation in the tracking week, according to MVPindex.
Hardwick’s debut comes as part of some disappointing news for the comedian: his Comedy Central show, @midnight with Chris Hardwick, was canceled July 19. “600 eps of @midnight!” he wrote on Twitter. “I’m so proud! I’ve nothing but gratitude for @ComedyCentral & YOU for watching/hashtagging.” Hardwick jumps 145 percent in Twitter mentions and snagged 5,000 new followers on the service.
After announcing he was “back on my comedy grind” on Twitter, Hart revealed dates for the opening leg of his latest stand-up tour, snagging a 77 percent boost in all social media engagement and 89 percent in conversation in the process. The tour kicks off Sept. 9 in Macon, Ga. |
/**
* Starts an artificial context that can be used to include files without having a source that contains
* the include directives.
* @param buffer a buffer containing the include directives.
* @param isMacroFile whether the context is used for running the preprocessor, only.
*/
public ILocationCtx pushPreInclusion(AbstractCharArray buffer, int offset, boolean isMacroFile) {
assert fCurrentContext instanceof LocationCtxContainer;
int sequenceNumber = getSequenceNumberForOffset(offset);
fCurrentContext = new LocationCtxContainer((LocationCtxContainer) fCurrentContext, buffer, offset, offset,
sequenceNumber);
fLastChildInsertionOffset = 0;
return fCurrentContext;
} |
<reponame>mkravchik/practical-poisoning-ics-ad
import re
import pandas as pd
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn import metrics
from sklearn.utils import class_weight
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
import numpy as np
import keras
import pickle
def process_matlab_log(log_file, silent=True):
f = open(log_file, "rt+")
lines = f.readlines()
f.close()
att_idx = 31
#tests starts with
# temporary misspelled variant
# Att_level 23.200000 att_delay;0.000000
#Run starts
att_run_start = "Poison loaded. num_poisons (\d+), att_idx (\d+)"
test_start = "^Att_level (\d+\.\d+) att_delay (\d+\.\d+).*$"
last_sep_val = "^Last value of sep level (\d+\.\d+) time (\d+\.\d+).*$"
#Attack generation with Sep level u(12) 53.075893, Sep flow u(14) 25.648470, xmv7 37.603183, Strip level u(15) 49.684285, strip flow u(17) 22.817279 xmv8 46.265101 at time 7.550500
pattern = " with Sep level u\(12\) (\d+\.\d+), Sep flow u\(14\) (\d+\.\d+), xmv7 (\d+\.\d+), Strip level u\(15\) (\d+\.\d+), strip flow u\(17\) (\d+\.\d+) xmv8 (\d+\.\d+) at time (\d+\.\d+)"
pattern_att_1 = " with A Feed Rate u\(1\) (-?\d+\.\d+), Reactor Pressure u\(7\) (\d+\.\d+), Reactor Level u8 (\d+\.\d+), xmv3 (\d+\.\d+) at time (\d+\.\d+)"
pred_input = "^\[\[.*\]\]$"
pred_input_first = "^\[\[.*\s+$"
# can be also 5.36676888e+01 5.95000000e+00]]
pred_input_last = "^\s+.*\s+(\d+\.\d+)\s+\]\]$|^\s+.*\s+(\d+\.\d+e[+-]\d{2}).*\]\]$"
pattern_attack_start = "^Attack generation" + pattern + ".*$"
pattern_attack_start_att_1 = "^Attack generation" + pattern_att_1 + ".*$"
#ends with
#Stop attack generation with Sep level u(12) 4.030612, Sep flow u(14) 24.897414, xmv7 36.681489, Strip level u(15) 105.718569, strip flow u(17) 23.568345 xmv8 49.438867 at time 9.525500
pattern_attack_end = "^Stop attack generation" + pattern + ".*$"
pattern_attack_end_att_1 = "^Stop attack generation" + pattern_att_1 + ".*$"
pattern_shutdown = "Shutting down"
sim_stops = "^Simulator completed!.*$"
sim_starts = "^Running simulator!$"
# patterns from the posioning with attack
poison_starts = "^Applying poison with .*$"
poison_stops = "^Stop applying poison .*$"
att_starts = "^Attacking" + pattern + ".*$"
att_starts_att_1 = "^Attacking" + pattern_att_1 + ".*$"
att_stops = "^Stop attacking poison" + pattern + ".*$"
att_stops_att_1 = "^Stop attacking poison" + pattern_att_1 + ".*$"
state = "before_test"
cols = ["time", "Delay", "Att level", "Sep level u(12)", "Sep flow u(14)", 'xmv7', 'Strip level u(15)',
"strip flow u(17)", "xmv8", "Final Sep level u(12)", "Shutdown", "Att time", "Att len", "num_poisons"]
cols_att_1 = ["time", "Delay", "Att level", "A Feed Rate u(1)", "Reactor Pressure u(7)", 'Reactor Level u8',
"xmv3", "Final Sep level u(12)", "Shutdown", "Att time", "Att len", "num_poisons"]
df_results = None
rec = None
num_poisons = 0
att_len = None
for line in lines:
# if not silent: print("Processing", line)
if state == "before_test":
#looking for the test run start
match = re.findall(att_run_start, line)
if len(match):
if not silent: print("Attack test starts", line)
state = "before_test"
num_poisons = int(match[0][0])
att_idx = int(match[0][1])
print("att_idx", att_idx)
if att_idx == 1:
pattern_attack_start = pattern_attack_start_att_1
pattern_attack_end = pattern_attack_end_att_1
att_starts = att_starts_att_1
att_stops = att_stops_att_1
cols = cols_att_1
if df_results is None:
df_results = pd.DataFrame(columns=cols)
continue
#looking for the test start
match = re.findall(test_start, line)
if len(match):
if not silent: print("Test starts", line)
state = "before_sim"
level = match[0][0]
delay = match[0][1]
continue
if state == "before_sim":
#looking for the test start
match = re.findall(sim_starts, line)
if len(match):
if not silent: print("Sim starts", line)
state = "before_att"
continue
if state == "in_pred_poison":
if not silent: print("Prediction", line)
state = "before_att"
continue
if state == "in_pred_poison_first":
match = re.findall(pred_input_last, line)
if len(match):
if not silent: print("Prediction input ends", line, match[0])
att_len = float(match[0][0]) if len(match[0][0]) else float(match[0][1])
state = "in_pred_poison"
continue
if state == "before_att":
# in the older files, there was no prediction here
# in the new ones - there is
match = re.findall(pred_input, line)
if len(match):
if not silent: print("Prediction input", line)
state = "in_pred_poison"
continue
match = re.findall(pred_input_first, line)
if len(match):
if not silent: print("Prediction input starts", line)
state = "in_pred_poison_first"
continue
#looking for the attack start
match = re.findall(pattern_attack_start, line)
if 0 == len(match):
match = re.findall(att_starts, line)
if len(match):
if not silent: print("Attack starts", line)
state = "started"
rec = {
"time":match[0][-1],
"Final Sep level u(12)":2.0,
"Shutdown":False,
"Att time":0,
"Delay": delay,
"Att level":level,
"num_poisons":num_poisons
}
if att_idx == 1:
rec["A Feed Rate u(1)"] = match[0][0]
rec["Reactor Pressure u(7)"] = match[0][1]
rec['Reactor Level u8'] = match[0][2]
rec['xmv3'] = match[0][3]
else:
rec["Sep level u(12)"] = match[0][0]
rec["Sep flow u(14)"] = match[0][1]
rec['xmv7'] = match[0][2]
rec['Strip level u(15)'] = match[0][3]
rec["strip flow u(17)"] = match[0][4]
rec["xmv8"] = match[0][5]
# print(match, rec)
continue
match = re.findall(last_sep_val, line)
if len(match):
if not silent: print("Last sep level", line)
# if we got here without seeing an attack - do not add anything
rec = None
state = "before_test"
continue
if state == "started":
#looking for the attack end
match = re.findall(pattern_attack_end, line)
if 0 == len(match):
match = re.findall(att_stops, line)
if len(match):
if not silent: print("Attack ends", line)
if att_idx != 1:
rec["Final Sep level u(12)"] = match[0][0]
rec["Att time"] = float(match[0][-1]) - float(rec["time"])
rec["Shutdown"] = False
state = "after_att"
continue
#looking for the shutdown
match = re.findall(pattern_shutdown, line)
if len(match):
if not silent: print("Shutdown", line)
rec["Shutdown"] = True
# not changing the state
continue
#looking for the Last values
match = re.findall(last_sep_val, line)
if len(match):
if not silent: print("Last sep level", line)
rec["Final Sep level u(12)"] = match[0][0]
rec["Att time"] = float(match[0][1]) - float(rec["time"])
# the only place to add the record is after the Last sep level record
if att_len is None and not rec["Shutdown"]:
att_len = rec["Att time"]
if att_len is None:
rec["Att len"] = rec["Att time"]
else:
rec["Att len"] = att_len
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_test"
continue
if state == "after_att":
#looking for the shutdown
match = re.findall(pattern_shutdown, line)
if len(match):
if not silent: print("Shutdown", line)
rec["Shutdown"] = True
continue
#looking for the Last values
match = re.findall(last_sep_val, line)
if len(match):
if not silent: print("Last sep level", line)
# the only place to add the record is after the Last sep level record
if rec["Shutdown"]: # if there was a shutdown after the attack has ended - update the level and time
rec["Final Sep level u(12)"] = match[0][0]
rec["Att time"] = float(match[0][1]) - float(rec["time"])
if att_len is None and not rec["Shutdown"]:
att_len = rec["Att time"]
if att_len is None:
rec["Att len"] = rec["Att time"]
else:
rec["Att len"] = att_len
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_test"
continue
if rec is not None:
df_results = df_results.append(rec, ignore_index=True)
if not silent: print(df_results)
return df_results
def process_matlab_log_ce_loss(log_file, silent=True):
f = open(log_file, "rt+")
lines = f.readlines()
f.close()
#tests starts with
# temporary misspelled variant
# Att_level 23.200000 att_delay;0.000000
pred_input = "^\[\[.*\]\]$"
pred_input_first = "^\[\[.*\s+$"
pred_input_last = "^\s+.*\]\]$"
poison_starts = "^Applying poison with .*$"
poison_stops = "^Stop applying poison .*$"
att_starts = "^Attacking with .*$|^Attack generation .*$"
att_stops = "^Stop attacking .*$|^Stop attack generation .*$"
sim_stops = "^Simulator completed!.*$"
sim_starts = "^Running simulator!$"
pattern_shutdown = "Shutting down"
state = "before_sim"
cols = ["y_true", "y_pred"]
df_results = pd.DataFrame(columns=cols)
rec = None
for line in lines:
# if not silent: print("Processing", line)
if state == "before_sim":
#looking for the test start
match = re.findall(sim_starts, line)
if len(match):
if not silent: print("Sim starts", line)
state = "before_poison_or_att"
continue
if state == "before_poison_or_att":
if rec is not None:
match = re.findall(pattern_shutdown, line)
if len(match):
if not silent: print("Shutdown", line)
rec["y_true"] = 1
else:
rec["y_true"] = 0
# add the record and keep on processing
df_results = df_results.append(rec, ignore_index=True)
rec = None
match = re.findall(pred_input, line)
if len(match):
if not silent: print("Prediction input", line)
state = "in_pred_poison"
continue
match = re.findall(pred_input_first, line)
if len(match):
if not silent: print("Prediction input starts", line)
state = "in_pred_poison_first"
continue
if state == "in_pred_poison_first":
match = re.findall(pred_input_last, line)
if len(match):
if not silent: print("Prediction input ends", line)
state = "before_pred_poison_or_attack"
continue
if state == "before_pred_poison_or_attack":
if not silent: print("Prediction", line)
rec = {
"y_pred":float(line.strip())
}
state = "after_pred_poison_or_attack"
continue
if state == "after_pred_poison_or_attack":
match = re.findall(poison_starts, line)
if len(match):
if not silent: print("Poison starts", line)
state = "in_poison"
continue
match = re.findall(att_starts, line)
if len(match):
if not silent: print("Attack starts", line)
state = "in_attack"
continue
match = re.findall(pred_input, line)
if len(match):
if not silent: print("Prediction input", line)
state = "in_pred_poison"
continue
match = re.findall(pred_input_first, line)
if len(match):
if not silent: print("Prediction input starts", line)
state = "in_pred_poison_first"
continue
if state == "in_poison":
match = re.findall(poison_stops, line)
if len(match):
if not silent: print("Poison stops", line)
rec["y_true"] = 0
# wait - don't add it yet
# df_results = df_results.append(rec, ignore_index=True)
# rec = None
state = "before_poison_or_att"
continue
match = re.findall(sim_stops, line)
if len(match):
if not silent: print("Simulation stops (shutdown)", line)
rec["y_true"] = 1
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_sim"
continue
if state == "in_attack":
match = re.findall(att_stops, line)
if len(match):
if not silent: print("Attack stops", line)
rec["y_true"] = 0
# don't add yet - give it chance to shutdown after the attack
# df_results = df_results.append(rec, ignore_index=True)
# rec = None
state = "after_att"
continue
match = re.findall(sim_stops, line)
if len(match):
if not silent: print("Simulation stops (shutdown)", line)
rec["y_true"] = 1
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_sim"
continue
if state == "after_att":
match = re.findall(sim_stops, line)
if len(match):
if not silent: print("Simulation stops (NO shutdown)", line)
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_sim"
continue
match = re.findall(pattern_shutdown, line)
if len(match):
if not silent: print("Shutdown", line)
rec["y_true"] = 1
df_results = df_results.append(rec, ignore_index=True)
rec = None
state = "before_sim"
continue
if rec is not None:
df_results = df_results.append(rec, ignore_index=True)
if not silent: print(df_results)
return df_results
def train_shutdown_predictor(df, clf_cols, save=False, load_prev=False, name_suffix=""):
X = df[clf_cols]
y = df.Shutdown.astype(int)
X_train, X_test, y_train, y_test = train_test_split(X.values, y.values, test_size=0.2)
def estimate(c, X_train, X_test, y_train, y_test):
print(c)
print("train accuracy", metrics.accuracy_score(c.predict(X_train), y_train))
print("test accuracy", metrics.accuracy_score(c.predict(X_test), y_test))
print("confusion matrix")
print(metrics.confusion_matrix(y_test, c.predict(X_test)))
print("f1 score", metrics.f1_score(y_test, c.predict(X_test), pos_label = 1.0))
for clf in [LogisticRegression(random_state=0, max_iter=500, class_weight='balanced'),
RandomForestClassifier(class_weight='balanced'),
LogisticRegressionCV(random_state=0, max_iter=500, class_weight='balanced')]:
if load_prev:
clf_name = repr(clf).split('(')[0]
clf_old = pickle.load(open(clf_name + name_suffix + ".mdl", 'rb'))
estimate(clf_old, X_train, X_test, y_train, y_test)
clf.fit(X_train, y_train)
if save:
clf_name = repr(clf).split('(')[0]
pickle.dump(clf, open(clf_name + name_suffix + ".mdl", 'wb'))
estimate(clf, X_train, X_test, y_train, y_test)
def train_NN_shutdown_predictor(df, clf_cols, save=False, name_suffix=""):
X = df[clf_cols]
y = df.Shutdown.astype(int)
model = keras.Sequential([
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dropout(0.25),
keras.layers.Dense(1, activation=tf.nn.sigmoid),
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['mse'])
earlyStopping= keras.callbacks.EarlyStopping(monitor='val_loss', patience=10,
verbose=1,
min_delta=1e-4, mode='auto')
lr_reduced = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=3,
verbose=1,
min_delta=1e-4, mode='min')
scaler = StandardScaler()
X = X.values
X = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y.values, test_size=0.2, random_state=42)
X_train, X_val, y_train, Y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
class_weights = class_weight.compute_class_weight('balanced',
np.unique(y_train),
y_train)
class_weights = dict(enumerate(class_weights))
print(class_weights)
model.fit(X_train, y_train, epochs=500, batch_size=32,
shuffle=True,
verbose=2,
callbacks = [earlyStopping, lr_reduced],
validation_data=(X_val, Y_val),
class_weight=class_weights
)
print(model)
# print(model.predict(X_test), y_test)
print("train accuracy", metrics.accuracy_score(model.predict(X_train)>0.5, y_train))
print("test accuracy", metrics.accuracy_score(model.predict(X_test)>0.5, y_test))
print("confusion matrix")
print(metrics.confusion_matrix(y_test, model.predict(X_test)>0.5))
print("f1 score", metrics.f1_score(y_test, model.predict(X_test)>0.5, pos_label = 1.0))
if save:
model.save("NN" + name_suffix + ".h5")
return model, scaler
if __name__ == '__main__':
log_file_name = "temexd_mod/poison_data_for_shutdown_predictor_att_1.txt"#"temexd_mod/poison_num_points_4_att_31_2.txt"#"attack31_with_poison_upd.txt"#"matlab_log.txt"
# df_results = process_matlab_log_ce_loss("temexd_mod/att_1_shutdown_3.txt", silent=True).astype(float)
# print(df_results)
# print(df_results[df_results["y_true"]==1])
# print(df_results[df_results["y_pred"]>0.6])
# print(log_loss(df_results["y_true"], df_results["y_pred"]))
# exit()
att_idx = 1
# log_file_name = "temexd_mod/poison_data_for_shutdown_predictor_att_3.txt"#"temexd_mod/poison_num_points_3_att_31.txt"#"attack31_4_poison_generation.txt"
df_results = process_matlab_log(log_file_name).astype(float)
print(df_results)
print(df_results.Shutdown.sum())
print(df_results["Att len"].unique())
if att_idx == 1:
clf_cols = ["Att level", "A Feed Rate u(1)", "Reactor Pressure u(7)", 'Reactor Level u8',
"xmv3", "Att len"]
else:
clf_cols = ["Att level", "Sep level u(12)", "Sep flow u(14)", 'xmv7', 'Strip level u(15)',
"strip flow u(17)", "xmv8", "Att len"]
df_results_subs = df_results[(df_results["Att len"] < 3.4)]
print("subset length", len(df_results_subs))
df_results_subs.to_csv("".join(log_file_name.split('.')[:-1])+".csv")
train_shutdown_predictor(df_results_subs, clf_cols, save=True, load_prev=False, name_suffix = "_te_attack_%d" % att_idx)
train_NN_shutdown_predictor(df_results_subs, clf_cols, save=True, name_suffix="_te_attack_%d" % att_idx)
# print("Current predictions")
# clf = pickle.load(open("RandomForestClassifier.mdl", 'rb'))
# df_shutdown = df_results[df_results.Shutdown == 1][clf_cols]
# df_shutdown.to_csv("shutdown.csv")
# print(df_shutdown)
# print(clf.predict(df_shutdown))
# print(clf.predict_proba(df_shutdown))
# print("Updated predictions")
# clf = pickle.load(open("RandomForestClassifier1.mdl", 'rb'))
# print(clf.predict(df_shutdown))
# print(clf.predict_proba(df_shutdown))
|
1. Field of the Invention
This invention relates to an image processing apparatus, and more specifically to an image processing apparatus which can improve the quality of the output image.
2. Related Background Art
A known image processing apparatus, such as a copying machine, a facsimile apparatus, etc., is used for converting dot resolution in an image.
Such a known image processing apparatus is structured to print recording data (data to be recorded) in such a way as simply to increase the size of a dot by four times, in a case where a printer designed to operate at a dot recording resolution of 400 dpi (dots per inch) is used for printing recording data of 200 dpi, for example.
However, the known image processing apparatus suffers from the problem that the whole output image is darkened, or what should be a thin line of the output image is excessively wide because four times the size of dot is used for printing notwithstanding the printer has an ability of 400 dpi dot resolution.
The apparatus further has a defect that printing density is darkened in such a manner as to give the output image a strange appearance in the case where an isolated dot of, e.g., 200 dpi size, processed by an artificial halftone processing method, is printed.
Especially, a laser beam printer using an electrophotographic method of printing has the defect that an increase of a darkened rate is conspicuous because of a fogging phenomenon which occurs due to the overlapping and combination of adjacent dots, or because of the round shape of the beam spot.
In recent years, an error diffusion method has been proposed as an artificial halftone processing method. When a laser beam printer records an image based on binary data processed by the error diffusion method, there is a possibility that dots may be linked in a highlight portion because the shape of the dots is round and the size of the dots is large. This has resulted in the defect that what should be a thin line in the output image is made to seem fat, or sometimes, a peculiar striped pattern occurs in the output image.
Methods for obtaining a fine line of a proper width and generally for obtaining a proper reproduced image are disclosed in U.S. Pat. Nos. 4,387,983; 4,476,474; 4,517,579; 4,878,068; and 4,905,023, assigned to the assignee of the present invention, but further improvement of those methods has been sought. |
Characterization of composites based on biodegradable poly(vinyl alcohol) and nanostructured fly ash with an emphasis on polymerfiller interaction A thermal power station fly ash (FA) was mechanochemically activated by high-energy ball milling that yielded nanostructured FA. This nanostructured FA was incorporated into biodegradable poly(vinyl alcohol) (PVA) matrix by solution mixing and ultrasonication. Transmission electron micrographs revealed that the smooth spherical particles of FA were changed into irregular and rough ones; in addition, the particle size of FA was reduced to a few hundred nanometers, and its specific surface area value increased after the high-energy milling process. All these factors, in turn, led to a thermodynamically favorable interaction between the mechanochemically activated FA and PVA as evidenced by Fourier transform infrared spectroscopy. The incorporation of a very small amount of the nanostructured FA led to an increase in crystallinity of the polymer matrix. The glass transition temperature of the PVA matrix increased by about 18°C when 5 wt% of the nanostructured FA was used as the reinforcement. |
<gh_stars>0
package com.rackspacecloud.blueflood.io;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.serializers.LongSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.rackspacecloud.blueflood.io.serializers.LocatorSerializer;
import com.rackspacecloud.blueflood.io.serializers.SlotStateSerializer;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.service.Configuration;
import com.rackspacecloud.blueflood.service.CoreConfig;
import com.rackspacecloud.blueflood.service.SlotState;
import com.rackspacecloud.blueflood.types.*;
import com.rackspacecloud.blueflood.utils.TimeValue;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class CassandraModel {
public static final String KEYSPACE = Configuration.getInstance().getStringProperty(CoreConfig.ROLLUP_KEYSPACE);
public static final String CLUSTER = Configuration.getInstance().getStringProperty(CoreConfig.CLUSTER_NAME);
/**
* It is worth pointing out that the actual TTL value is calculated by taking the TimeValues below
* and multiplying by 5. Why? Becuase SafetyTtlProvider.java multiplies the TimeValues below by 5.
*
* Look for a line like this (currently line 48):
* TimeValue ttl = new TimeValue(metricCF.getDefaultTTL().getValue() * 5, metricCF.getDefaultTTL().getUnit());
*
* For example, TimeValue of 1 will equate to a 5 day TTL.
*/
public static final MetricColumnFamily CF_METRICS_FULL = new MetricColumnFamily("metrics_full", new TimeValue(1, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_5M = new MetricColumnFamily("metrics_5m", new TimeValue(2, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_20M = new MetricColumnFamily("metrics_20m", new TimeValue(4, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_60M = new MetricColumnFamily("metrics_60m", new TimeValue(31, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_240M = new MetricColumnFamily("metrics_240m", new TimeValue(60, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_1440M = new MetricColumnFamily("metrics_1440m", new TimeValue(365, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_STRING = new MetricColumnFamily("metrics_string", new TimeValue(365 * 3, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_FULL = new MetricColumnFamily("metrics_preaggregated_full", new TimeValue(1, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_5M = new MetricColumnFamily("metrics_preaggregated_5m", new TimeValue(2, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_20M = new MetricColumnFamily("metrics_preaggregated_20m", new TimeValue(4, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_60M = new MetricColumnFamily("metrics_preaggregated_60m", new TimeValue(31, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_240M = new MetricColumnFamily("metrics_preaggregated_240m", new TimeValue(60, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_PREAGGREGATED_1440M = new MetricColumnFamily("metrics_preaggregated_1440m", new TimeValue(365, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_HIST_FULL = CF_METRICS_FULL;
public static final MetricColumnFamily CF_METRICS_HIST_5M = new MetricColumnFamily("metrics_histogram_5m", new TimeValue(2, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_HIST_20M = new MetricColumnFamily("metrics_histogram_20m", new TimeValue(4, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_HIST_60M = new MetricColumnFamily("metrics_histogram_60m", new TimeValue(31, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_HIST_240M = new MetricColumnFamily("metrics_histogram_240m", new TimeValue(60, TimeUnit.DAYS));
public static final MetricColumnFamily CF_METRICS_HIST_1440M = new MetricColumnFamily("metrics_histogram_1440m", new TimeValue(365, TimeUnit.DAYS));
public static final ColumnFamily<Locator, String> CF_METRIC_METADATA = new ColumnFamily<Locator, String>("metrics_metadata",
LocatorSerializer.get(),
StringSerializer.get());
public static final ColumnFamily<Long, Locator> CF_METRICS_LOCATOR = new ColumnFamily<Long, Locator>("metrics_locator",
LongSerializer.get(),
LocatorSerializer.get());
public static final ColumnFamily<Long, SlotState> CF_METRICS_STATE = new ColumnFamily<Long, SlotState>("metrics_state",
LongSerializer.get(),
SlotStateSerializer.get());
private static final MetricColumnFamily[] METRIC_COLUMN_FAMILES = new MetricColumnFamily[] {
CF_METRICS_FULL, CF_METRICS_5M, CF_METRICS_20M, CF_METRICS_60M, CF_METRICS_240M, CF_METRICS_1440M,
CF_METRICS_PREAGGREGATED_FULL, CF_METRICS_PREAGGREGATED_5M, CF_METRICS_PREAGGREGATED_20M,
CF_METRICS_PREAGGREGATED_60M, CF_METRICS_PREAGGREGATED_240M, CF_METRICS_PREAGGREGATED_1440M,
CF_METRICS_HIST_FULL, CF_METRICS_HIST_5M, CF_METRICS_HIST_20M, CF_METRICS_HIST_60M,
CF_METRICS_HIST_240M, CF_METRICS_HIST_1440M,
CF_METRICS_STRING
};
private static final ColumnFamily[] BF_SYSTEM_COLUMN_FAMILIES = new ColumnFamily[] {
CF_METRIC_METADATA, CF_METRICS_LOCATOR, CF_METRICS_STATE
};
private static final Collection<ColumnFamily> ALL_COLUMN_FAMILIES;
private static final ColumnFamilyMapper CF_NAME_TO_CF;
private static final ColumnFamilyMapper PREAG_GRAN_TO_CF;
private static final ColumnFamilyMapper HIST_GRAN_TO_CF;
private static final Map<ColumnFamily<Locator, Long>, Granularity> CF_TO_GRAN;
static {
final Map<Granularity, MetricColumnFamily> columnFamilyMap = new HashMap<Granularity, MetricColumnFamily>();
columnFamilyMap.put(Granularity.FULL, CF_METRICS_FULL);
columnFamilyMap.put(Granularity.MIN_5, CF_METRICS_5M);
columnFamilyMap.put(Granularity.MIN_20, CF_METRICS_20M);
columnFamilyMap.put(Granularity.MIN_60, CF_METRICS_60M);
columnFamilyMap.put(Granularity.MIN_240, CF_METRICS_240M);
columnFamilyMap.put(Granularity.MIN_1440, CF_METRICS_1440M);
final Map<Granularity, MetricColumnFamily> preagCFMap = new HashMap<Granularity, MetricColumnFamily>();
preagCFMap.put(Granularity.FULL, CF_METRICS_PREAGGREGATED_FULL);
preagCFMap.put(Granularity.MIN_5, CF_METRICS_PREAGGREGATED_5M);
preagCFMap.put(Granularity.MIN_20, CF_METRICS_PREAGGREGATED_20M);
preagCFMap.put(Granularity.MIN_60, CF_METRICS_PREAGGREGATED_60M);
preagCFMap.put(Granularity.MIN_240, CF_METRICS_PREAGGREGATED_240M);
preagCFMap.put(Granularity.MIN_1440, CF_METRICS_PREAGGREGATED_1440M);
final Map<Granularity, MetricColumnFamily> histCFMap = new HashMap<Granularity, MetricColumnFamily>();
histCFMap.put(Granularity.FULL, CF_METRICS_HIST_FULL);
histCFMap.put(Granularity.MIN_5, CF_METRICS_HIST_5M);
histCFMap.put(Granularity.MIN_20, CF_METRICS_HIST_20M);
histCFMap.put(Granularity.MIN_60, CF_METRICS_HIST_60M);
histCFMap.put(Granularity.MIN_240, CF_METRICS_HIST_240M);
histCFMap.put(Granularity.MIN_1440, CF_METRICS_HIST_1440M);
Map<ColumnFamily<Locator, Long>, Granularity> cfToGranMap = new HashMap<ColumnFamily<Locator, Long>, Granularity>();
cfToGranMap.put(CF_METRICS_FULL, Granularity.FULL);
cfToGranMap.put(CF_METRICS_STRING, Granularity.FULL);
cfToGranMap.put(CF_METRICS_5M, Granularity.MIN_5);
cfToGranMap.put(CF_METRICS_20M, Granularity.MIN_20);
cfToGranMap.put(CF_METRICS_60M, Granularity.MIN_60);
cfToGranMap.put(CF_METRICS_240M, Granularity.MIN_240);
cfToGranMap.put(CF_METRICS_1440M, Granularity.MIN_1440);
CF_NAME_TO_CF = new ColumnFamilyMapper() {
@Override
public MetricColumnFamily get(Granularity gran) {
return columnFamilyMap.get(gran);
}
};
PREAG_GRAN_TO_CF = new ColumnFamilyMapper() {
@Override
public MetricColumnFamily get(Granularity gran) {
return preagCFMap.get(gran);
}
};
HIST_GRAN_TO_CF = new ColumnFamilyMapper() {
@Override
public MetricColumnFamily get(Granularity gran) {
return histCFMap.get(gran);
}
};
CF_TO_GRAN = Collections.unmodifiableMap(cfToGranMap);
List<ColumnFamily> cfs = new ArrayList<ColumnFamily>();
for (ColumnFamily cf : METRIC_COLUMN_FAMILES) {
cfs.add(cf);
}
for (ColumnFamily cf : BF_SYSTEM_COLUMN_FAMILIES) {
cfs.add(cf);
}
ALL_COLUMN_FAMILIES = Collections.unmodifiableList(cfs);
}
public static ColumnFamily getColumnFamily(Class<? extends Rollup> type, Granularity granularity) {
if (type.equals(SimpleNumber.class)) {
return CF_METRICS_FULL;
} else if (type.equals(BasicRollup.class)) {
return CF_NAME_TO_CF.get(granularity);
} else if (type.equals(HistogramRollup.class)) {
return HIST_GRAN_TO_CF.get(granularity);
} else if (type.equals(SetRollup.class) || type.equals(TimerRollup.class) || type.equals(GaugeRollup.class) ||
type.equals(CounterRollup.class)) {
return PREAG_GRAN_TO_CF.get(granularity);
} else {
throw new RuntimeException("Unsupported rollup type.");
}
}
public static ColumnFamily getColumnFamily(RollupType type, DataType dataType, Granularity gran) {
if (type == RollupType.BF_BASIC &&
(dataType.equals(DataType.BOOLEAN) || dataType.equals(DataType.STRING))) {
return CF_METRICS_STRING;
}
return getColumnFamily(RollupType.classOf(type, gran), gran);
}
// iterate over all column families that store metrics.
public static Iterable<MetricColumnFamily> getMetricColumnFamilies() {
return new Iterable<MetricColumnFamily>() {
@Override
public Iterator<MetricColumnFamily> iterator() {
return new Iterator<MetricColumnFamily>() {
private int pos = 0;
@Override
public boolean hasNext() {
return pos < METRIC_COLUMN_FAMILES.length;
}
@Override
public MetricColumnFamily next() {
return METRIC_COLUMN_FAMILES[pos++];
}
@Override
public void remove() {
throw new NoSuchMethodError("Not implemented");
}
};
}
};
}
public static Collection<ColumnFamily> getAllColumnFamilies() {
return ALL_COLUMN_FAMILIES;
}
public static class MetricColumnFamily extends ColumnFamily<Locator, Long> {
private final TimeValue ttl;
public MetricColumnFamily(String name, TimeValue ttl) {
super(name, LocatorSerializer.get(), LongSerializer.get());
this.ttl = ttl;
}
public TimeValue getDefaultTTL() {
return ttl;
}
}
// future versions will have get(Granularity, RollupType).
public interface ColumnFamilyMapper {
public MetricColumnFamily get(Granularity gran);
}
}
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban
// =============================================================================
#include <algorithm>
#include <cmath>
#include "chrono/physics/ChMaterialSurface.h"
#include "chrono/physics/ChMaterialSurfaceSMC.h"
#include "chrono/physics/ChMaterialSurfaceNSC.h"
#include "chrono/physics/ChSystem.h"
namespace chrono {
// -----------------------------------------------------------------------------
ChMaterialSurface::ChMaterialSurface()
: static_friction(0.6f),
sliding_friction(0.6f),
rolling_friction(0),
spinning_friction(0),
restitution(0.4f) {}
ChMaterialSurface::ChMaterialSurface(const ChMaterialSurface& other) {
static_friction = other.static_friction;
sliding_friction = other.sliding_friction;
rolling_friction = other.rolling_friction;
spinning_friction = other.spinning_friction;
restitution = other.restitution;
}
void ChMaterialSurface::SetFriction(float val) {
SetSfriction(val);
SetKfriction(val);
}
void ChMaterialSurface::ArchiveOut(ChArchiveOut& marchive) {
// version number
marchive.VersionWrite<ChMaterialSurface>();
// serialize all member data:
marchive << CHNVP(static_friction);
marchive << CHNVP(sliding_friction);
marchive << CHNVP(rolling_friction);
marchive << CHNVP(spinning_friction);
marchive << CHNVP(restitution);
}
void ChMaterialSurface::ArchiveIn(ChArchiveIn& marchive) {
// version number
/*int version =*/ marchive.VersionRead<ChMaterialSurface>();
// stream in all member data:
marchive >> CHNVP(static_friction);
marchive >> CHNVP(sliding_friction);
marchive >> CHNVP(rolling_friction);
marchive >> CHNVP(spinning_friction);
marchive >> CHNVP(restitution);
}
std::shared_ptr<ChMaterialSurface> ChMaterialSurface::DefaultMaterial(ChContactMethod contact_method) {
switch (contact_method) {
case ChContactMethod::NSC:
return chrono_types::make_shared<ChMaterialSurfaceNSC>();
case ChContactMethod::SMC:
return chrono_types::make_shared<ChMaterialSurfaceSMC>();
}
return nullptr;
}
ChContactMaterialData::ChContactMaterialData()
: mu(0.8f), cr(0.01f), Y(2e7f), nu(0.3f), kn(2e5f), gn(40.0f), kt(2e5f), gt(20.0f) {}
ChContactMaterialData::ChContactMaterialData(float mu_,
float cr_,
float Y_,
float nu_,
float kn_,
float gn_,
float kt_,
float gt_)
: mu(mu_), cr(cr_), Y(Y_), nu(nu_), kn(kn_), gn(gn_), kt(kt_), gt(gt_) {}
std::shared_ptr<ChMaterialSurface> ChContactMaterialData::CreateMaterial(ChContactMethod contact_method) const {
switch (contact_method) {
case ChContactMethod::NSC: {
auto matNSC = chrono_types::make_shared<ChMaterialSurfaceNSC>();
matNSC->SetFriction(mu);
matNSC->SetRestitution(cr);
return matNSC;
}
case ChContactMethod::SMC: {
auto matSMC = chrono_types::make_shared<ChMaterialSurfaceSMC>();
matSMC->SetFriction(mu);
matSMC->SetRestitution(cr);
matSMC->SetYoungModulus(Y);
matSMC->SetPoissonRatio(nu);
matSMC->SetKn(kn);
matSMC->SetGn(gn);
matSMC->SetKt(kt);
matSMC->SetGt(gt);
return matSMC;
}
default:
return std::shared_ptr<ChMaterialSurface>();
}
}
} // end namespace chrono
|
Optic neuropathy in superficial intracranial siderosis. Superficial intracranial siderosis is a degenerative condition secondary to recurrent occult subarachnoid hemorrhage. Progressive sensorineural deafness, cerebellar ataxia, and pyramidal signs are well-documented clinical manifestations, but optic neuropathy is not a recognized feature. We describe 2 patients with clinical and electrophysiological evidence of optic nerve/chiasm dysfunction and MRI signal abnormalities consistent with hemosiderin staining of the anterior visual pathway. In a third case, neuropathological examination of the optic chiasm showed demyelination attributed to hemosiderin deposition. We suggest that anterior visual pathway damage may be underrecognized in this condition. |
import { ConfigurationService } from '../../common/configuration.service';
import { CategoryAxisLabelsComponentGenerated } from '../category-axis-item/labels.component.generated';
/**
* The configuration of the axis labels ([see example]({% slug labels_chart_charts %})).
*/
export declare class CategoryAxisLabelsComponent extends CategoryAxisLabelsComponentGenerated {
configurationService: ConfigurationService;
constructor(configurationService: ConfigurationService);
}
|
<gh_stars>0
package com.dardan.rrafshi.filezilla.examples;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dardan.rrafshi.commons.security.Passwords;
import com.dardan.rrafshi.filezilla.Constants;
import com.dardan.rrafshi.filezilla.FilezillaManager;
import com.dardan.rrafshi.filezilla.model.FilezillaPath;
import com.dardan.rrafshi.filezilla.model.FilezillaSession;
public final class DownloadFolder
{
private static final Logger LOGGER = LoggerFactory.getLogger(DownloadFile.class);
public static void main(final String[] args)
{
final FilezillaSession session = FilezillaSession.builder()
.login(Constants.DEFAULT_FTP_USERNAME, Passwords.getPasswordFromFile("<PASSWORD>"))
.build();
try(FilezillaManager filezillaManager = new FilezillaManager(session)) {
final Path targetPath = Paths.get("C:\\Users\\drraf\\Music\\Temp\\");
final FilezillaPath originPath = FilezillaPath.parse("/artists/all time low");
filezillaManager.downloadFolder(originPath, targetPath);
} catch (final Exception exception) {
LOGGER.error("Download failed: ", exception);
}
LOGGER.info("Finished at " + LocalDateTime.now());
}
}
|
package main
import (
"fmt"
"strconv"
"strings"
"time"
"log"
"os"
"testing"
"github.com/streadway/amqp"
"github.com/remeh/sizedwaitgroup"
)
/*func TestFailing(t *testing.T) {
t.Fail()
}*/
func readEnvVars() (string, string, string, string, string, string, string, string, string, string, string, string, string, int64) {
timeout, err := strconv.ParseInt(os.Getenv("TIMEOUT"), 10, 0)
if err != nil {
timeout = 10000
}
protocol := strings.ToLower(os.Getenv("PROTOCOL"))
if protocol != "amqp" && protocol != "amqps" {
protocol = "amqps"
}
publishAmqpServer := os.Getenv("PUBLISH_AMQP_SERVER")
publishAmqpTCPPort := os.Getenv("PUBLISH_AMQP_SERVER_TCP")
if publishAmqpTCPPort == "" {
if protocol == "amqp" {
publishAmqpTCPPort = "5672"
} else {
publishAmqpTCPPort = "5671"
}
}
publishURISuffix := os.Getenv("PUBLISH_URI_SUFFIX")
subscribeAmqpServer := os.Getenv("SUBSCRIBE_AMQP_SERVER")
if subscribeAmqpServer == "" {
subscribeAmqpServer = publishAmqpServer
}
subscribeAmqpTCPPort := os.Getenv("SUBSCRIBE_AMQP_SERVER_TCP")
if subscribeAmqpTCPPort == "" {
subscribeAmqpTCPPort = publishAmqpTCPPort
}
subscribeURISuffix := os.Getenv("SUBSCRIBE_URI_SUFFIX")
if subscribeURISuffix == "" {
subscribeURISuffix = publishURISuffix
}
publishUsername := os.Getenv("PUBLISH_USERNAME")
if publishUsername == "" {
publishUsername = "guest"
}
publishPassword := os.Getenv("PUBLISH_PASSWORD")
if publishPassword == "" {
publishPassword = "<PASSWORD>"
}
subscribeUsername := os.Getenv("SUBSCRIBE_USERNAME")
if subscribeUsername == "" {
subscribeUsername = publishUsername
}
subscribePassword := os.Getenv("SUBSCRIBE_PASSWORD")
if subscribePassword == "" {
subscribePassword = publishPassword
}
publishQ := os.Getenv("PUBLISH_Q")
subscribeQ := os.Getenv("SUBSCRIBE_Q")
return protocol, publishAmqpServer, publishAmqpTCPPort, publishUsername, publishPassword, publishURISuffix, subscribeAmqpServer, subscribeAmqpTCPPort, subscribeURISuffix, subscribeUsername, subscribePassword, publishQ, subscribeQ, timeout
}
func SendMsg(ch *amqp.Channel, queue string, payload string) (string, error) {
log.Printf("Attempting to write payload '%s' to queue '%s'\n", payload, queue)
q, err := ch.QueueDeclare(
queue, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return "", fmt.Errorf("Failed to declare a queue:%v", err)
}
body := payload
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
if err != nil {
return "", fmt.Errorf("Failed to publish a message: %v", err)
}
return body, nil
}
func RecvMsg(ch *amqp.Channel, queue string, timeout int64) (string, error) {
log.Printf("Reading from queue '%s'\n", queue)
ch.Qos(1, 0, false)
q, err := ch.QueueDeclare(
queue, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return "", fmt.Errorf("Failed to declare a queue")
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack - set to false to ensure only a single message gets read off the queue at a time
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return "", fmt.Errorf("Failed to register a consumer")
}
//log.Printf("msgs: %v\n", msgs)
var msg string
duration := time.Duration(timeout) * time.Millisecond
timer := time.NewTimer(duration)
for {
select {
case d := <-msgs:
//log.Printf("d: %v\n", d)
timer.Reset(duration)
log.Printf("Received a message: '%s'\n", d.Body)
msg = string(d.Body)
case <-timer.C:
log.Println("Timeout !")
return "", fmt.Errorf("Timeout waiting for message to appear")
}
return msg, nil
}
}
type PactDetail struct {
testName string
reqBody string
respBody interface{}
}
func getAmqpChannel(uri string) (*amqp.Channel, error) {
conn, err := amqp.Dial(uri)
if err != nil {
return nil, fmt.Errorf("Failed to connect to RabbitMQ: %v", err)
}
ch, err := conn.Channel()
if err != nil {
return nil, fmt.Errorf("Failed to open a channel: %v", err)
}
return ch, nil
}
func TestAMQPConsumerProvider(t *testing.T) {
protocol, publishQServer, publishQServerPort, publishUsername, publishPassword, publishURISuffix, subscribeQServer, subscribeQServerPort, subscribeURISuffix, subscribeUsername, subscribePassword, publishQ, subscribeQ, timeout := readEnvVars()
publishURI := fmt.Sprintf("%s://%s:%s@%s:%s/%s", protocol, publishUsername, publishPassword, publishQServer, publishQServerPort, publishURISuffix)
subscribeURI := fmt.Sprintf("%s://%s:%s@%s:%s/%s", protocol, subscribeUsername, subscribePassword, subscribeQServer, subscribeQServerPort, subscribeURISuffix)
pubCh, err := getAmqpChannel(publishURI)
if err != nil {
t.Fatalf("%v\n", err)
}
var subCh *amqp.Channel
if subscribeURI != publishURI {
// we're reading from a different queue server; need a different channel
subCh, err = getAmqpChannel(subscribeURI)
if err != nil {
t.Fatalf("%v\n", err)
}
} else {
// use the same channel for subscribe as for publish
subCh = pubCh
}
t.Logf("Publishing to %s\n", publishURI)
t.Logf("Subscribing to %s\n", subscribeURI)
///////
var testCases = []PactDetail{
{"TestA", "hello", "hello"},
{"TestB", "there", "there"},
{"TestC", "everywhere", "everywhere"},
}
///////
concurrency := 1
swg := sizedwaitgroup.New(concurrency)
for _, tc := range testCases {
swg.Add()
go func(t *testing.T, tc PactDetail) {
defer swg.Done()
t.Run(tc.testName, func(t *testing.T) {
_, err := SendMsg(pubCh, publishQ, tc.reqBody)
if err != nil {
t.Logf("Failed to send message '%s': %v\n", tc.reqBody, err)
t.Fail()
}
responsePayload, _ := RecvMsg(subCh, subscribeQ, timeout)
if tc.respBody != responsePayload {
t.Logf("Expected response '%s' doesn't match actual response '%s'\n", tc.respBody, responsePayload)
t.Fail()
} else {
t.Log("Expected payload matches actual payload")
}
})
}(t, tc)
}
swg.Wait()
}
|
<filename>pidfile.c
#include <stdio.h>
#include <assert.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include "pidfile.h"
#define BUF_SIZE 64
static int lock_file(int fd, short int type, short int whence, off_t start, off_t len)
{
struct flock fl;
fl.l_type = type;
fl.l_whence = whence;
fl.l_start = start;
fl.l_len = len;
fl.l_pid = 0;
#ifdef F_OFD_SETLK
return fcntl(fd, F_OFD_SETLK, &fl);
#else
return fcntl(fd, F_SETLK, &fl);
#endif
}
int create_pid_file(const char* path)
{
int fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (-1 == fd) {
return -1;
}
if (lock_file(fd, F_WRLCK, SEEK_SET, 0, 0) == -1) {
int e = errno;
close(fd);
errno = e;
if (e == EAGAIN || e == EACCES) {
/* PID file locked - another instance is running */
return -2;
}
return -1;
}
if (ftruncate(fd, 0) == -1) {
int e = errno;
close(fd);
errno = e;
return -1;
}
#ifndef F_OFD_SETLK
if (lock_file(fd, F_UNLCK, SEEK_SET, 0, 0) == -1) {
assert(0);
}
#endif
return fd;
}
int write_pid(int fd)
{
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "%ld\n", (long int)getpid());
#ifndef F_OFD_SETLK
if (lock_file(fd, F_WRLCK, SEEK_SET, 0, 0)) {
return -1;
}
#endif
if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) {
return -1;
}
return fsync(fd);
}
|
A Greek official says one of the assailants in Friday’s terrorist attacks in Paris whose Syrian passport was found at the scene crossed into the European Union through the Greek island of Leros in October.
Citizen Protection Minister Nikos Toskas, in charge of police forces, has released the following statement: “On the case of the Syrian passport found at the scene of the terrorist attack.
“We announce that the passport holder had passed from Leros on Oct. 3. where he was identified based on EU rules… We do not know if the passport was checked by other countries through which the holder likely passed.
“We will continue the painstaking and persistent effort to ensure the security of our country and Europe under difficult circumstances, insisting on complete identification of those arriving.”
An employee at Greece’s Ministry of Citizen Protection says Greek police have sent the fingerprints of the owner of the Syrian passport found at one of Friday’s attacks in Paris to French police.
Police are trying to see if they match those of the assailant whose body was found nearby — or any other person known to police.
The same source, who spoke to the Associated Press on condition of anonymity because she was not authorized to comment on an investigation, discounted reports in Greek media that a second passport was found at the scene.
At least 129 people were killed and 352 injured in the attacks Friday night in Paris. The Islamic State group has claimed responsibility
Earlier today, two French police officials say that authorities have identified one of the suicide bombers who targeted Paris in deadly attacks as a young Frenchman flagged in the past for links with an Islamic extremist activity.
The officials said the man was among attackers who blew himself up after a rampage and hostage-taking in a Paris concert hall.
Earlier, police officials said at least one suicide bombers who targeted another site, France’s national stadium, was found to have a Syrian passport.
None of the attackers has been publicly identified. |
Police in Cambridge are warning residents that the sounds of gunfire they may hear Tuesday night will be to test its ShotSpotter system.
Cambridge Police are alerting residents that the department will be using gunfire sounds to test the city's ShotSpotter system Tuesday night.
Police said the department will conduct "live-fire gunshot training" on Tuesday between 8 p.m. and 9:30 p.m. in the Area 4 and Inman neighborhoods.
"The controlled testing is being conducted for sensor calibrations, quality of gunshot detection and validation of analysis purposes," police said. "The training exercise presents no danger to the public and we urge residents not to be alarmed."
The tests will consist of a sequence of gunshot sounds. Testing areas will be held in cordoned-off areas away from the public.
ShotSpotter, which is also used in Boston, detects the sound of the gunfire explosion as it radiates out from the point of origin and helps officers quickly locate the exact spot a gun was fired, police said. |
Utilizing sport to build trust the case of Cyprus Abstract The Republic of Cyprus became an independent state in 1960. It has been de facto divided since 1974. Efforts over the past 30 years to solve the Cyprus problem and reunify the island have not yet been successful yet. Various attempts have been made at different levels from politicians, professionals and the United Nations to bring the two communities on the island together but again these attempts have been without success. Sport has never been utilized in these attempts. Sports carry specific rules, norms and values that are in many instances more flexible than the ones adapted in general in social settings. Sport has been perceived as being a great socialization agent. The code of ethics in sports allow participants to interact at a different level, thus developing trust that can be transferred to other areas of life. Thus, the organization of summer camps through the Doves Olympic Movement presents the first attempt on the island of Cyprus to utilize sport and related activities to build trust in Greek Cypriot and Turkish Cypriot children. The purpose of the project was to enhance favourable development and relationships between Greek Cypriot and Turkish Cypriot youths from the two communities in conflict. This paper examines the impact that the summer camps had on the children and instructors who participated in the camps, and how this participation managed to change their perceptions in relation to specific issues. |
'Suburgatory' stars out their energy-wasting and recycling-mad relatives.
September 28, 2011, 3:21 p.m.
"I follow my wife around the house turning off lights. I think she grew up in a house where the lights were always on, but she's changing," reports Jeremy Sisto optimistically. "I drive a hybrid. We've been talking a lot about making our footprint smaller. Moving from New York to L.A., it's pretty big, so we have more to do on that score. But it's important to us to focus on that in the next period of our lives."
Sisto and his family are subletting a house in the Hollywood Hills while he's shooting his new ABC sitcom "Suburgatory," which premieres Sept. 28. He plays a contractor and single dad who moves his teenage daughter from the city to the suburbs after discovering condoms in her room (despite her protests that they weren't hers). "He's an angry optimist, and I thought he had some depth," says Sisto, who was open to doing comedy after "Law & Order," and in fact, recently wrote a script for a comedy film about doubles tennis called "Break Point."
He credits a few comedy shorts he'd done with helping to convince producers he was right for lighter fare, something he wanted to do after having turned away from it after "Clueless." "The other shows I was offered this season were crime shows and I knew I wasn't going to do that. This is about a relationship, and for me that's more fun to play," says the actor, who has a daughter of his own, just 2 years old. "I feel very lucky to be able to go from a crime procedural to something like this. I think that sometimes is a difficult transition for actors, and so I feel very fortunate that I've been able to do that."
"My mom is the recycling Nazi, and I always bring a bag to the grocery store," says Jane Levy, who plays Sisto's daughter Tessa, and narrates the series. Now 21, she grew up in suburban Marin County, Calif., and though she "wasn't exactly like Tessa in high school, I was friends with some of the mean girls. Not that I was a mean girl, but I was a floater — I got along with everyone. I had the new girl experience in other ways. I went to England for five months when I was in high school, by myself, so I did experience a bit of being the fish out of water."
Levy saw the role as a challenge, "because on paper she could be read as really snarky and annoying" — she'd have to work to bring heart to it. Fairly new to Hollywood, she appeared on Showtime's "Shameless" in its first season and plays Victoria Justice's best friend in the Halloween comedy "Fun Size," due out in Oct. 2012. "I play a girl who's trying way too hard to be popular," she says. |
Resolution of Disseminated Intravascular Coagulation in a Patient with COVID-19 and Associated SepsisInduced Neutropenia COVID-19 has been associated with a hypercoagulable state and thrombotic events. Venous thromboembolism has been the most commonly reported type of thrombosis but also arterial thrombosis and disseminated intravascular coagulation in inpatients have been described frequently in several clinical experiences. Patients with COVID-19, because of its tendency to induce leucopenia and overlapping of bacterial infection, may experience sudden disseminated intravascular coagulation (DIC), as in the case that we report here. However, early diagnosis and treatment may be associated with positive resolution of these severe complications. Introduction Coagulopathy with a trend towards a hypercoagulable state and thrombotic complications has been described since the first reports on COVID-19 were presented. Disseminated intravascular coagulation (DIC) is an induced complication associated with several infections and it has been reported also as a complication in patients with COVID-19. DIC, in fact, occurs when the viral damage is associated with endothelial damage that may also induce ischemia of tissues and organs. However, DIC is also a well-known complication of bacterial sepsis that may be a consequence of viral infections and/or of immunodeficiencies such as lymphocytopenia or neutropenia. SARS-CoV-2 is one virus which is able to induce lymphocytopenia, while neutropenia has been rarely reported. We here report a case of a 63-year-old male who, during hospitalization for COVID-19, developed sudden neutropenia that induced bacterial sepsis and associated DIC. Case History LR, a 63-year-old male, required hospitalization for bilateral ground glass pneumonia due to SARS-CoV-2 infection (i.e., COVID-19). In the emergency room, he presented with fever and dyspnea, and a nasopharyngeal swab revealed positivity for SARS-CoV-2 infection; his laboratory values were typical of COVID-19, with an increase in C reactive protein (CRP), lactate deydrogenase (LDH), d-dimer, fibrinogen and with a reduced count of lymphocytes (Table 1). His treatment was based on full doses of systemic antibiotics (i.e., piperacilline-tazobactam 13.5 g daily; full doses of dexamethasone (i.e., 6 mg daily), prophylactic doses of enoxaparin (i.e., 4000 U daily), systemic intravenous fluconazole (i.e., 100 mg daily), oxygen therapeutic support with high-flow nasal cannula (HFNC)). The Medicina 2021, 57, 106 2 of 4 patient underwent this treatment without side effects for 10 days, with an improvement in his overall respiratory performance, improvement in pulse oximetry and regression of fever; his laboratory markers also revealed an improvement, as reported in Table 1, and Doppler ultrasound scan excluded deep vein thrombosis of the lower limbs. Starting from day 11, the patient experienced chills twice daily, with new occurrence of fever, and new laboratory screening revealed sudden neutropenia with associated increase in d-dimer (i.e., 56,000 mcg/dL) and decrease in platelets (i.e., 46.000 mmcube). CRP showed a new strong increase and also procalcitonin showed a relevant and pathological increase. Assessment of clinical signs and symptoms was repeated on the following day and laboratory data confirmed the previously observed trend (Table 1) (Figure 1). Furthermore, several blood cultures were performed while the patient was experiencing chills in order to detect bacterial sepsis but none of them identified a bacterial pathogen. Medicina 2021, 57, x FOR PEER REVIEW 2 of 4 protein (CRP), lactate deydrogenase (LDH), d-dimer, fibrinogen and with a reduced count of lymphocytes (Table 1). His treatment was based on full doses of systemic antibiotics (i.e., piperacilline-tazobactam 13.5 g daily; full doses of dexamethasone (i.e., 6 mg daily), prophylactic doses of enoxaparin (i.e., 4000 U daily), systemic intravenous fluconazole (i.e., 100 mg daily), oxygen therapeutic support with high-flow nasal cannula (HFNC)). The patient underwent this treatment without side effects for 10 days, with an improvement in his overall respiratory performance, improvement in pulse oximetry and regression of fever; his laboratory markers also revealed an improvement, as reported in Table 1, and Doppler ultrasound scan excluded deep vein thrombosis of the lower limbs. Starting from day 11, the patient experienced chills twice daily, with new occurrence of fever, and new laboratory screening revealed sudden neutropenia with associated increase in d-dimer (i.e., 56,000 mcg/dL) and decrease in platelets (i.e., 46.000 mmcube). CRP showed a new strong increase and also procalcitonin showed a relevant and pathological increase. Assessment of clinical signs and symptoms was repeated on the following day and laboratory data confirmed the previously observed trend (Table 1) (Figure 1). Furthermore, several blood cultures were performed while the patient was experiencing chills in order to detect bacterial sepsis but none of them identified a bacterial pathogen. We implemented a withdrawal of enoxaparin and desamethazone and we began pulse therapy with intravenous 3 g methylprednisolone on the first day, 2 g on the second day and 1 g on the third, with an associated a single shot of subcutaneous growth colony factor lenograstrin (i.e., 34 Millions UI/mL daily) in order to improve the count of neutrophils. We also started treatment of DIC with 2 units twice daily of fresh frozen plasma for three consecutive days in order to restore induced coagulopathy and prevent microthromboses of tissues and organs. From the first day of treatment, the patient showed a clinical improvements concerning chills and fever and progressive improvements were recorded in laboratory markers, as reported in Table 1 and Figure 1. After three days of the new therapeutic approach, all treatments were interrupted (also antibiotics and antimycotics) and clinical surveillance was performed for two additional days; then, the patient was dismissed, with improved clinical condition with normal laboratory markers and with improved lung performance (Table 1) on day 17 of his hospitalization. Discussion DIC is always a consequence of another underlying disease or infection. Bacterial sepsis is more frequently associated with DIC because the bacterial wall is able to induce hyperactivation of the clotting system by several mechanisms ; however, hyperactivation of the clotting system with a trend toward DIC has been described during viral infections of COVID-19 since the first reports were presented from China. SARS-CoV-2 is able to induce a hypercoagulable state via cytokine storm and the induction of the peptidase cascade as angiotensin-converting enzyme (ACE) as complement toward the kallikrein system, which may activate clotting factor XII and so the intrinsic pathway of coagulation. The hyperaction of the peptidases and clotting system, present also in other forms of DIC, induces an increase in d-dimer and the progressive consumption of clotting factors until the decrease in fibrinogen and platelets results in multiple bleedings and shock. On the other hand, SARS-CoV-2 may also induce alteration of white blood cells and lymphocytopenia has been frequently reported in the first phases of infection. However, in severe clinical forms of COVID-19, neutropenia is also described and neutropenia is frequent in febrile patients with bacterial sepsis for other reasons. In the case that we reported, the occurrence of neutropenia was quickly followed by the clinical complications of DIC and systemic sepsis. The early identification of both complications permitted us to begin treatment rapidly for neutropenia and DIC with early restoration of all clinical and laboratory parameters including neutrophils, platelets and procalcitonin. The management of this case may contribute to the improved clinical screening of patients with COVID-19 and associated DIC, because early identification and treatment could allow good outcomes following these severe complications. |
Rating Advisers on Effectiveness as Teachers Why should we do it? For at least three reasons. First, its right that the issue be raised. Second, we can define and plan better than anyone else. Third, it is in our best interest to do so. First, the issue of accountability ought to be raised. Accountability, evaluation, value-added education call it what you will is an idea whose time has come. Actually, accountability as an important concept entered the American mainstream at least a dozen years ago in the aftermath of Watergate. (some form of accountability as a principle has been around forever, of course.) Second, if we are to be judged on our teaching effectiveness, who is better prepared to define what this evaluation should include and how it might be measured than those of us associated with student publications? We know where the bodies are buried. We know what the real problems of advising are and how effective teachers deal with them. (It is assumed that we agree advisers are teachers; that the prinapal function of advisers is to assist students with whom they work to develop as journalists and communicators in preparation for their professional careers.) Thiid. we should do it. |
<filename>app/src/main/java/com/cspirat/RangeAddition.java
package com.cspirat;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : RangeAddition
* Creator : Edward
* Date : Oct, 2017
* Description : 370. Range Addition
*/
public class RangeAddition {
/**
* Assume you have an array of length n initialized with all 0's and are given k update operations.
Each operation is represented as a triplet: [startIndex, endIndex, inc]
which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.
Return the modified array after all k operations were executed.
* Example:
Given:
length = 5,
updates = [
[1, 3, 2],
[2, 4, 3],
[0, 2, -2]
]
Output:
[-2, 0, 3, 5, 3]
Explanation:
Initial state:
[ 0, 0, 0, 0, 0 ]
After applying operation [1, 3, 2]:
[ 0, 2, 2, 2, 0 ]
After applying operation [2, 4, 3]:
[ 0, 2, 5, 5, 3 ]
After applying operation [0, 2, -2]:
[-2, 0, 3, 5, 3 ]
time : O(K + N);
space : O(n)
* @param length
* @param updates
* @return
*/
public int[] getModifiedArray(int length, int[][] updates) {
int[] res = new int[length];
for (int[] update : updates) {
int value = update[2];
int start = update[0];
int end = update[1];
res[start] += value;
if (end + 1 < length) {
res[end + 1] -= value;
}
}
for (int i = 1; i < length; i++) {
res[i] += res[i - 1];
}
return res;
}
}
|
Growth arrest specific 1 (Gas1) and glial cell line-derived neurotrophic factor receptor 1 (Gfr1), two mouse oocyte glycosylphosphatidylinositol-anchored proteins, are involved in fertilisation. Recently, Juno, the oocyte receptor for Izumo1, a male immunoglobulin, was discovered. Juno is an essential glycosylphosphatidylinositol (GIP)-anchored protein. This result did not exclude the participation of other GIP-anchored proteins in this process. After bibliographic and database searches we selected five GIP-anchored proteins (Cpm, Ephrin-A4, Gas1, Gfra1 and Rgmb) as potential oocyte candidates participating in fertilisation. Western blot and immunofluorescence analyses showed that only three were present on the mouse ovulated oocyte membrane and, of these, only two were clearly involved in the fertilisation process, namely growth arrest specific 1 (Gas1) and glial cell line-derived neurotrophic factor receptor 1 (Gfr1). This was demonstrated by evaluating oocyte fertilisability after treatment of oocytes with antibodies against the selected proteins, with their respective short interference RNA or both. Gfr1 and Gas1 seem to be neither redundant nor synergistic. In conclusion, oocyte Gas1 and Gfr1 are both clearly involved in fertilisation. |
<reponame>abbasqasemi/wordpres
/*
* Copyright (C) 2019 All rights reserved for FaraSource (ABBAS GHASEMI)
* https://farasource.com
*/
package ghasemi.abbas.wordpress;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import androidx.core.content.FileProvider;
import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import ja.burhanrashid52.photoeditor.OnSaveBitmap;
import ja.burhanrashid52.photoeditor.PhotoEditor;
import ja.burhanrashid52.photoeditor.PhotoEditorView;
import ghasemi.abbas.wordpress.builder.BuildApp;
public class PhotoEditActivity extends AppCompatActivity {
static Bitmap bitmap;
PhotoEditorView mPhotoEditorView;
PhotoEditor mPhotoEditor;
AppCompatEditText editText;
RelativeLayout colors;
ImageView back, share, pen, markerPen, a, undo, redo, eraser, red, orange, yellow,
green, jadeGreen, blue, mauve, close, done, markerPenColor, aColor, penColor;
int color;
Animation show, hide;
int status;
public static void loadBitmapFromView(View v) {
bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
v.requestLayout();
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_edit);
init();
mPhotoEditor = new PhotoEditor.Builder(this, mPhotoEditorView)
.setPinchTextScalable(true)
.setDefaultTextTypeface(Typeface.createFromAsset(getAssets(), "fonts/" + BuildApp.fontName + ".ttf"))
.build();
mPhotoEditorView.getSource().setImageBitmap(bitmap);
// mPhotoEditorView.getSource().setScaleType(ImageView.ScaleType.FIT_XY);
toolbar();
center();
colors();
bottombar();
}
private void colors() {
red.setOnClickListener(new colors());
orange.setOnClickListener(new colors());
yellow.setOnClickListener(new colors());
green.setOnClickListener(new colors());
jadeGreen.setOnClickListener(new colors());
blue.setOnClickListener(new colors());
mauve.setOnClickListener(new colors());
}
private void init() {
mPhotoEditorView = findViewById(R.id.photoEditorView);
editText = findViewById(R.id.edit_text);
a = findViewById(R.id.a);
aColor = findViewById(R.id.a_color);
close = findViewById(R.id.close);
done = findViewById(R.id.done);
colors = findViewById(R.id.colors);
eraser = findViewById(R.id.eraser);
back = findViewById(R.id.back);
share = findViewById(R.id.share);
pen = findViewById(R.id.pen);
penColor = findViewById(R.id.pen_color);
markerPen = findViewById(R.id.marker_pen);
markerPenColor = findViewById(R.id.marker_pen_color);
undo = findViewById(R.id.undo);
redo = findViewById(R.id.redo);
red = findViewById(R.id.red);
mauve = findViewById(R.id.mauve);
blue = findViewById(R.id.blue);
jadeGreen = findViewById(R.id.jade_green);
green = findViewById(R.id.green);
yellow = findViewById(R.id.yellow);
orange = findViewById(R.id.orange);
show = AnimationUtils.loadAnimation(this, R.anim.fade_in);
hide = AnimationUtils.loadAnimation(this, R.anim.fade_out);
show.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
editText.clearAnimation();
colors.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
hide.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
editText.clearAnimation();
colors.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private void center() {
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (editText.getText().toString().trim().isEmpty()) {
editText.setText("");
return false;
}
mPhotoEditor.addText(editText.getText().toString(), color);
close();
return true;
}
});
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editText.getText().toString().trim().isEmpty()) {
editText.setText("");
return;
}
mPhotoEditor.addText(editText.getText().toString(), color);
close();
}
});
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
close();
}
});
}
private void close() {
if (editText.getVisibility() == View.GONE) {
return;
}
keyboard(false);
editText.setVisibility(View.GONE);
done.setVisibility(View.GONE);
close.setVisibility(View.GONE);
editText.setText("");
}
private void keyboard(boolean show) {
try {
InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
if (show) {
editText.startAnimation(this.show);
imm.showSoftInput(editText, 0);
buttonEnabled(false);
} else {
editText.startAnimation(hide);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
buttonEnabled(true);
}
} catch (Exception e) {
//
}
}
private void bottombar() {
eraser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (colors.getVisibility() == View.VISIBLE) {
colors.startAnimation(hide);
colors.setVisibility(View.GONE);
}
aColor.setVisibility(View.INVISIBLE);
markerPenColor.setVisibility(View.INVISIBLE);
penColor.setVisibility(View.INVISIBLE);
mPhotoEditor.brushEraser();
}
});
undo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPhotoEditor.undo();
}
});
redo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPhotoEditor.redo();
}
});
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
status = 1;
setColors();
}
});
pen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
status = 0;
setColors();
}
});
markerPen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
status = 2;
setColors();
}
});
}
private void setColors() {
if (colors.getVisibility() == View.GONE) {
colors.startAnimation(show);
colors.setVisibility(View.VISIBLE);
} else {
colors.startAnimation(hide);
colors.setVisibility(View.GONE);
}
}
private void buttonEnabled(boolean isEnabled) {
pen.setEnabled(isEnabled);
a.setEnabled(isEnabled);
markerPen.setEnabled(isEnabled);
undo.setEnabled(isEnabled);
eraser.setEnabled(isEnabled);
redo.setEnabled(isEnabled);
}
private void toolbar() {
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
share.setOnClickListener(new View.OnClickListener() {
boolean doing = false;
@Override
public void onClick(View v) {
if (doing) {
return;
}
doing = true;
mPhotoEditor.saveAsBitmap(new OnSaveBitmap() {
@Override
public void onBitmapReady(Bitmap saveBitmap) {
try {
File file = new File(getExternalFilesDir(null), getString(R.string.app_name) + ".png");
if (file.exists()) {
Log.e("Sdsd", "sd");
file.delete();
}
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.close();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(PhotoEditActivity.this, getPackageName() + ".provider", file));
startActivity(Intent.createChooser(intent, "اشتراک خبر ..."));
} catch (Exception e) {
//
}
doing = false;
}
@Override
public void onFailure(Exception e) {
doing = false;
Toast.makeText(PhotoEditActivity.this, "با عرض پوزش،خطائی پیش آمده است", Toast.LENGTH_SHORT).show();
}
});
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
bitmap = null;
}
private float getDP(int i) {
return getResources().getDisplayMetrics().density * i;
}
class colors implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.red:
color = 0xffE53935;
break;
case R.id.orange:
color = 0xffFB8C00;
break;
case R.id.yellow:
color = 0xffFDD835;
break;
case R.id.green:
color = 0xff43A047;
break;
case R.id.jade_green:
color = 0xff00ACC1;
break;
case R.id.blue:
color = 0xff1E88E5;
break;
case R.id.mauve:
color = 0xff8E24AA;
break;
}
setColors();
if (status == 0) {
mPhotoEditor.setBrushDrawingMode(true);
mPhotoEditor.setBrushColor(color);
mPhotoEditor.setBrushSize(getDP(5));
mPhotoEditor.setOpacity(100);
penColor.setColorFilter(color, PorterDuff.Mode.SRC_IN);
penColor.setVisibility(View.VISIBLE);
markerPenColor.setVisibility(View.INVISIBLE);
aColor.setVisibility(View.INVISIBLE);
close();
} else if (status == 1) {
if (editText.getVisibility() == View.VISIBLE) {
return;
}
mPhotoEditor.setBrushDrawingMode(false);
editText.setVisibility(View.VISIBLE);
done.setVisibility(View.VISIBLE);
close.setVisibility(View.VISIBLE);
editText.requestFocus();
aColor.setColorFilter(color, PorterDuff.Mode.SRC_IN);
aColor.setVisibility(View.VISIBLE);
markerPenColor.setVisibility(View.INVISIBLE);
penColor.setVisibility(View.INVISIBLE);
keyboard(true);
} else {
mPhotoEditor.setBrushDrawingMode(true);
mPhotoEditor.setBrushColor(color);
mPhotoEditor.setBrushSize(getDP(15));
mPhotoEditor.setOpacity(50);
markerPenColor.setColorFilter(color, PorterDuff.Mode.SRC_IN);
markerPenColor.setVisibility(View.VISIBLE);
aColor.setVisibility(View.INVISIBLE);
penColor.setVisibility(View.INVISIBLE);
close();
}
}
}
}
|
Dens in Dente in a Six Year Old Doberman Pinscher Developmental abnormalities of tooth shape and form are rare. Identification of dens in dente is made by radiographic and clinical examination. Pulpitis, pulp necrosis and periapical inflammation can be associated with this abnormality. The tooth should be evaluated for endodontic therapy. A review of the literature related to dens in dente is described with the findings in a doberman pinscher. |
With all of the attention being focused on the untiring efforts of the deep state to undermine our president, it is easy to forget how much his family is suffering.
Thankfully, as long as Donald Trump, Jr. has the strength to open his mouth and whine about his troubles, the first family’s plight is never far from our minds.
The first son (and if he is the first, please save us from the last) took his “Why’s Everybody Always Picking On Me” tour on the road to West Palm Beach, Florida, on Tuesday night, where he brushed aside his fears of shadow bureaucrats who are out to get him to tell his story at the Turning Point USA Student Action Summit, a speech that was first noted by CNN.
It is not just words Trump Jr. said as the audience hung on his every utterance. Because he tried to help his father, because he did his duty as any American citizen who had a chance to have a meeting with a Russian who claims to have the dirt on Hillary Clinton would, he was put through hours of torture by those who are out to get him.
Trump told of his interrogation at the hands of the House Intelligence Committee. Although they did not slap the 39-year-old holder of his father’s blind trust around, shine bright lights in his face for hours, or stick bamboo chutes under his fingernails, they did something far, far worse.
The Democrats on the committee grilled him mercilessly about a meeting that lasted only a few minutes (and failed to get him any dirt on Hillary). They tried to get him to say what he told his father after the meeting became public knowledge and they were trying to compose a response.
Fortunately, he remembered father-son privilege and that there was also an attorney present.
The Republicans on the committee weren’t any better.
They kept asking Trump Jr. if he needed his drink refreshed.
The president’s oldest revealed to the young conservatives the secret of what is happening to the United States and why the deep state has taken aim at him.
It’s a “rigged system,” he confided, giving them a few moments to absorb the shocking news that the older Donald Trump was right all along.
“It is and you’ve seen it,” Trump Jr. said.
Just in case any skeptics remained in the crowd, he provided the evidence to prove his conspiracy theory.
Trump Jr. asked the crowd to imagine what would have happened in 2008 if someone had tried to show that Barack Obama’s election was not legitimate.
The young conservatives racked their brains trying to envision such a thing.
Once he was sure they were on the same wavelength, young Trump delivered the telling blow. If that had happened, the fake media would have been all over the news like a Trump on a birther theory, he said, though he neglected to use that simile.
When Donald Trump Jr. concluded his speech, he received rapturous applause, and as he left the summit, he looked left and then right, surveying the scene cautiously. After all, you can’t be too careful.
The deep state is everywhere. |
Generating Isogenic Deletions (Knockouts) in Francisella tularensis, a Highly-infectious and Fastidious Gram-negative Bacterium. Generating bacterial gene deletion mutants, also known as knockouts (KOs), is a powerful tool to investigate individual gene functions. However, fastidious bacteria such as Francisella tularensis (F. tularensis) often are difficult to genetically manipulate. Indeed, many different approaches have been tested to generate F. tularensis mutants. First, Tn5-based EZ::TN transposons have been successfully used to generate transposon libraries in F. tularensis (Qin and Mann, 2006; ). However, creating a comprehensive transposon library with saturating mutations can be laborious, screening for gene disruption requires high-throughput assays where known phenotypes can be measured, and transposons may not completely inactivate the gene of interest or may alter downstream gene expression. Second, group II introns (also referred to as Targetron) have been used to inactivate F. tularensis genes of interest (; ). Targetron functions by forming a complex between plasmid-encoded RNA and chromosomal DNA, followed by group II intron insertion into the gene of interest. The main advantage of Targetron is that it does not require an antibiotic resistance marker. However, as noted for transposons, targetron gene insertions may not eliminate all gene functions or may affect downstream gene expression. Third, homologous recombination can be used to completely replace the chromosomal target gene with a selectable marker, such as an antibiotic resistance marker. This classical genetic technique has been used in many F. tularensis studies (; ; ; ). To accomplish this, a suicide plasmid is engineered to include a selectable marker flanked by regions upstream and downstream of the gene of interest. This KO plasmid can be delivered into host bacteria by many methods, including electroporation, chemical transformation, or conjugation. Here, we describe an optimized procedure to generate KO plasmid constructs, use E. coli to conjugatively transfer the plasmid into F. tularensis, select for F. tularensis KOs using a series of kanamycin-, hygromycin-, and sucrose-resistance steps, and confirm that the gene of interest has been deleted (general overview of the knockout protocol diagramed in Figure 1). This optimized procedure is relatively simple, rapid, and, more importantly, includes a series of both positive and negative selection steps to increase the chances of deleting a target gene from F. tularensis. |
/*-----------------------------------------------------------------------------
/ _trace_prolog_logfile
/ ---------------------
/ Handle the prolog to a prefix string, including outputting the
/ function name if we haven't already.
/
/ In:
/ iDepth = depth in the call stack
/ fForce = ignore flags
/
/ Out:
/ BOOL if trace output should be made
/----------------------------------------------------------------------------*/
BOOL _trace_prolog_logfile(LONG iDepth, BOOL fForce)
{
if ( (LOG_TRACE_MASK & g_CallStackLF[iDepth].m_dwMask) || fForce )
{
if ( iDepth > 0 )
{
if ( !g_CallStackLF[iDepth-1].m_fTracedYet )
_trace_prolog_logfile(iDepth-1, TRUE);
}
if ( !g_CallStackLF[iDepth].m_fTracedYet )
{
_output_proc_name_logfile(iDepth);
g_CallStackLF[iDepth].m_fTracedYet = TRUE;
}
return TRUE;
}
return FALSE;
} |
def connect(self, *args, **kwargs):
self.circuit.check_not_finalized()
if self.inputs:
raise EdzedInvalidState("connect() may by called only once")
if not args and not kwargs:
raise ValueError("No inputs to connect were given")
if '_' in kwargs:
raise ValueError("Input name '_' is reserved")
if args:
for inp in args:
if _is_multiple(inp):
raise ValueError(
f"{inp!r} is not a single input specification; "
"(wrap it in Const() if it is a constant)")
self.inputs['_'] = args
for iname, inp in kwargs.items():
self.inputs[iname] = tuple(inp) if _is_multiple(inp) else inp
return self |
Outcome of Teenage Pregnancy in a Low Resource Setting: A Comparative Study Background: Teenage pregnancy constitutes a high-risk pregnancy due to possible physical, psychological, socio-economic and increased obstetric risks associated with it. These risks though equally present in the older pregnant women are probably less when compared with teenagers. Thus perinatal outcome of pregnancies in these groups of patients varies. Objective: To compare the socio-demographic characteristics, pattern of pregnancy complications and perinatal outcome of pregnancy among primigravid teenagers and older primigravid women. Method: A comparative study was carried out among 58 primigravid teenagers and equal numbers of adult primigravidae at Federal Teaching Hospital, Ido Ekiti, Nigeria over five year period between January 2008 and December, 2012. Their socio-demographic characteristics, booking status, pregnancy complications, estimated gestational age at delivery, mode of delivery, post-partum morbidities, neonatal birth weight and perinatal mortalities were obtained from their case notes. Results: Deliveries by teenagers accounted for 2.48% of all deliveries during the period under review. Teenage age was significantly associated with unmarried status (P in both groups (P > 0.05). Conclusion: Pregnancy and deliveries in teenagers are high risk. Therefore, sex education as well as access to reproductive health information and care will help reduce the occurrence of unwanted pregnancies and their lasting impact on teenagers, their families, and the society. |
<filename>Mediabench/mesa/src/texobj.c
/* $Id: texobj.c,v 1.5 1997/02/09 18:52:15 brianp Exp $ */
/*
* Mesa 3-D graphics library
* Version: 2.2
* Copyright (C) 1995-1997 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* $Log: texobj.c,v $
* Revision 1.5 1997/02/09 18:52:15 brianp
* added GL_EXT_texture3D support
*
* Revision 1.4 1997/01/16 03:35:34 brianp
* added calls to device driver DeleteTexture() and BindTexture() functions
*
* Revision 1.3 1997/01/09 19:49:47 brianp
* added a check to switch rasterizers if needed in glBindTexture()
*
* Revision 1.2 1996/09/27 17:09:42 brianp
* removed a redundant return statement
*
* Revision 1.1 1996/09/13 01:38:16 brianp
* Initial revision
*
*/
#include <assert.h>
#include <stdlib.h>
#include "context.h"
#include "macros.h"
#include "teximage.h"
#include "texobj.h"
#include "types.h"
/*
* Allocate a new texture object structure. The name and dimensionality are
* set to zero here and must be initialized by the caller.
*/
struct gl_texture_object *gl_alloc_texture_object( void )
{
struct gl_texture_object *obj;
obj = (struct gl_texture_object *)
calloc(1,sizeof(struct gl_texture_object));
if (obj) {
/* init the non-zero fields */
obj->WrapS = GL_REPEAT;
obj->WrapT = GL_REPEAT;
obj->MinFilter = GL_NEAREST_MIPMAP_LINEAR;
obj->MagFilter = GL_LINEAR;
}
return obj;
}
/*
* Append a gl_texture_object struct to a list of texture objects.
*/
static void append_texture_object( struct gl_texture_object *list,
struct gl_texture_object *obj )
{
struct gl_texture_object *t;
t = list;
while (t->Next) {
t = t->Next;
}
t->Next = obj;
}
/*
* Deallocate a texture object struct and all children structures
* and image data.
*/
void gl_free_texture_object( struct gl_texture_object *t )
{
GLuint i;
for (i=0;i<MAX_TEXTURE_LEVELS;i++) {
if (t->Image[i]) {
gl_free_texture_image( t->Image[i] );
}
}
free( t );
}
/*
* Given a texture object name, return a pointer to the texture object.
*/
static struct gl_texture_object *
find_texture_object( GLcontext *ctx, GLuint name )
{
struct gl_texture_object *t;
assert( name>0 );
t = ctx->Shared->TexObjectList;
while (t) {
if (t->Name == name) {
return t;
}
t = t->Next;
}
return NULL;
}
void gl_GenTextures( GLcontext *ctx, GLsizei n, GLuint *textures )
{
struct gl_texture_object *t;
GLuint i, max;
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glGenTextures" );
return;
}
if (n<0) {
gl_error( ctx, GL_INVALID_VALUE, "glGenTextures" );
return;
}
/* Find maximum texture object name in use */
t = ctx->Shared->TexObjectList;
max = 0;
while (t) {
if (t->Name>max) {
max = t->Name;
}
t = t->Next;
}
/* Return new texture names starting at max+1 */
for (i=0;i<n;i++) {
max++;
textures[i] = max;
}
}
void gl_DeleteTextures( GLcontext *ctx, GLsizei n, const GLuint *textures)
{
GLuint i;
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glAreTexturesResident" );
return;
}
for (i=0;i<n;i++) {
struct gl_texture_object *t, *tprev, *tcurr;
if (textures[i]>0) {
t = find_texture_object( ctx, textures[i] );
if (t) {
if (ctx->Texture.Current1D==t) {
/* revert to default 1-D texture */
ctx->Texture.Current1D = ctx->Shared->TexObjectList;
t->RefCount--;
assert( t->RefCount >= 0 );
}
else if (ctx->Texture.Current2D==t) {
/* revert to default 2-D texture */
ctx->Texture.Current2D = ctx->Shared->TexObjectList->Next;
t->RefCount--;
assert( t->RefCount >= 0 );
}
else if (ctx->Texture.Current3D==t) {
/* revert to default 3-D texture */
ctx->Texture.Current3D = ctx->Shared->TexObjectList->Next;
t->RefCount--;
assert( t->RefCount >= 0 );
}
if (t->RefCount==0) {
/* remove texture object t from the linked list */
tprev = NULL;
tcurr = ctx->Shared->TexObjectList;
while (tcurr) {
if (tcurr==t) {
assert( tprev );
tprev->Next = t->Next;
gl_free_texture_object( t );
break;
}
tprev = tcurr;
tcurr = tcurr->Next;
}
}
/* tell device driver to delete texture */
if (ctx->Driver.DeleteTexture) {
(*ctx->Driver.DeleteTexture)( ctx, textures[i] );
}
}
}
}
}
void gl_BindTexture( GLcontext *ctx, GLenum target, GLuint texture )
{
struct gl_texture_object *oldtexobj;
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glAreTexturesResident" );
return;
}
switch (target) {
case GL_TEXTURE_1D:
oldtexobj = ctx->Texture.Current1D;
if (texture==0) {
/* use default 1-D texture */
ctx->Texture.Current1D = ctx->Shared->TexObjectList;
}
else {
struct gl_texture_object *t;
t = find_texture_object( ctx, texture );
if (t) {
if (t->Dimensions==1) {
/* success! */
ctx->Texture.Current1D = t;
}
else {
/* wrong dimensionality */
gl_error( ctx, GL_INVALID_OPERATION, "glBindTextureEXT" );
return;
}
}
else {
/* create new texture object */
t = gl_alloc_texture_object();
append_texture_object( ctx->Shared->TexObjectList, t );
t->Name = texture;
t->Dimensions = 1;
ctx->Texture.Current1D = t;
}
}
/* Tidy up reference counting */
if (ctx->Texture.Current1D != oldtexobj && oldtexobj->Name>0) {
/* decr reference count of the prev texture object */
oldtexobj->RefCount--;
assert( oldtexobj->RefCount >= 0 );
}
if (ctx->Texture.Current1D->Name>0) {
ctx->Texture.Current1D->RefCount++;
}
#ifdef FOO
if (!ctx->Texture.Current1D->Complete) {
/* re-examine texture completeness */
gl_update_texture_state();
}
#endif
/* Check if we may have to use a new triangle rasterizer */
if (oldtexobj->WrapS != ctx->Texture.Current1D->WrapS
|| oldtexobj->MinFilter != ctx->Texture.Current1D->MinFilter
|| oldtexobj->MagFilter != ctx->Texture.Current1D->MagFilter) {
ctx->NewState |= NEW_RASTER_OPS;
}
/* The current 1D texture object can never be NULL! */
assert(ctx->Texture.Current1D);
break;
case GL_TEXTURE_2D:
oldtexobj = ctx->Texture.Current2D;
if (texture==0) {
/* use default 2-D texture */
ctx->Texture.Current1D = ctx->Shared->TexObjectList->Next;
}
else {
struct gl_texture_object *t;
t = find_texture_object( ctx, texture );
if (t) {
if (t->Dimensions==2) {
/* success */
ctx->Texture.Current2D = t;
}
else {
/* wrong dimensionality */
gl_error( ctx, GL_INVALID_OPERATION, "glBindTexture" );
return;
}
}
else {
/* create new texture object */
t = gl_alloc_texture_object();
append_texture_object( ctx->Shared->TexObjectList, t );
t->Name = texture;
t->Dimensions = 2;
ctx->Texture.Current2D = t;
}
}
/* Tidy up reference counting */
if (ctx->Texture.Current2D != oldtexobj && oldtexobj->Name>0) {
/* decr reference count of the prev texture object */
oldtexobj->RefCount--;
assert( oldtexobj->RefCount >= 0 );
}
if (ctx->Texture.Current2D->Name>0) {
ctx->Texture.Current2D->RefCount++;
}
#ifdef FOO
if (!ctx->Texture.Current2D->Complete) {
/* re-examine texture completeness */
gl_update_texture_state();
}
#endif
/* Check if we may have to use a new triangle rasterizer */
if (oldtexobj->WrapS != ctx->Texture.Current1D->WrapS
|| oldtexobj->WrapT != ctx->Texture.Current1D->WrapT
|| oldtexobj->MinFilter != ctx->Texture.Current1D->MinFilter
|| oldtexobj->MagFilter != ctx->Texture.Current1D->MagFilter) {
ctx->NewState |= NEW_RASTER_OPS;
}
/* The current 2D texture object can never be NULL! */
assert(ctx->Texture.Current2D);
break;
case GL_TEXTURE_3D_EXT:
oldtexobj = ctx->Texture.Current3D;
if (texture==0) {
/* use default 3-D texture */
ctx->Texture.Current1D = ctx->Shared->TexObjectList->Next->Next;
}
else {
struct gl_texture_object *t;
t = find_texture_object( ctx, texture );
if (t) {
if (t->Dimensions==3) {
/* success */
ctx->Texture.Current3D = t;
}
else {
/* wrong dimensionality */
gl_error( ctx, GL_INVALID_OPERATION, "glBindTexture" );
return;
}
}
else {
/* create new texture object */
t = gl_alloc_texture_object();
append_texture_object( ctx->Shared->TexObjectList, t );
t->Name = texture;
t->Dimensions = 3;
ctx->Texture.Current3D = t;
}
}
/* Tidy up reference counting */
if (ctx->Texture.Current3D != oldtexobj && oldtexobj->Name>0) {
/* decr reference count of the prev texture object */
oldtexobj->RefCount--;
assert( oldtexobj->RefCount >= 0 );
}
if (ctx->Texture.Current3D->Name>0) {
ctx->Texture.Current3D->RefCount++;
}
#ifdef FOO
if (!ctx->Texture.Current3D->Complete) {
/* re-examine texture completeness */
gl_update_texture_state();
}
#endif
/* Check if we may have to use a new triangle rasterizer */
if (oldtexobj->WrapS != ctx->Texture.Current3D->WrapS
|| oldtexobj->WrapT != ctx->Texture.Current3D->WrapT
|| oldtexobj->MinFilter != ctx->Texture.Current3D->MinFilter
|| oldtexobj->MagFilter != ctx->Texture.Current3D->MagFilter) {
ctx->NewState |= NEW_RASTER_OPS;
}
/* The current 3D texture object can never be NULL! */
assert(ctx->Texture.Current3D);
break;
default:
gl_error( ctx, GL_INVALID_ENUM, "glBindTexture" );
return;
}
/* Pass BindTexture to device driver */
if (ctx->Driver.BindTexture) {
(*ctx->Driver.BindTexture)( ctx, target, texture );
}
}
void gl_PrioritizeTextures( GLcontext *ctx,
GLsizei n, const GLuint *textures,
const GLclampf *priorities )
{
GLuint i;
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glAreTexturesResident" );
return;
}
if (n<0) {
gl_error( ctx, GL_INVALID_VALUE, "glAreTexturesResident(n)" );
return;
}
for (i=0;i<n;i++) {
struct gl_texture_object *t;
if (textures[i]>0) {
t = find_texture_object( ctx, textures[i] );
if (t) {
t->Priority = CLAMP( priorities[i], 0.0F, 1.0F );
}
}
}
}
GLboolean gl_AreTexturesResident( GLcontext *ctx, GLsizei n,
const GLuint *textures,
GLboolean *residences )
{
GLboolean resident = GL_TRUE;
GLuint i;
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glAreTexturesResident" );
return GL_FALSE;
}
if (n<0) {
gl_error( ctx, GL_INVALID_VALUE, "glAreTexturesResident(n)" );
return GL_FALSE;
}
for (i=0;i<n;i++) {
struct gl_texture_object *t;
if (textures[i]==0) {
gl_error( ctx, GL_INVALID_VALUE, "glAreTexturesResident(textures)" );
return GL_FALSE;
}
t = find_texture_object( ctx, textures[i] );
if (t) {
/* we consider all valid texture objects to be resident */
residences[i] = GL_TRUE;
}
else {
gl_error( ctx, GL_INVALID_VALUE, "glAreTexturesResident(textures)" );
return GL_FALSE;
}
}
return resident;
}
GLboolean gl_IsTexture( GLcontext *ctx, GLuint texture )
{
if (INSIDE_BEGIN_END(ctx)) {
gl_error( ctx, GL_INVALID_OPERATION, "glIsTextures" );
return GL_FALSE;
}
if (texture>0 && find_texture_object(ctx,texture)) {
return GL_TRUE;
}
else {
return GL_FALSE;
}
}
|
import datacon.*;
import java.io.*;
import java.util.Date;
import java.text.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class BloodBankFrame extends JFrame implements ActionListener,ItemListener
{
JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13,l14,l15,l16;
JTextField t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9;
Choice ch1,ch2;
JMenuBar mb;
JMenu m1,m2,m3,m4,m5,m6,m7,m8;
JMenuItem mi1,mi2,mi3,mi4,mi5,mi6,mi7,mi8,mi9,mi10,mi11,mi12,mi13,mi14,mi15;
JPanel p1,p2,p3,p4,p5,p6,p7;
String k=null;
int x=0;
int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a10=0,a11=0,a12=0,a13=0,a14=0,a15=0,a16=0;
String s1=null,s2=null,s3=null,s4=null,s5=null,s6=null,s7=null,s8=null;
FileDialog fd;
FileWriter fw = null;
SimpleDateFormat dateformat;
Date date;
ResultSet rs1,rs2,rs3,rs4,rs5,rs6,rs7,rs8,rs9,rs10,rs11,rs12,rs13;
BloodSql bs;
public BloodBankFrame ()
{
bs = new BloodSql ();
bs.setVisible (true);
try
{
Thread.sleep (10000);
}
catch (Exception e)
{
System.out.println (e);
}
bs.setVisible (false);
try
{
rs1 = bs.show ("select * from donordetails");
rs2 = bs.show ("select * from blooddetails");
}
catch (Exception e)
{
System.out.println (e);
}
setLayout (new GridLayout (7,1));
setBackground (new Color (222,184,135));
setSize (900,900);
setTitle ("Blood Bank Management System");
mb = new JMenuBar ();
setJMenuBar (mb);
m1 = new JMenu ("File");mb.add (m1);
m2 = new JMenu ("Search");mb.add (m2);
m3 = new JMenu ("Insert");mb.add (m3);
m4 = new JMenu ("Token");mb.add (m4);
m5 = new JMenu ("Database");mb.add (m5);
m6 = new JMenu ("Help");mb.add (m6);
mi1 = new JMenuItem ("Open");m1.add (mi1);mi1.addActionListener (this);
mi2 = new JMenuItem ("Save");m1.add (mi2);
mi3 = new JMenuItem ("Save As");m1.add (mi3);mi3.addActionListener (this);
mi4 = new JMenuItem ("Exit");m1.add (mi4);mi4.addActionListener (this);
m7 = new JMenu ("Donor");m2.add(m7);
mi5 = new JMenuItem ("By ID");m7.add (mi5);mi5.addActionListener (this);
mi6 = new JMenuItem ("By Name");m7.add (mi6);mi6.addActionListener (this);
m8 = new JMenu ("Blood");m2.add(m8);
mi7 = new JMenuItem ("By Blood Group");m8.add (mi7);mi7.addActionListener (this);
mi8 = new JMenuItem ("New Donor");m3.add (mi8);mi8.addActionListener (this);
mi9 = new JMenuItem ("New Blood Group");m3.add (mi9);
mi10 = new JMenuItem ("Create");m4.add (mi10);mi10.addActionListener (this);
mi11 = new JMenuItem ("Database Connectivity");m5.add (mi11);
mi12 = new JMenuItem ("Database Name");m5.add (mi12);
mi13 = new JMenuItem ("View Entire Database");m5.add (mi13);
mi14 = new JMenuItem ("Help Topics");m6.add (mi14);
mi15 = new JMenuItem ("About System");m6.add (mi15);
p1 = new JPanel ();
p1.setVisible (false);
p1.setLayout (new FlowLayout());
p1.setBackground (new Color (210,105,30));
l1 = new JLabel ("Enter Blood Group");p1.add(l1);
t1 = new JTextField (20); p1.add(t1);
l1.setHorizontalAlignment(JLabel.CENTER);
l1.setFont (new Font ("Times New Roman",Font.BOLD,25));
b1 = new JButton ("Search Blood Database");p1.add(b1);b1.addActionListener (this);
b2 = new JButton ("Clear");p1.add(b2);b2.addActionListener (this);
add (p1,BorderLayout.CENTER);
p2 = new JPanel ();
p2.setVisible (false);
p2.setLayout (new FlowLayout());
p2.setBackground (new Color (255,255,240));
l2 = new JLabel ("Blood ID");p2.add(l2);
l2.setHorizontalAlignment(JLabel.CENTER);
l2.setFont (new Font ("Times New Roman",Font.BOLD,25));
t2 = new JTextField (10); p2.add(t2);
l3 = new JLabel ("Blood Group");p2.add(l3);
l3.setHorizontalAlignment(JLabel.CENTER);
l3.setFont (new Font ("Times New Roman",Font.BOLD,25));
t3 = new JTextField (10); p2.add(t3);
l4 = new JLabel ("Quantity of Blood");p2.add(l4);
l4.setHorizontalAlignment(JLabel.CENTER);
l4.setFont (new Font ("Times New Roman",Font.BOLD,25));
t4 = new JTextField (10); p2.add(t4);
add (p2,BorderLayout.CENTER);
p3 = new JPanel ();
p3.setVisible (true);
p3.setLayout (new FlowLayout());
p3.setBackground (new Color (30,144,255));
l15 = new JLabel ("Welcome to the System.");p3.add(l15);
l15.setHorizontalAlignment(JLabel.CENTER);
l15.setFont (new Font ("Times New Roman",Font.BOLD,60));
add (p3,BorderLayout.CENTER);
p4 = new JPanel ();
p4.setVisible (false);
p4.setLayout (new FlowLayout());
p4.setBackground (new Color (240,128,128));
l5 = new JLabel ("Enter Donor's ID");p4.add(l5);
l5.setHorizontalAlignment(JLabel.CENTER);
l5.setFont (new Font ("Times New Roman",Font.BOLD,25));
t5 = new JTextField (20); p4.add(t5);
b3 = new JButton ("Search Donor by ID");p4.add(b3);b3.addActionListener (this);
b4 = new JButton ("Clear");p4.add(b4);b4.addActionListener (this);
add (p4,BorderLayout.CENTER);
p5 = new JPanel ();
p5.setVisible (false);
p5.setLayout (new FlowLayout());
p5.setBackground (new Color (255,228,181));
l6 = new JLabel ("Enter Donor's Name");p5.add(l6);
l6.setHorizontalAlignment(JLabel.CENTER);
l6.setFont (new Font ("Times New Roman",Font.BOLD,25));
t6 = new JTextField (20); p5.add(t6);
b5 = new JButton ("Search Donor by Name");p5.add(b5);b5.addActionListener (this);
b6 = new JButton ("Clear");p5.add(b6);b6.addActionListener (this);
add (p5,BorderLayout.CENTER);
p6 = new JPanel ();
p6.setVisible (false);
p6.setLayout (new FlowLayout());
p6.setBackground (new Color (210,180,140));
l7 = new JLabel ("Donor ID");p6.add(l7);
l7.setHorizontalAlignment(JLabel.CENTER);
l7.setFont (new Font ("Times New Roman",Font.BOLD,25));
t7 = new JTextField (10); p6.add(t7);
l8 = new JLabel ("Donor Name");p6.add(l8);
l8.setHorizontalAlignment(JLabel.CENTER);
l8.setFont (new Font ("Times New Roman",Font.BOLD,25));
t8 = new JTextField (20); p6.add(t8);
l9 = new JLabel ("Gender");p6.add(l9);
l9.setHorizontalAlignment(JLabel.CENTER);
l9.setFont (new Font ("Times New Roman",Font.BOLD,25));
t9 = new JTextField (20); p6.add(t9);
ch1 = new Choice ();
ch1.add ("Male");
ch1.add ("Female");
ch1.add ("Others");
p6.add (ch1);ch1.addItemListener (this);
l10 = new JLabel ("Age");p6.add(l10);
l10.setHorizontalAlignment(JLabel.CENTER);
l10.setFont (new Font ("Times New Roman",Font.BOLD,25));
t10 = new JTextField (20); p6.add(t10);
l11 = new JLabel ("Parent's Name");p6.add(l11);
l11.setHorizontalAlignment(JLabel.CENTER);
l11.setFont (new Font ("Times New Roman",Font.BOLD,25));
t11 = new JTextField (20); p6.add(t11);
l12 = new JLabel ("Blood Group");p6.add(l12);
l12.setHorizontalAlignment(JLabel.CENTER);
l12.setFont (new Font ("Times New Roman",Font.BOLD,25));
t12 = new JTextField (10); p6.add(t12);
ch2 = new Choice ();
ch2.add ("A+");
ch2.add ("A-");
ch2.add ("B+");
ch2.add ("B-");
ch2.add ("AB+");
ch2.add ("AB-");
ch2.add ("O+");
ch2.add ("O-");
ch2.add ("H");
p6.add (ch2);ch2.addItemListener (this);
l13 = new JLabel ("Blood Pressure");p6.add(l13);
l13.setHorizontalAlignment(JLabel.CENTER);
l13.setFont (new Font ("Times New Roman",Font.BOLD,25));
t13 = new JTextField (10); p6.add(t13);
l14 = new JLabel ("Donating Times");p6.add(l14);
l14.setHorizontalAlignment(JLabel.CENTER);
l14.setFont (new Font ("Times New Roman",Font.BOLD,25));
t14 = new JTextField (10); p6.add(t14);
b7 = new JButton ("Update");p6.add(b7);b7.addActionListener (this);
b8 = new JButton ("Generate Token");p6.add(b8);b8.addActionListener (this);
b9 = new JButton ("Clear");p6.add(b9);b9.addActionListener (this);
add (p6,BorderLayout.CENTER);
p7 = new JPanel ();
p7.setVisible (true);
p7.setLayout (new FlowLayout());
p7.setBackground (new Color (255,228,196));
l16 = new JLabel ("Last Operation Status");p7.add(l16);
l16.setHorizontalAlignment(JLabel.CENTER);
l16.setFont (new Font ("Times New Roman",Font.BOLD,20));
t15 = new JTextField (20);p7.add(t15);
add (p7,BorderLayout.CENTER);
}
public void actionPerformed (ActionEvent ae)
{
k = ae.getActionCommand ();
if (k.equals("Open"))
{
fd = new FileDialog (this,"Open",0);
fd.show ();
}
if (k.equals("Save As"))
{
fd = new FileDialog (this,"Save",1);
fd.show();
}
if (k.equals("Exit"))
{
System.exit (0);
}
if (k.equals("By ID"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (true);
p5.setVisible (false);
p6.setVisible (false);
}
if (k.equals("By Name"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (true);
p6.setVisible (false);
}
if (k.equals("By Blood Group"))
{
p1.setVisible (true);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (false);
}
if (k.equals("New Donor"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (true);
a2 =1;
try
{
rs7 = bs.show ("select * from blooddata.donordetails");
rs7.last();
a6=rs7.getInt(1) + 1;
t7.setText (""+a6);
}
catch (Exception e)
{
System.out.println (e);
}
}
if (k.equals("Create"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (true);
}
if (k.equals("Search Blood Database"))
{
p1.setVisible (false);
p2.setVisible (true);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (false);
try
{
rs5 = bs.searchBloodGroup (t1.getText());
rs5.next();
t2.setText (""+rs5.getInt (1));
t3.setText (rs5.getString (2));
t4.setText (""+rs5.getInt (3));
t15.setText ("Query Successful.");
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Query Failed.");
}
}
if (k.equals("Search Donor by ID"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (true);
try
{
rs3 = bs.searchDonorID (Integer.parseInt (t5.getText()));
rs3.next();
t7.setText (""+rs3.getInt (1));
t8.setText (rs3.getString (2));
t9.setText (rs3.getString (3));
t10.setText (""+rs3.getInt (4));
t11.setText (rs3.getString (5));
t12.setText (rs3.getString (6));
t13.setText (rs3.getString (7));
t14.setText (""+rs3.getInt (8));
t15.setText ("Query Successful.");
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Query Failed.");
}
}
if (k.equals("Search Donor by Name"))
{
p1.setVisible (false);
p2.setVisible (false);
p4.setVisible (false);
p5.setVisible (false);
p6.setVisible (true);
try
{
rs4 = bs.searchDonorName (t6.getText());
rs4.next();
t7.setText (""+rs4.getInt (1));
t8.setText (rs4.getString (2));
t9.setText (rs4.getString (3));
t10.setText (""+rs4.getInt (4));
t11.setText (rs4.getString (5));
t12.setText (rs4.getString (6));
t13.setText (rs4.getString (7));
t14.setText (""+rs4.getInt (8));
t15.setText ("Query Successful.");
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Query Failed.");
}
}
if (k.equals("Update"))
{
if (a2==1)
{
try
{
a1 = bs.insertDonorDetails (Integer.parseInt (t7.getText()),t8.getText(),t9.getText(),Integer.parseInt (t10.getText()),t11.getText(),t12.getText(),t13.getText(),Integer.parseInt (t14.getText()));
t15.setText ("Donor Inserted & Bloodbank Updated.");
rs11 = bs.searchDonorID (Integer.parseInt(t7.getText()));
rs11.next();
a12=rs11.getInt(8);
rs12=bs.searchBloodGroup (t12.getText());
rs12.next();
a13=rs12.getInt(3);
a14 = a12+a13;
rs13=bs.getBloodID (t12.getText());
rs13.next();
a15=rs13.getInt(1);
a16 = bs.updateBloodGroup (a15,a14);
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Insertion Failed.");
}
}
else
{
try
{
rs8 = bs.searchDonorID (Integer.parseInt(t7.getText()));
rs8.next();
a7=rs8.getInt(8);
a5 = bs.updateDonorDetails (Integer.parseInt(t7.getText()),Integer.parseInt(t14.getText()));
t15.setText ("Current Donor & Bloodbank Updated.");
rs9 = bs.searchDonorID (Integer.parseInt(t7.getText()));
rs9.next();
a8=rs9.getInt(8);
a9 = a8 - a7;
rs10 = bs.searchBloodGroup (t12.getText());
rs10.next();
a10=rs10.getInt(3);
a11=a10+a9;
rs5=bs.getBloodID (t12.getText());
rs5.next();
a3=rs5.getInt(1);
a4 = bs.updateBloodGroup (a3,a11);
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Updation Failed.");
}
}
a2=0;
}
if (k.equals("Generate Token"))
{
dateformat = new SimpleDateFormat ("E dd.MM.yyyy 'at' hh:mm:ss a zzz");
date = new Date( );
s1 = t7.getText();
s2 = t8.getText();
s3 = t9.getText();
s4 = t10.getText();
s5 = t11.getText();
s6 = t12.getText();
s7 = t13.getText();
s8 = t14.getText();
try
{
fw = new FileWriter ("E:\\Token - "+s2+".txt");
fw.write (dateformat.format(date));
fw.write ("\r\n");
fw.write ("\r\n");
fw.write ("----------------------------------------------");
fw.write ("\r\n");
fw.write ("Donor ID : ");
fw.write (s1);
fw.write ("\r\n");
fw.write ("Donor's Name : ");
fw.write (s2);
fw.write ("\r\n");
fw.write ("Gender : ");
fw.write (s3);
fw.write ("\r\n");
fw.write ("Age : ");
fw.write (s4);
fw.write ("\r\n");
fw.write ("Donor's Parent Name : ");
fw.write ("Mr." + s5);
fw.write ("\r\n");
fw.write ("Donor's Blood Group : ");
fw.write (s6);
fw.write ("\r\n");
fw.write ("Donor's Blood Pressure : ");
fw.write (s7);
fw.write ("\r\n");
fw.write ("Number of times donated blood : ");
fw.write (s8);
fw.write ("\r\n");
fw.write ("----------------------------------------------");
fw.write ("\r\n");
fw.write ("\r\n");
fw.write ("\r\n");
fw.write ("Authorized Signature -");
fw.write ("\r\n");
fw.write ("Stamp -");
fw.flush();
t15.setText ("Token Generated.");
}
catch (Exception e)
{
System.out.println (e);
t15.setText ("Token Generation Failed.");
}
}
if (k.equals("Clear"))
{
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
t5.setText("");
t6.setText("");
t7.setText("");
t8.setText("");
t9.setText("");
t10.setText("");
t11.setText("");
t12.setText("");
t13.setText("");
t14.setText("");
}
}
public void itemStateChanged (ItemEvent ie)
{
t9.setText (ch1.getSelectedItem());
t12.setText (ch2.getSelectedItem());
}
} |
CIA’s Brennan warns ISIL could use Turkish airport strike as template for attack in U.S.
Islamic State of Iraq and Levant (ISIL) is likely to attempt an attack like that on Istanbul’s Ataturk Airport in the United States, CIA Director John Brennan said.
“I’d be surprised if Daesh (ISIL) is not trying to carry out that kind of attack in the United States,” Brennan said on June 29.
Security officials have taken note of the ways in which ISIL terrorists successfully penetrated security in the airport strike.
“You look at what happened in the Turkish airport, these were suicide vests. It’s not that difficult to actually construct and fabricate a suicide vest … so if you have a determined enemy and individuals who are not concerned about escape, that they are going into it with a sense that they are going to die, that really does complicate your strategy in terms of preventing attacks,” he told Yahoo News.
Brennan said he believes the group will keep trying to penetrate American defenses and echoed somewhat pessimistic comments he made earlier this month before the Senate Intelligence Committee about the enduring strength of ISIL as a terrorist organization with global reach. |
This article mentions the topic of suicide. The suicide hotline can be reached, 24/7, every day at 1-800-273-8255.
Students lit up the darkened Shurmer Gym in honor of the loss of a fellow student Wednesday, in a student-organized candlelight vigil.
The vigil was organized by members of the campus group Just Unity Sistas, who felt it was inappropriate for students to have to try and study and go to lectures in Butte Hall for the remainder of the day.
Counselors were also made available at the vigil, and students can call the counseling center 24/7 at 530-898-6345.
President Hutchinson also briefly spoke at the vigil, urging troubled students to reach out to faculty or administration. |
New Delhi: The Supreme Court has said that the Adani Group-promoted Mundra Port and Special Economic Zone (SEZ) Ltd in Gujarat has to submit a fresh proposal to divert forest land and cannot use an earlier request by a group company.
Recently, the apex court had asked the state government to place a new application by Mundra Port and SEZ before the forest advisory committee (FAC), a body constituted under the Forest Conservation Act (FCA) to regulate diversion of forest land for non-forestry purposes.
Diverting land: Mundra Port, Gujarat. In June 1998, the forest advisory committee rejected the initial proposal by Adani Chemicals to divert 2,400ha of forest land as the area had 1.9 million mangroves.
Prior to that, the central empowered committee (CEC), meant to advise the Supreme Court on forestry-related issues, had rejected the proposal for diversion of more than 2,000ha of forest land for the Mundra Port and SEZ. The CEC report dated 16 July said: “The user agency (had) requested for forest land in an ecologically sensitive area for a site-specific activity, namely salt project." The request for diversion of forest land was first made in 1998 by Adani Chemicals Ltd for a salt project in Kutch, Gujarat. “Since the site-specific salt project has been given up... the request by the user agency (Adani Chemicals Ltd) for diversion of forest land as a part of the Mundra Port and special economic zone may be rejected."
“We shall consider the new proposal when it comes," said an official at the ministry of environment and forests (MoEF), who did not want to be identified.
“The proposal will be re-submitted to the concerned authority as desired," said the spokesperson for the Adani Group.
The diversion of forest land—originally 2,400ha—was proposed in 1998 by Adani Chemicals. On 26 June 1998, the FAC rejected the proposal as the area had 1.9 million mangroves; coastal norms of the time did not allow such projects.
Thereafter Adani Chemicals amended the proposal, reducing forest land from 2,400ha to 1,850ha by excluding land covered by mangroves. On 26 September 2002, the FAC recommended the diversion of 1,840ha of forest land for the salt project.
After that, the MoEF granted in-principle approval on 13 May 2004, along with another proposal of Adani Chemicals for diversion of 168.41ha of forest land for a salt-washing and desalination plant and a container depot.
Adani Chemicals then wrote to the MoEF in the same year stating that the salt project fell within the boundary of Mundra SEZ—which was renamed as Mundra Port and SEZ in 2007—and requested the ministry to make a mention in the approval letter that the diversion will apply to related land use permitted in the area.
The MoEF then permitted Adani Chemicals to include the diverted forest land in the SEZ, which the CEC report said “was taken without placing the matter before the FAC".
On 23 June 2004, the MoEF approved the change of name of the user agency from Mundra SEZ Ltd to Mundra Port and SEZ Ltd without placing the matter before the FAC, the CEC report added.
Three years later, in 2007, Mundra Port and SEZ Ltd, wrote to the MoEF to amend the earlier approval to change the land use as per the master plan and the name of user agency to Mundra Port and SEZ Ltd from Mundra SEZ Ltd. It also asked the MoEF to phase out the payment of net present value, or NPV.
NPV is the price of the forest land diverted for non-forestry purposes and has to be paid into a fund called Compensatory Afforestation Management and Planning Authority. The payment is mandatory except in certain cases of development such as schools and hospitals and for defence purposes.
On the new proposal, the FAC on 27 March said: “...the proposed changed land use completely changes the scope and purpose of the original diversion approvals accorded by the ministry, thereby rendering the entire EIA (environment impact assessment) and other special reports...meaningless."
However, after a representation dated 3 April to the MoEF by the Mundra Port and SEZ Ltd, the FAC reconsidered the matter once again though it had closed the matter earlier. This time around, the FAC approved the change of user agency without any new EIA studies.
The CEC also said no reason for the change of stand of the FAC has been recorded in the minutes of its March meeting.
Several other SEZs across the country are facing difficulties in acquiring land, mainly due to protests from land owners. GMR Group’s Kakinada SEZ, Andhra Pradesh Industrial Infrastructure’s SEZ in Visakhapatnam and Reliance Industries Ltd’s SEZ in Raigad, Maharashtra, have all run into trouble over protests from land owners.
“I think the demand for large tracts of fertile agriculture land, especially in peripheries of upcoming cities, has brought into conflict agriculturists, peasants and land owners—if you look at the struggles, they are mostly from such areas. It is not just a farmer issue, because many SEZs, especially a port-based one such as Mundra, are looking at coastal areas...fishing communities are also in the picture," said Manshi Asher, independent researcher on social and environmental issues. |
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <slhaea.h>
using namespace std;
using namespace SLHAea;
int main()
{
stringstream some_blocks(
"BLOCK test Q= 1000 \n"
" 1 3.14 \n"
" 2 6.28 \n"
"BLOCK test Q= 2000 \n"
" 1 2.71 \n"
" 2 5.42 \n"
"BLOCK test Q= 2000 \n"
" 1 1.61 \n"
" 2 3.22 \n");
Coll input(some_blocks);
Block b1, b2, b3;
// Find the first block:
vector<string> key;
key.push_back("Block");
key.push_back("TEST");
key.push_back("q=");
key.push_back("1000");
b1 = input.at(key);
cout << *b1.find_block_def() << endl;
cout << b1.at(1).at(1) << " == 3.14" << endl;
cout << b1.at(2).at(1) << " == 6.28" << endl;
// Find the second block:
key.at(3) = "2000";
b2 = input.at(key);
cout << *b2.find_block_def() << endl;
cout << b2.at(1).at(1) << " == 2.71" << endl;
cout << b2.at(2).at(1) << " == 5.42" << endl;
// Find the third block:
b3 = *Coll::find(input.rbegin(), input.rend(), key);
cout << *b3.find_block_def() << endl;
cout << b3.at(1).at(1) << " == 1.61" << endl;
cout << b3.at(2).at(1) << " == 3.22" << endl;
}
|
pub mod base_shape;
pub mod cone;
pub mod csg;
pub mod cube;
pub mod cylinder;
pub mod group;
pub mod plane;
pub mod shape;
pub mod smooth_triangle;
pub mod sphere;
mod test_shape;
pub mod triangle;
|
<reponame>turn/splicer
/* Generated By:JavaCC: Do not edit this line. SyntaxCheckerConstants.java */
package com.turn.splicer.tsdbutils.expression.parser;
/**
* Token literal values and constants.
* Generated by org.javacc.parser.OtherFilesGen#start()
*/
public interface SyntaxCheckerConstants {
/**
* End of File.
*/
int EOF = 0;
/**
* RegularExpression Id.
*/
int NAME = 5;
/**
* RegularExpression Id.
*/
int PARAM = 6;
/**
* Lexical state.
*/
int DEFAULT = 0;
/**
* Literal token values.
*/
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\n\"",
"\"\\r\"",
"<NAME>",
"\"&&\"",
"\"(\"",
"\",\"",
"\")\"",
"\":\"",
"\"{\"",
"\"=\"",
"\"}\"",
};
}
|
<gh_stars>1-10
from expressions5 import Query
import psycopg2, sys, getopt, time
import random
def sample(inputs, params):
inp = inputs[0]
fraction = params[0]
x = 0.0
for f in inp:
x += fraction
if x >= 1.0:
x -= 1.0
yield f
filters = dict(sample = sample)
connstr = sys.argv[1]
conn = psycopg2.connect(connstr)
queries = [
("minus",
"""
with namespace="test"
(dataset A - dataset B) where b == true
"""),
("mult", """
with namespace="test"
(
dataset test:A # comment
* dataset test:B
) where b = true and f < 100 and i < 30
"""),
("meta_filter, intersection", """
{
dataset test:A,
dataset test:B
}
where i > 10
"""),
("sample",
"""
filter sample(0.1) (dataset test:K where b == true)
"""
),
("meta int", """
dataset test:C where i < 10
"""),
("named", """
union (
query test:C_true,
dataset test:A
) where b=true
""")
]
queries = []
qtext = """
union(
dataset test:M where b = true and i < 10 and f < 100.0,
dataset test:M where b=false and i < 100 and f < 1000.0
)
"""
exp = Query(qtext, default_namespace = "t")
t0 = time.time()
exp.parse()
dt_parse = time.time() - t0
print("-- parsed --")
print(exp.parse().pretty())
exp.assemble(conn)
print("-- optimized --")
print(exp.optimize().pretty())
t1 = time.time()
out = list(exp.run(conn, filters))
dt_run = time.time() - t1
#print (qn,f"parse: {dt_parse:.3}, run:{dt_run:.3}","\n -> ",sorted([f.Name for f in out]))
for f in out:
print(f)
for qn, qtext in queries:
print("Query '%s': %s" % (qn, qtext))
exp = Query(qtext, default_namespace = "t")
t0 = time.time()
exp.parse()
dt_parse = time.time() - t0
print("-- parsed --")
print(exp.parse().pretty())
exp.assemble(conn)
print("-- optimized --")
print(exp.optimize().pretty())
t1 = time.time()
out = list(exp.run(conn, filters))
dt_run = time.time() - t1
print (qn,f"parse: {dt_parse:.3}, run:{dt_run:.3}","\n -> ",sorted([f.Name for f in out]))
|
// Fill a gradient on a LED ring with any possible start positions.
// startLed and endLed may be negative (one or both), may be larger than _meshNumLeds (one or both)
// TODO:
// * remove floating point calculation; replace by linear interpolation?
void FX::fillGradientRing( int startLed, CHSV startColor, int endLed, CHSV endColor ) {
int actualStart = mod(startLed + _meshNumLeds, _meshNumLeds) ;
int actualEnd = mod(endLed + _meshNumLeds, _meshNumLeds) ;
if ( actualStart > actualEnd ) {
float ratio = 1.0 - float(actualEnd) / float(endLed - startLed) ;
int normalizedRatio = round( ratio * 255 ) ;
CHSV colorAtLEDZero = blend(startColor, endColor, normalizedRatio);
fill_gradient(_leds, actualStart, startColor, _meshNumLeds - 1, colorAtLEDZero, SHORTEST_HUES);
fill_gradient(_leds, 0, colorAtLEDZero, actualEnd, endColor, SHORTEST_HUES);
} else {
fill_gradient(_leds, actualStart, startColor, actualEnd, endColor, SHORTEST_HUES);
}
} |
Qualcomm made an appearance at CES this week to unveil the next step past their successful Snapdragon S4 chipset, which was found in, among other things, the bulk of HTC’s and Nokia’s smartphone line-up from last year. The S4 was the main competitor to the highly touted quad-core NVIDIA Tegra 3 processor in the mobile world last year, and proved to be more than up to the task, despite, in its most commonly seen forms, being a dual-core processor.
This year, we’ll be seeing a numbering change to Qualcomm’s chipsets, headlined by the brand new Snapdragon 600 and 800 sets. Since these are chipsets, CPU, GPU, and memory are all included in what Qualcomm is offering. For the 800, that means a quad-core Krait 400 CPU (up to 2.3 GHz), a brand new Adreno 330 GPU, and 2×32 bit 800 MHz of LPDDR3 RAM. That last bit is a big part of what the new chipset is offering – the LP in LPDDR3 stands for low-power. That means the chipsets should be able to work harder using less power, which should (hopefully) translate into improved battery life for devices using the 800. Also in the top-of-the-line Snapdragon 800 set is support for 4G LTE connectivity, HD audio, and UltraHD. UltraHD is a new standard for resolution currently only applicable to televisions – specifically, those with resolutions of 3,840 x 2,160. That means that, in addition to seeing the 800 in highest-end smartphones and tablets, you’ll also be seeing it in a lot of new UltraHD smart TVs that will be coming to market next year and beyond. That support for UltraHD will be for both playback and capture, and it seems that 3D video capture will also be supported.
The Snapdragon 600 will also find its way into high end smartphones, especially those coming out in the first half of this year. The 600 still packs in quad-core power, though with a Krait 300 CPU, a slight step down from what will be in the 800 chipset. It’ll also have an Adreno 320 GPU (another slight step down) and, like the 800, will boast energy-saving LPDDR3 RAM. Qualcomm claims that the 600 features 40 percent improved performance over the S4, compared to a 75 percent increase seen in the 800 set. What that actually means, I’m guessing only Qualcomm knows, but I’m willing to take them at their word that these are going to be some seriously high-powered chipsets.
There will also be the lower-end Snapdragon 400 and 200 chipsets, which will come to market in mid to low-end devices sometime this year. Qualcomm is currently sampling the 600 and 800 chipsets. They expect the 600 to start coming with devices released in Q2 this year, while the 800 is pegged for devices released in the latter half of this year and beyond.
With Steve Ballmer, Maroon 5, and Big Bird all appearring on stage, Qualcomm’s press conference at CES was perhaps the most talked about at CES this year. So in case you missed it – you can check out the rebroadcast here. |
<reponame>prabal77/CoherenceScheduler<filename>samples/Test-clients/SchedulerServer/src/main/java/org/prabal/scheduler/internals/processors/UpdateTriggerAfterFireProcessor.java
/**
*
*/
package org.prabal.scheduler.internals.processors;
import org.prabal.scheduler.core.BaseCoherenceCalendar;
import org.prabal.scheduler.core.ExecutionStatus;
import org.prabal.scheduler.core.Trigger;
import org.prabal.scheduler.internals.SchedulerContantsEnum;
import com.tangosol.io.pof.annotation.Portable;
import com.tangosol.net.BackingMapContext;
import com.tangosol.util.BinaryEntry;
import com.tangosol.util.InvocableMap;
import com.tangosol.util.InvocableMap.Entry;
import com.tangosol.util.processor.AbstractProcessor;
/**
* @author <NAME>
*
*/
@Portable
public class UpdateTriggerAfterFireProcessor extends AbstractProcessor {
@Override
public Object process(Entry entry) {
Trigger triggerInstance = (Trigger) entry.getValue();
ExecutionStatus executionStatus = ExecutionStatus.NORMAL;
BaseCoherenceCalendar calendar = null;
if (triggerInstance.getCalendarName() != null) {
BackingMapContext backingMapContext = ((BinaryEntry) entry).getContext().getBackingMapContext(SchedulerContantsEnum.JOB_STORE_CACHE.getConstantValue());
InvocableMap.Entry calendarEntry = backingMapContext.getBackingMapEntry(triggerInstance.getCalendarName());
if (calendarEntry.isPresent())
calendar = (BaseCoherenceCalendar) calendarEntry.getValue();
}
triggerInstance.triggered(calendar);
if (triggerInstance.getNextFireTime() == null) {
executionStatus = ExecutionStatus.COMPLETE;
}
triggerInstance.changeTriggerState(executionStatus);
entry.setValue(triggerInstance);
return null;
}
}
|
<reponame>lvzon/libsodium-python
#!/usr/bin/python3
import sys
import libsodium
def write_bytes(fname, data):
with open(fname, 'wb') as outfile:
outfile.write(data)
def read_bytes(fname):
with open(fname, 'rb') as infile:
data = infile.read()
return data
# Get input/output files from commandline
if len(sys.argv) < 3 or sys.argv[1] in ('-h', '--help'):
print("Usage:", sys.argv[0], "<ed25519 sender pubkey> <input message file> [<input signature file>]\n")
exit()
# Load Ed25519 keyfile
sender_pubkey_ed25519 = read_bytes(sys.argv[1])
# Read message to be verified
message = read_bytes(sys.argv[2])
# Read signature to be verified
if len(sys.argv) >= 4:
signature = read_bytes(sys.argv[3])
else:
signature = sys.stdin.buffer.read()
# Verify signature
try:
libsodium.crypto_sign_verify_detached(signature, message, sender_pubkey_ed25519)
except:
print("Signature does not match message\n", file=sys.stderr)
exit(1)
print("Signature matches message\n", file=sys.stderr)
|
Q:
Is it wrong to recommend a more appropriate Stack Exchange site?
I was wondering if it is poor practice to redirect a new user to a more appropriate Stack Exchange site when they ask a question that is not suitable for the site they asked the question?
If it is ok, then why have I never seen anyone do this? Instead, many questions get shut down (often accompanied with a sarcastic or nasty comment), when they should have just been redirected to another Stack Exchange site.
There are obvious benefit for doing this including:-
The new user still uses Stack Exchange to get their question answered.
The new user is educated about the different sites and appropriate questions for each site.
Stack Exchange will grow and retain members.
The first experience of Stack Exchange becomes a positive one instead of a negative one.
A:
Directing to another site is just fine. But you might want to hold off on making that a comment, if the question is not closed.
You'd risk the user asking a cross-site duplicate, which is usually not appreciated. A better way to approach this would be to flag for moderator attention, recommending migration if possible. Or to simply vote for migration if such a path is available. Or, of course, you could recommend the user to migrate instead of duplicating.
As for sarcastic or nasty comments: flag.
A:
if it is poor practice to redirect a new user to a more appropriate Stack Exchange site
No, it is not a poor practice. It is appropriate to point the new user towards the relevant site provided that the question is on-topic for that site. It would be better to provide more information to the new user that cross-posting is highly discouraged. The user should migrate the question (or delete) before posting on the other site.
why have I never seen anyone do this?
Maybe you missed some of these, here is a recent example (which was later migrated to the appropriate site):
https://stackoverflow.com/questions/19671649/how-to-simplify-my-jquery-codes?noredirect=1
On this quesiton, one of the user commented:
This question appears to be off-topic - It belongs on codereview.stackexchange.com
A:
A few random thoughts on migration comments:
Do not just tell the OP their question is off topic. If you don't have the time or energy to explain why it's on topic, please do not post a comment at all. Someone else will, soon enough.
If you are going to suggest migration, please also:
Let the OP know they can flag the question and ask the moderators to move it, or
If the question was closed without answers, encourage them to delete it before posting it elsewhere
If you are not 100% certain that the question is indeed on topic elsewhere and that it fits that site's quality expectations, do not comment. Instead, flag the question yourself and ask for it to be moved.
Even if you are 100% certain, you should still let the OP know that they should familiarize themselves with the other site before posting there.
Migration comments, although almost always well meaning, quite often create a very disappointing experience for newer users:
This is off topic on Foo.SE, it belongs on Bar.SE.
OP re-posts on Bar.SE.
Question is quickly closed on Bar.SE.
And we are left with a newer user who now thinks we are a bunch of circlejerks, playing migration ping pong with their question, and two closed questions1. That's not nice.
Recommending a more appropriate Stack Exchange site is definitely not wrong. It is, however, very hard to get right. If you have even the slightest doubts about the question's suitability on the target site, you should probably avoid commenting.
1 And if Foo.SE and Bar.SE happen to have automatic question bans enabled, the OP is now a step closer to getting question banned on two sites. This might seem like a narrow edge case, but it happens at least once per day (on average) between SO and Programmers. |
/*
Package cli contains utilities for "Command Line Interface" applications.
*/
package cli
|
import {
ButtonHTMLAttributes,
createElement as r,
FunctionComponent,
MouseEvent,
ReactNode,
} from 'react'
import {
CollapsibleContext,
CollapsibleContextValue,
} from './collapsible-context'
type RenderCallback = (expanded: boolean) => ReactNode
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children?: RenderCallback
render?: RenderCallback
}
const Button: FunctionComponent<ButtonProps> = function Button({
children,
onClick,
onKeyDown,
render,
...props
}) {
return r(
CollapsibleContext.Consumer as any,
null,
({ expanded, toggle }: CollapsibleContextValue) =>
r(
'button',
{
'aria-expanded': expanded,
onClick: onClick
? (event: MouseEvent<HTMLButtonElement>) => {
onClick(event)
toggle()
}
: toggle,
type: 'button',
...props,
},
render
? render(expanded)
: typeof children === 'function'
? children(expanded)
: children,
),
)
}
export { Button }
|
EXPERIMENTAL CALIBRATION OF RANDOMNESS IN ADDITIVELY MANUFACTURED CONTINUOUSLY REINFORCED COMPOSITES This paper presents an experimental analysis of the uncertainty in physical and mechanical properties of fused filament fabrication (FFF) parts that are reinforced with continuous carbon fibers (CCF). The goal of this work is to quantify modulus uncertainty in composites specimens printed on a commercially available continuous carbon filament 3D printer. The specimens that are analyzed in this paper are fabricated of a nylon-based material as the thermoplastic matrix and CCF as the reinforcing material. The test specimens are designed with four unique set of stacking sequences, which are categorized as SS #1, a combination of symmetric 0°and 90°layers, SS #2, a combination of symmetric ±45°layers, SS #3, a combination of symmetric 0°, ±45 °, and 90°and SS #4, a combination of non-symmetric ±45°layers. In each category, a total of 15 specimens are manufactured through FFF. A load-unload tensile test is performed for each specimen using an extensometer and digital image correlation (DIC) for strain analysis. Elastic Modulus (Exx) values of the specimens are determined and compared within each specimen to analyze the uncertainty. Also, strain variability is analyzed among the specimens using the DIC results. |
//
// HHShopCarTableViewCell.h
// haho
//
// Created by ANDY on 16/4/21.
// Copyright © 2016年 vangehome. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HHShopCarTableViewCell : UITableViewCell
@end
|
// LangIdBasicNew: create structure tha hold a Basic version of RFC 5646 (BCP 47)
func LangIdBasicNew(filename string) *LangIdBasic {
var err error
lids := new(LangIdBasic)
lids.Filename = filename
if len(langIdStr) > 0 {
lids.LangId = make([]langId, len(langIdStr))
for idx, lId := range langIdStr {
lids.LangId[idx], err = lids.makeEntry(lId[0], lId[1], lId[2])
if err != nil {
log.Println(err.Error())
}
}
tmpVal, err := lids.makeEntry("0x0000", "_UNKNOWN_", "Unknown")
if err != nil {
log.Println(err.Error())
}
lids.LangId = append(lids.LangId, tmpVal)
}
return lids
} |
Treatment of cervical sensitivity with a root sealant. PURPOSE To assess a novel root sealant for cervical sensitivity. MATERIALS AND METHODS Clinical assessments, impressions and modified USPHS criteria (n = 24) were carried out at baseline, 3, 6 and 19 months. Plaque samplings were performed at baseline and after 3 and 19 months. RESULTS At 19 months, 20 patients completed the clinical trial. There was a significant reduction for the sensitivity scores. The log10 of total colony-forming units (cfu + 1) from overlying plaque significantly reduced. The percentage of mutans streptococci reduced after 3 months (P < 0.01) and yeasts also reduced after 19 months (P < 0.01). The mean overall wear (+/- SD) (microm) on the sealant was 78.8 +/- 21.3 at 3 months; 95.4 +/- 7.3 after 6 months and 136.5 +/- 9.8 after 19 months. In conclusion, this sealant was capable of reducing sensitivity. Further wear on the cervical surface was prevented as the mean sealant thickness was 65.3 +/- 3.3 after 19 months. |
<reponame>ringcentral/ringcentral-js-widgets<filename>packages/ringcentral-widgets/modules/CallControlUI/CallControlUI.ts<gh_stars>10-100
import { RcUIModuleV2 } from '@ringcentral-integration/core';
import { ObjectMapValue } from '@ringcentral-integration/core/lib/ObjectMap';
import { filter, find, values } from 'ramda';
import { Module } from '@ringcentral-integration/commons/lib/di';
import {
ConferenceCall,
LastCallInfo,
} from '@ringcentral-integration/commons/modules/ConferenceCallV2';
import { Webphone } from '@ringcentral-integration/commons/modules/WebphoneV2';
import callDirections from '@ringcentral-integration/commons/enums/callDirections';
import { NormalizedSession } from '@ringcentral-integration/commons/interfaces/Webphone.interface';
import { formatNumber } from '@ringcentral-integration/commons/lib/formatNumber';
import callingModes from '@ringcentral-integration/commons/modules/CallingSettings/callingModes';
import { sessionStatus } from '@ringcentral-integration/commons/modules/Webphone/sessionStatus';
import callCtrlLayouts from '../../enums/callCtrlLayouts';
import { checkShouldHidePhoneNumber } from '../../lib/checkShouldHidePhoneNumber';
import {
CallControlComponentProps,
Deps,
getLastCallInfoFromWebphoneSession,
} from './CallControlUI.interface';
@Module({
name: 'CallControlUI',
deps: [
'Webphone',
'Locale',
'ContactMatcher',
'RegionSettings',
'Brand',
'ContactSearch',
'CallingSettings',
'ConnectivityManager',
'ForwardingNumber',
'CallMonitor',
'ExtensionInfo',
'AppFeatures',
{ dep: 'ConferenceCall', optional: true },
{ dep: 'RouterInteraction', optional: true },
],
})
export class CallControlUI extends RcUIModuleV2<Deps> {
constructor(deps: Deps) {
super({
deps,
});
}
getUIProps({
params,
showCallQueueName = false,
showPark = false,
children,
}: CallControlComponentProps) {
const {
brand,
callingSettings,
conferenceCall,
connectivityManager,
contactMatcher,
contactSearch,
forwardingNumber,
regionSettings,
locale,
webphone,
} = this._deps;
const sessionId = params?.sessionId;
const currentSession =
(sessionId
? find((session) => session.id === sessionId, webphone.sessions)
: webphone.activeSession) || ({} as NormalizedSession);
const contactMapping = contactMatcher?.dataMapping;
const fromMatches = contactMapping?.[currentSession.from] ?? [];
const toMatches = contactMapping?.[currentSession.to] ?? [];
const nameMatches =
currentSession.direction === callDirections.outbound
? toMatches
: fromMatches;
const isWebRTC = callingSettings.callingMode === callingModes.webphone;
const isInboundCall = currentSession.direction === callDirections.inbound;
let lastCallInfo = conferenceCall?.lastCallInfo;
const conferenceCallEquipped = conferenceCall?.hasPermission ?? false;
const conferenceData = conferenceCallEquipped
? values(conferenceCall.conferences)[0]
: undefined;
const isOnConference = conferenceCallEquipped
? conferenceCall.isConferenceSession(currentSession.id)
: false;
const isMerging = conferenceCallEquipped && conferenceCall.isMerging;
const conferenceCallId =
conferenceData && isWebRTC ? conferenceData.conference.id : null;
const isConferenceCallOverload =
conferenceData && isWebRTC
? conferenceCall.isOverload(conferenceCallId)
: false;
const hasConferenceCall = !!conferenceData;
const conferenceCallParties = conferenceCallEquipped
? conferenceCall.partyProfiles
: undefined;
// TODO: investigate whether this can simply use isMerging
const fromSessionId = conferenceCallEquipped
? conferenceCall.mergingPair?.fromSessionId
: undefined;
const hideChildren =
conferenceCallEquipped &&
!isInboundCall &&
fromSessionId &&
fromSessionId !== currentSession.id;
lastCallInfo && lastCallInfo.status !== sessionStatus.finished;
if (currentSession.warmTransferSessionId) {
const warmTransferSession = webphone.sessions.find(
(session) => session.id === currentSession.warmTransferSessionId,
);
lastCallInfo = getLastCallInfoFromWebphoneSession(warmTransferSession);
}
const disableLinks = !!(
connectivityManager.isOfflineMode || connectivityManager.isVoipOnlyMode
);
let phoneNumber =
currentSession.direction === callDirections.outbound
? currentSession.to
: currentSession.from;
if (
this._deps.appFeatures.isCDCEnabled &&
checkShouldHidePhoneNumber(phoneNumber, nameMatches)
) {
phoneNumber = null;
}
return {
brand: brand.fullName,
nameMatches,
phoneNumber,
currentLocale: locale.currentLocale,
session: currentSession,
areaCode: regionSettings.areaCode,
countryCode: regionSettings.countryCode,
showBackButton: true, // callMonitor.calls.length > 0,
searchContactList: contactSearch.sortedResult,
showSpinner: isMerging,
conferenceCallEquipped,
hasConferenceCall,
conferenceCallParties,
conferenceCallId,
lastCallInfo,
// TODO: investigate whether it's better to just
// use isMerging and let the component decide whether to display children
children: hideChildren ? null : children,
isOnConference,
isWebRTC,
disableLinks,
isConferenceCallOverload,
disableFlip: forwardingNumber.flipNumbers.length === 0,
showCallQueueName,
showPark,
};
}
getInitialLayout = ({
conferenceCallEquipped,
isOnConference,
lastCallInfo,
session,
}: {
conferenceCallEquipped: boolean;
isOnConference: boolean;
lastCallInfo?: LastCallInfo;
session?: NormalizedSession;
}) => {
const { conferenceCall, webphone } = this._deps;
let layout = callCtrlLayouts.normalCtrl;
if (session.warmTransferSessionId) {
return callCtrlLayouts.completeTransferCtrl;
}
if (!conferenceCallEquipped) {
return layout;
}
if (isOnConference) {
return callCtrlLayouts.conferenceCtrl;
}
const isInboundCall = session.direction === callDirections.inbound;
const { fromSessionId } = conferenceCall.mergingPair;
const fromSession = find(
(x: any) => x.id === fromSessionId,
webphone.sessions,
);
const activeSessionId =
webphone && webphone.activeSession && webphone.activeSession.id;
if (
!isOnConference &&
!isInboundCall &&
fromSession &&
fromSessionId !== session.id &&
lastCallInfo &&
(session.callStatus !== sessionStatus.onHold ||
(session.callStatus === sessionStatus.onHold &&
session.id === activeSessionId))
) {
// enter merge ctrl page.
layout = callCtrlLayouts.mergeCtrl;
}
return layout;
};
getUIFunctions({
getAvatarUrl,
onBackButtonClick,
phoneTypeRenderer,
phoneSourceNameRenderer,
}: CallControlComponentProps) {
const {
conferenceCall,
webphone,
regionSettings,
extensionInfo,
callingSettings,
callMonitor,
routerInteraction,
contactSearch,
} = this._deps;
return {
getInitialLayout: this.getInitialLayout,
formatPhone: (phoneNumber: string) =>
formatNumber({
phoneNumber,
areaCode: regionSettings.areaCode,
countryCode: regionSettings.countryCode,
siteCode: extensionInfo?.site?.code ?? '',
isMultipleSiteEnabled: extensionInfo.isMultipleSiteEnabled,
}),
onHangup: (
sessionId: string,
layout: ObjectMapValue<typeof callCtrlLayouts>,
) => {
webphone.hangup(sessionId);
if (layout && layout === callCtrlLayouts.mergeCtrl) {
callMonitor.mergeControlClickHangupTrack();
}
},
onMute: (sessionId: string) => webphone.mute(sessionId),
onUnmute: (sessionId: string) => webphone.unmute(sessionId),
onHold: (sessionId: string) => webphone.hold(sessionId),
onUnhold: (sessionId: string) => {
webphone.unhold(sessionId);
},
onRecord: (sessionId: string) => webphone.startRecord(sessionId),
onStopRecord: (sessionId: string) => webphone.stopRecord(sessionId),
sendDTMF: (...args: Parameters<Webphone['sendDTMF']>) =>
webphone.sendDTMF(...args),
updateSessionMatchedContact: (
...args: Parameters<Webphone['updateSessionMatchedContact']>
) => webphone.updateSessionMatchedContact(...args),
getAvatarUrl,
onBackButtonClick,
onFlip: (sessionId: string) => {
routerInteraction.push(`/flip/${sessionId}`);
},
onTransfer: (sessionId: string) => {
routerInteraction.push(`/transfer/${sessionId}/webphone`);
},
onCompleteTransfer: (sessionId: string) => {
webphone.completeWarmTransfer(sessionId);
},
onPark: (sessionId: string) => webphone.park(sessionId),
searchContact: (searchString: string) =>
contactSearch.debouncedSearch({ searchString }),
phoneTypeRenderer,
phoneSourceNameRenderer,
onAdd: (sessionId: string) => {
// track user click add on call control
callMonitor.callControlClickAddTrack();
const session = find((x: any) => x.id === sessionId, webphone.sessions);
if (!session || !conferenceCall.validateCallRecording(session)) {
return;
}
let fromNumber = callingSettings.fromNumber;
if (session.direction === callDirections.outbound) {
fromNumber = session.fromNumber; // keep the same fromNumber
}
const otherCalls = filter(
(call: any) =>
call.webphoneSession && call.webphoneSession.id !== session.id,
callMonitor.allCalls,
);
if (otherCalls.length) {
// goto 'calls on hold' page
routerInteraction.push(
`/conferenceCall/callsOnhold/${fromNumber}/${session.id}`,
);
} else {
if (conferenceCall) {
conferenceCall.setMergeParty({ fromSessionId: sessionId });
}
// goto dialer directly
routerInteraction.push(
`/conferenceCall/dialer/${fromNumber}/${sessionId}`,
);
}
},
onBeforeMerge: (sessionId: string) => {
const session = find((x: any) => x.id === sessionId, webphone.sessions);
if (!session || !conferenceCall.validateCallRecording(session)) {
return false;
}
if (conferenceCall) {
const conferenceData = Object.values(conferenceCall.conferences)[0];
if (conferenceData) {
const conferenceSession = find(
(x: any) => x.id === conferenceData.sessionId,
webphone.sessions,
);
if (
conferenceSession &&
!conferenceCall.validateCallRecording(conferenceSession)
) {
return false;
}
}
}
return true;
},
onMerge: async (sessionId: string) => {
const sessions = await conferenceCall.parseMergingSessions({
sessionId,
});
if (sessions) {
await conferenceCall.mergeSessions(sessions);
}
},
gotoParticipantsCtrl: () => {
routerInteraction.push('/conferenceCall/participants');
// track user click participant area on call control
callMonitor.callControlClickParticipantAreaTrack();
},
loadConference: (conferenceId: string) => {
if (conferenceCall) {
conferenceCall.loadConference(conferenceId);
}
},
closeMergingPair: () => {
return conferenceCall && conferenceCall.closeMergingPair();
},
setMergeParty: (...args: Parameters<ConferenceCall['setMergeParty']>) => {
return conferenceCall && conferenceCall.setMergeParty(...args);
},
// user action track functions
afterHideMergeConfirm: () => callMonitor.confirmMergeClickCloseTrack(),
afterConfirmMerge: () => callMonitor.confirmMergeClickMergeTrack(),
afterOnMerge: () => callMonitor.callControlClickMergeTrack(),
};
}
}
|
A group based genetic algorithm data replica placement strategy for scientific workflow When running data intensive scientific workflow in multiple data centers environment, it is inevitable that massive data movement will be caused. The emergence of cloud computing technologies offers a new way to develop scientific workflow systems, and using dataset replicas to reduce data transfer among data centers is an import issue. In this paper, we propose a group based genetic algorithm which can make full use of dataset replicas to reduce data transmission in cloud. We compare the performance of our proposed algorithm with that of random algorithm and K-means algorithm. The results show that our proposed algorithm can effectively reduce data movements among data centers and improve the performance of data intensive scientific workflow. |
The present invention relates to a fixing apparatus for an electrostatic copying machine.
In a known electrophotographic process a photoconductive copy sheet is electrostatically charged and radiated with a light image to locally dissipate the charge to form an electrostatic image on the sheet. The sheet is then developed by applying a dry toner substance thereto which adheres to the high charge areas of the electrostatic image to form a toner image. The sheet is then pressingly fed between two fixing rollers which crush the toner into the copy sheet to fix the toner image to the copy sheet.
These fixing rollers are amounted on shafts for rotation, and a biasing force is applied to the ends of the shafts by springs or the like to urge the rollers together. A problem is encountered in such apparatus in that since the force is applied to the ends of the shafts, the shafts and rollers tend to bow or deflect outwardly in such a manner that the pressing force between the rollers is greatest at the ends and least in the center. This causes uneven fixing of the toner to the sheet. In extreme cases the toner will not be sufficiently pressed into the sheet in the center and will come off the sheet onto the hands of persons handling the sheet, objects which the sheets touches, etc.
Two expedients have been introduced in an attempt to overcome this problem. Increasing the diameter of the rollers also increases their rigidity so that the deflection is reduced. However, increasing the diameter of the rollers also increases the size and cost of the copying apparatus to an impractical degree. A second expedient is to orient the axes of the shafts and thereby the rollers so that they form a small actute angle therebetween. Compressive deformation of the rollers due to the pressing force causes a contact portion with the copy sheet in which the pressure distribution is more uniform than with the shafts and rollers aligned parallel to each other. However, a problem exists in this configuration in that the sheets tend to be wrinkled during passage between the fixing rollers unless the angle is so small as to be ineffective. This not only leads to tearing of the sheets in the wrinkled areas but also damages to the rollers due to high stress concentrations caused by the wrinkles. |
//Copyright © 2015 <NAME> All Rights Reserved
import de.hamster.debugger.model.Territorium;import de.hamster.debugger.model.Territory;import de.hamster.model.HamsterException;import de.hamster.model.HamsterInitialisierungsException;import de.hamster.model.HamsterNichtInitialisiertException;import de.hamster.model.KachelLeerException;import de.hamster.model.MauerDaException;import de.hamster.model.MaulLeerException;import de.hamster.model.MouthEmptyException;import de.hamster.model.WallInFrontException;import de.hamster.model.TileEmptyException;public class Level6 extends de.hamster.debugger.model.IHamster implements de.hamster.model.HamsterProgram {public void main() {
int schritte = 0;
do{
setzteKorn(schritte % 2);
vor();
schritte++;
}while(vornFrei());
}
void setzteKorn(int anzahl){
int i = 0;
while(kornDa()){
nimm();
}
while(anzahl > i){
gib();
i++;
}
}
} |
<filename>component/src/main/java/com/synopsys/integration/alert/component/certificates/AlertTrustStoreManager.java
/*
* component
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.alert.component.certificates;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.synopsys.integration.alert.api.common.model.exception.AlertConfigurationException;
import com.synopsys.integration.alert.api.common.model.exception.AlertException;
import com.synopsys.integration.alert.common.AlertProperties;
import com.synopsys.integration.alert.common.persistence.model.CustomCertificateModel;
@Component
public class AlertTrustStoreManager {
private final Logger logger = LoggerFactory.getLogger(AlertTrustStoreManager.class);
private final AlertProperties alertProperties;
@Autowired
public AlertTrustStoreManager(AlertProperties alertProperties) {
this.alertProperties = alertProperties;
}
public synchronized void importCertificate(CustomCertificateModel customCertificate) throws AlertException {
logger.debug("Importing certificate into trust store.");
validateCustomCertificateHasValues(customCertificate);
File trustStoreFile = getAndValidateTrustStoreFile();
KeyStore trustStore = getAsKeyStore(trustStoreFile, getTrustStorePassword(), getTrustStoreType());
try {
Certificate cert = getAsJavaCertificate(customCertificate);
trustStore.setCertificateEntry(customCertificate.getAlias(), cert);
try (OutputStream stream = new BufferedOutputStream(new FileOutputStream(trustStoreFile))) {
trustStore.store(stream, getTrustStorePassword());
}
} catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
throw new AlertException("There was a problem storing the certificate.", e);
}
}
public synchronized void removeCertificate(CustomCertificateModel customCertificate) throws AlertException {
logger.debug("Removing certificate from trust store.");
if (null == customCertificate) {
throw new AlertException("The alias could not be determined from the custom certificate because it was null.");
}
removeCertificate(customCertificate.getAlias());
}
public synchronized void removeCertificate(String certificateAlias) throws AlertException {
logger.debug("Removing certificate by alias from trust store.");
if (StringUtils.isBlank(certificateAlias)) {
throw new AlertException("The alias cannot be blank");
}
try {
File trustStore = getAndValidateTrustStoreFile();
KeyStore keyStore = getAsKeyStore(trustStore, getTrustStorePassword(), getTrustStoreType());
if (keyStore.containsAlias(certificateAlias)) {
keyStore.deleteEntry(certificateAlias);
try (OutputStream stream = new BufferedOutputStream(new FileOutputStream(trustStore))) {
keyStore.store(stream, getTrustStorePassword());
}
}
} catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
throw new AlertException("There was a problem removing the certificate.", e);
}
}
public synchronized KeyStore getAsKeyStore(File keyStore, char[] keyStorePass, String keyStoreType) throws AlertException {
logger.debug("Get key store.");
KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(keyStorePass);
try {
return KeyStore.Builder.newInstance(keyStoreType, null, keyStore, protection).getKeyStore();
} catch (KeyStoreException e) {
throw new AlertException("There was a problem accessing the trust store.", e);
}
}
public synchronized File getAndValidateTrustStoreFile() throws AlertConfigurationException {
logger.debug("Get and validate trust store.");
Optional<String> optionalTrustStoreFileName = alertProperties.getTrustStoreFile();
if (optionalTrustStoreFileName.isPresent()) {
String trustStoreFileName = optionalTrustStoreFileName.get();
File trustStoreFile;
try {
URI trustStoreUri = new URI(trustStoreFileName);
trustStoreFile = new File(trustStoreUri);
} catch (IllegalArgumentException | URISyntaxException ex) {
logger.debug("Error getting Java trust store from file URI", ex);
trustStoreFile = new File(trustStoreFileName);
}
if (!trustStoreFile.isFile()) {
throw new AlertConfigurationException("The trust store provided is not a file: " + trustStoreFileName);
}
if (!trustStoreFile.canWrite()) {
throw new AlertConfigurationException("The trust store provided cannot be written by Alert: " + trustStoreFileName);
}
return trustStoreFile;
} else {
throw new AlertConfigurationException("No trust store file has been provided.");
}
}
public synchronized void validateCertificateContent(CustomCertificateModel customCertificateModel) throws AlertException {
getAsJavaCertificate(customCertificateModel);
}
private void validateCustomCertificateHasValues(CustomCertificateModel customCertificate) throws AlertException {
if (null == customCertificate) {
throw new AlertException("The custom certificate cannot be null.");
}
if (StringUtils.isBlank(customCertificate.getAlias())) {
throw new AlertException("The alias cannot be blank.");
}
if (StringUtils.isBlank(customCertificate.getCertificateContent())) {
throw new AlertException("The certificate content cannot be blank.");
}
}
private Certificate getAsJavaCertificate(CustomCertificateModel customCertificate) throws AlertException {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
String certificateContent = customCertificate.getCertificateContent();
try (ByteArrayInputStream certInputStream = new ByteArrayInputStream(certificateContent.getBytes())) {
return certFactory.generateCertificate(certInputStream);
}
} catch (CertificateException | IOException e) {
throw new AlertException("The custom certificate could not be read.", e);
}
}
private String getTrustStoreType() {
return alertProperties.getTrustStoreType().orElse(KeyStore.getDefaultType());
}
private char[] getTrustStorePassword() {
return alertProperties
.getTrustStorePass()
.map(String::toCharArray)
.orElse(null);
}
}
|
Legal information retrieval and application to e-rulemaking The complexity and diversity of government regulations make understanding the regulations a non-trivial task. One of the issues is the existence of multiple sources of regulations and interpretive guides; the latter are often independent of governing bodies. This work aims to develop an information infrastructure for legal information retrieval with applications to electronic-rulemaking. The pilot study focuses on accessibility regulations from the US Federal government, private organizations and European agencies. A shallow parser is developed to consolidate different regulations into a unified XML format, which is well suited for handling semi-structured data such as legal documents. Handcrafted rules and a text mining tool are developed to extract the important features, such as concepts, measurements, effective dates and so on, and to incorporate them into the corpus.To compare and locate related provisions from different regulatory documents, we employ Information Retrieval techniques to combine generic features with domain knowledge. Structural information from regulations, such as the hierarchical organization of provisions and heavy referencing among provisions, are used to help improve the relatedness analysis. Results are obtained to illustrate the use of regulatory structure and domain knowledge in provision comparisons. Application to an e-rulemaking scenario for a rights-of-way drafted regulation is shown to demonstrate extended capabilities of the prototype system. |
/**
* @Author fengjie
* @Description
* @Date Created in 2018/6/2
* @Time 17:12
*/
public class TwoQueueStack {
Queue<Integer> data;
Queue<Integer> help;
public TwoQueueStack(){
data = new LinkedList<>();
help = new LinkedList<>();
}
public void push(int value){
data.add(value);
}
public int pop(){
int size = data.size();
for(int i = 0;i < size-1;i++){
help.add(data.poll());
}
int val = data.poll();
swap();
return val;
}
private void swap() {
Queue<Integer> tmp = help;
help = data;
data = tmp;
}
} |
A task-parallel programming language for interactive applications Task-parallel Programming is a methodology in which algorithms are specified as a set of tasks to be executed, and the dependencies between them. A scheduler can then automatically determine the correct execution order and extract parallelism. Task programming is well-known to be a very effective way to leverage parallel hardware (and is gaining popularity among game developers ), however there is significant programming overhead associated with maintaining a program in this form. |
<filename>plugins/gdifont/include/sge/gdifont/convert/align_h.hpp
// Copyright <NAME> 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_GDIFONT_CONVERT_ALIGN_H_HPP_INCLUDED
#define SGE_GDIFONT_CONVERT_ALIGN_H_HPP_INCLUDED
#include <sge/font/align_h/variant_fwd.hpp>
#include <sge/gdifont/include_windows.hpp>
namespace sge
{
namespace gdifont
{
namespace convert
{
UINT align_h(sge::font::align_h::variant const &);
}
}
}
#endif
|
In its first year of managing the public school system in Chelsea, Mass., Boston University hired a superintendent of "exceptional ability" and negotiated a promising contract with the teachers' union, but it fell short in its efforts to raise money for the project, the first-annual report on the unprecedented partnership has concluded.
The report paints a picture of a school system in radical transition: It says the district's 10-year management contract with the university has affected everything from the district's budgeting process to playgrounds at its elementary schools.
In writing the summary, Peter R. Greer, dean of the university's school of education and chairman of the management team that oversees the project, drew on reports from teachers, administrators, staff members, parents, Chelsea residents, professors, and student volunteers from the university.
"The data in this report provide evidence of the substantial achievements in the Chelsea schools in the first year of our collaboration," Mr. Greer writes. "We believe this evidence disproves the claims of detractors, both those who opposed the formation of the partnership and those who seek to thwart its promise now."
"We have not done everything right," Mr. Greer adds, "but the Chelsea/Boston University partnership has clearly begun to move the schools in the right direction."
Shortly after the university contract with the district took effect more than a year ago, the management team hired Diana Lam, an area superintendent in the Boston school system, to serve as superintendent of the Chelsea schools.
The negotiations over the new contract were complicated by "incorrect assumptions" that the partnership with the university would make tax increases unnecessary, the report says, or that the university's endowment could be tapped to meet expenses in Chelsea.
In fact, the report notes, it is not widely understood in the community that the money Boston University raises for the project must be used for specific programs, not for salaries, textbooks, or basic school facilities.
The city "must provide more than the 17 cents per tax dollar--the lowest figure in the state--it now allocates for education," Mr. Greer writes.
Although the university hoped to raise $3 million in the first year, it only raised $2.167 million.
In an interview, Mr. Greer said many corporations and foundations prefer to "back a good horse" rather than take a chance on an experimental program.
The fund-raising gap made it impossible for the Chelsea management team to begin preschool and early-childhood programs on the wide scale that had been planned, although elementary-school programs were expanded.
Of the money raised, $800,000 paid for the installation of computers in each of Chelsea's six schools. They are used for instruction and administration and have enabled the district to computerize its budget for the first time, the report says.
The university's school of public health, working with the district and other community agencies, developed a comprehensive health-services plan that will provide students with counseling, immunizations, dental care, nutritional services, and weight counseling.
The university's school of social work put together a drug-education workshop for students and developed a plan for coordinating services with parents that began this fall.
More than 200 b.u. students and staff members participated in a tutoring program that is credited with helping to reduce by 50 percent student failures in the third quarter of the school year.
But, the report notes, the tutoring program received more requests for assistance than it could meet, and suffered because of the difficulties students had traveling between the university and Chelsea and with fitting the tutoring work into their schedules.
A fraternity at Boston University also "adopted" an elementary school, painting a mural depicting the students in professional occupations and restoring its playground.
Objectives have been established for reading, writing, math, science, and social studies in kindergarten through 8th grade, and teachers are to be trained this year in techniques for meeting them, Mr. Greer said.
The management committee has decided to make music a central component of education in Chelsea, in the hope that it will help students develop self-discipline and will draw parents into the schools to hear their children play.
Chelsea's high school has been restructured into three separate schools: a traditional high school, an alternative school for students at risk of dropping out, and a "renaissance school" in which teachers work in teams and set their own schedules.
The superintendent developed the programs to eliminate the pervasive academic tracking in Chelsea, Mr. Greer explained.
The project also has launched an intergenerational literacy program that is teaching 66 adults to read and write and has taught 137 how to teach their children to read and write.
During the current school year, Mr. Greer said, the emphasis will be on intensive staff development for teachers.
"The results are good in terms of teachers working hard," he said. "What we're looking for is student achievement." |
Too cute to pass up - check out this sweet 3/2 pool home with a huge back yard! Lovely pergo floors in the living room, carpet in the bedrooms and tile in the rest of the house. Inside laundry, bright open kitchen with breakfast bar, updated hall bath are just a few of the upgrades you will find inside. Outside is a 3 year new salt water pool with huge screened lanai that opens to your fenced in spacious backyard. A metal roof and aluminum siding adorn the outside. Call me at 321-544-5428for more details about your new home!! |
/*
* Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* HP designates this particular file as subject to the "Classpath" exception
* as provided by HP in the LICENSE.txt file that accompanied this code.
*/
#include "foedus/storage/hash/hash_reserve_impl.hpp"
#include <glog/logging.h>
#include "foedus/assert_nd.hpp"
#include "foedus/memory/numa_core_memory.hpp"
#include "foedus/storage/hash/hash_page_impl.hpp"
#include "foedus/thread/thread.hpp"
namespace foedus {
namespace storage {
namespace hash {
ErrorCode ReserveRecords::run(xct::SysxctWorkspace* sysxct_workspace) {
ASSERT_ND(aggressive_payload_count_hint_ >= payload_count_);
return find_or_create_or_expand(sysxct_workspace, target_, hint_check_from_);
}
ErrorCode ReserveRecords::find_or_create_or_expand(
xct::SysxctWorkspace* sysxct_workspace,
HashDataPage* page,
DataPageSlotIndex examined_records) {
ASSERT_ND(!page->header().snapshot_);
// lock the page first so that there is no race on new keys.
VolatilePagePointer next_pointer = page->next_page().volatile_pointer_;
if (next_pointer.is_null()) {
CHECK_ERROR_CODE(context_->sysxct_page_lock(sysxct_workspace, reinterpret_cast<Page*>(page)));
next_pointer = page->next_page().volatile_pointer_;
} else {
// If the page already has a next-page pointer, the page is already finalized. Skip locking.
assorted::memory_fence_acquire(); // must check next-page BEFORE everything else
}
// In either case, from now on this page is finalized
ASSERT_ND(page->is_locked() || !next_pointer.is_null());
const DataPageSlotIndex count = target_->get_record_count();
ASSERT_ND(examined_records <= count);
// Locate the key in this page.
DataPageSlotIndex index;
if (examined_records == count) {
#ifndef NDEBUG
// is examined_records correct? let's confirm
index = search_within_page(page, examined_records, 0);
ASSERT_ND(index == kSlotNotFound);
#endif // NDEBUG
index = kSlotNotFound;
} else {
// We can skip the first examined_records records.
// We took the page lock, so physical-only search is enough.
index = search_within_page(page, count, examined_records);
}
if (index == kSlotNotFound) {
// still no match, This is simpler.
if (!next_pointer.is_null()) {
// We have a next page, let's go on.
// This is so far a recursion. Easier to debug than a loop.
// Stackoverflow? If you have a long chain in hash bucket, you are already screwed
HashDataPage* next_page = context_->resolve_cast<HashDataPage>(next_pointer);
return find_or_create_or_expand(sysxct_workspace, next_page, 0);
} else {
// This is the tail page. and we locked it.
// We simply create a new physical record.
ASSERT_ND(page->is_locked());
return create_new_record_in_tail_page(page);
}
} else {
// We found a match! This is either super easy or complex
ASSERT_ND(index >= examined_records);
ASSERT_ND(index < count);
if (page->get_slot(index).get_max_payload() >= payload_count_) {
// This record is enough spacious. we are done! a super easy case.
out_slot_ = index;
out_page_ = page;
return kErrorCodeOk;
} else {
// We need to expand this record. To do that, we need to lock this record and move it.
// This can be complex.
return expand_record(sysxct_workspace, page, index);
}
}
}
ErrorCode ReserveRecords::expand_record(
xct::SysxctWorkspace* sysxct_workspace,
HashDataPage* page,
DataPageSlotIndex index) {
auto* record = &page->get_slot(index).tid_;
CHECK_ERROR_CODE(context_->sysxct_record_lock(
sysxct_workspace,
page->get_volatile_page_id(),
record));
// After locking, now the record status is finalized.
if (record->is_moved()) {
// If we now find it moved, we have two choices.
// 1) resume the search. the new location should be somewhere after here.
// 2) retry the whole sysxct.
// We do 2) to save coding (yikes!). Excuse: This case should be rare.
LOG(INFO) << "Rare. The record turns out to be moved after locking. Retry the sysxct";
return kErrorCodeXctRaceAbort;
}
// Now, because we locked a record of the key, and because it wasn't moved yet,
// we are sure that this is the only record in this hash bucket that might contain this key.
// We'll be done as soon as we figure out where to move this record.
HashDataPage* tail;
CHECK_ERROR_CODE(find_and_lock_spacious_tail(sysxct_workspace, page, &tail));
ASSERT_ND(tail->is_locked());
ASSERT_ND(tail->available_space()
>= HashDataPage::required_space(key_length_, aggressive_payload_count_hint_));
// Copy the XID of the existing record
out_slot_ = append_record_to_page(tail, record->xct_id_);
out_page_ = tail;
// Now we mark the old record as moved
assorted::memory_fence_release();
record->xct_id_.set_moved();
return kErrorCodeOk;
}
ErrorCode ReserveRecords::find_and_lock_spacious_tail(
xct::SysxctWorkspace* sysxct_workspace,
HashDataPage* from_page,
HashDataPage** tail) {
*tail = nullptr;
HashDataPage* cur = from_page;
while (true) {
VolatilePagePointer next_pointer = cur->next_page().volatile_pointer_;
if (!next_pointer.is_null()) {
cur = context_->resolve_cast<HashDataPage>(next_pointer);
continue;
}
// cur looks like a tail page, but we need to confirm that after locking.
CHECK_ERROR_CODE(context_->sysxct_page_lock(sysxct_workspace, reinterpret_cast<Page*>(cur)));
if (!cur->next_page().volatile_pointer_.is_null()) {
LOG(INFO) << "Rare. Someone has just made a next page";
continue;
}
const uint16_t available_space = cur->available_space();
const uint16_t required_space
= HashDataPage::required_space(key_length_, aggressive_payload_count_hint_);
if (available_space >= required_space) {
*tail = cur;
return kErrorCodeOk;
} else {
// need to make a new page..
HashDataPage* new_tail;
CHECK_ERROR_CODE(create_new_tail_page(cur, &new_tail));
// Then, after all, we "publish" this new page
assorted::memory_fence_release(); // so that others don't see uninitialized page
cur->next_page().volatile_pointer_ = new_tail->get_volatile_page_id();
assorted::memory_fence_release(); // so that others don't have "where's the next page" issue
cur->header().page_version_.set_has_next_page();
// We could immediately make a record in this page before the publish above.
// If we do that we could avoid lock here. But the code becomes a bit uglier.
// record-expand is anyway a costly operation, so ok for now.
CHECK_ERROR_CODE(context_->sysxct_page_lock(
sysxct_workspace,
reinterpret_cast<Page*>(new_tail)));
*tail = new_tail;
return kErrorCodeOk;
}
}
}
ErrorCode ReserveRecords::create_new_tail_page(
HashDataPage* cur_tail,
HashDataPage** new_tail) {
ASSERT_ND(cur_tail->is_locked());
DVLOG(2) << "Volatile HashDataPage is full. Adding a next page..";
const VolatilePagePointer new_pointer
= context_->get_thread_memory()->grab_free_volatile_page_pointer();
if (UNLIKELY(new_pointer.is_null())) {
return kErrorCodeMemoryNoFreePages;
}
*new_tail = context_->resolve_newpage_cast<HashDataPage>(new_pointer.get_offset());
(*new_tail)->initialize_volatile_page(
cur_tail->header().storage_id_,
new_pointer,
reinterpret_cast<Page*>(cur_tail),
cur_tail->get_bin(),
cur_tail->get_bin_shifts());
return kErrorCodeOk;
}
ErrorCode ReserveRecords::create_new_record_in_tail_page(HashDataPage* tail) {
ASSERT_ND(tail->is_locked());
ASSERT_ND(tail->next_page().volatile_pointer_.is_null());
// do we have enough room in this page?
const uint16_t available_space = tail->available_space();
const uint16_t required_space
= HashDataPage::required_space(key_length_, aggressive_payload_count_hint_);
xct::XctId initial_xid;
initial_xid.set(
Epoch::kEpochInitialCurrent, // TODO(Hideaki) this should be something else
0);
initial_xid.set_deleted();
if (available_space < required_space) {
// This page can't hold it. Let's make a new page.
HashDataPage* new_tail;
CHECK_ERROR_CODE(create_new_tail_page(tail, &new_tail));
// Then append a record to it.
out_slot_ = append_record_to_page(new_tail, initial_xid);
ASSERT_ND(out_slot_ == 0); // it's the first record in the new page
out_page_ = new_tail;
// Then, after all, we "publish" this new page
assorted::memory_fence_release(); // so that others don't see uninitialized page
tail->next_page().volatile_pointer_ = new_tail->get_volatile_page_id();
assorted::memory_fence_release(); // so that others don't have "where's the next page" issue
tail->header().page_version_.set_has_next_page();
} else {
// the page is enough spacious, and has no next page. we rule!
out_slot_ = append_record_to_page(tail, initial_xid);
out_page_ = tail;
}
return kErrorCodeOk;
}
DataPageSlotIndex ReserveRecords::search_within_page(
const HashDataPage* page,
DataPageSlotIndex key_count,
DataPageSlotIndex examined_records) const {
ASSERT_ND(!page->header().snapshot_);
ASSERT_ND(page->header().page_version_.is_locked()
|| !page->next_page().volatile_pointer_.is_null());
ASSERT_ND(key_count == page->get_record_count());
return page->search_key_physical(
combo_.hash_,
combo_.fingerprint_,
key_,
key_length_,
key_count,
examined_records);
}
DataPageSlotIndex ReserveRecords::append_record_to_page(
HashDataPage* page,
xct::XctId initial_xid) const {
ASSERT_ND(page->available_space()
>= HashDataPage::required_space(key_length_, aggressive_payload_count_hint_));
DataPageSlotIndex index = page->get_record_count();
auto& slot = page->get_new_slot(index);
slot.offset_ = page->next_offset();
slot.hash_ = combo_.hash_;
slot.key_length_ = key_length_;
slot.physical_record_length_ = assorted::align8(key_length_) + assorted::align8(payload_count_);
slot.payload_length_ = 0;
char* record = page->record_from_offset(slot.offset_);
std::memcpy(record, key_, key_length_);
if (key_length_ % 8 != 0) {
std::memset(record + key_length_, 0, 8 - (key_length_ % 8));
}
slot.tid_.reset();
slot.tid_.xct_id_ = initial_xid;
// we install the fingerprint to bloom filter BEFORE we increment key count.
// it's okay for concurrent reads to see false positives, but false negatives are wrong!
page->bloom_filter_.add(combo_.fingerprint_);
// we increment key count AFTER installing the key because otherwise the optimistic read
// might see the record but find that the key doesn't match. we need a fence to prevent it.
assorted::memory_fence_release();
page->header_.increment_key_count();
return index;
}
} // namespace hash
} // namespace storage
} // namespace foedus
|
Palaeolithic occupation and cultural transition in the Wainganga River Basin, India Abstract The Pleistocene archaeological record of South Asia is important for addressing questions relating to the origin and evolution of Palaeolithic cultures, continuity or change in lithic technologies, and population dispersals across Asia. Here, the authors report on intensive regional studies to investigate variability within this record, employing field survey, lithic analysis and experimental knapping. They examine Palaeolithic hominin behavioural change in the Wainganga Basin, central India, focusing on variability in spatial distribution, stratigraphy and lithic reduction strategies in Acheulian to Late Palaeolithic sites. This emphasises the diversity of cultural sequences in South Asia and contributes to questions of transition and change based on cultural preferences, raw materials and lithic strategies in different regions. |
import { expect } from 'chai'
import { CacheInstancesByKey } from '../../../src'
describe('CacheInstancesByKey', () => {
const getFoo = (limit = Infinity) => {
@CacheInstancesByKey(limit)
class Foo {
constructor(public bar: string) {}
}
return Foo
}
it('should return the same instance when passing the same key', () => {
const Foo = getFoo()
const a = new Foo('goo')
const b = new Foo('goo')
expect(a).to.equal(b)
})
it('should return an instanc for each key', () => {
const Foo = getFoo()
const a = new Foo('goo')
const b = new Foo('goo')
const c = new Foo('buzz')
const d = new Foo('buzz')
expect(a).to.equal(b)
expect(c).to.equal(d)
expect(b).not.equal(c)
})
it('should delete old instances from the cache when crossing the limit', () => {
const Foo = getFoo(2)
const fuzz = new Foo('goo')
new Foo('foo')
new Foo('oof')
const buzz = new Foo('goo')
expect(fuzz).not.to.equal(buzz)
})
})
|
<gh_stars>10-100
/*============================================================================
This C header file is part of TestFloat, Release 3e, a package of programs for
testing the correctness of floating-point arithmetic complying with the IEEE
Standard for Floating-Point, by <NAME>.
Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#include <stdint.h>
/*----------------------------------------------------------------------------
| Warning: This list must match the contents of "functionInfos.c".
*----------------------------------------------------------------------------*/
enum {
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
#ifdef FLOAT16
UI32_TO_F16 = 1,
UI32_TO_F32,
#else
UI32_TO_F32 = 1,
#endif
#ifdef FLOAT64
UI32_TO_F64,
#endif
#ifdef EXTFLOAT80
UI32_TO_EXTF80,
#endif
#ifdef FLOAT128
UI32_TO_F128,
#endif
#ifdef FLOAT16
UI64_TO_F16,
#endif
UI64_TO_F32,
#ifdef FLOAT64
UI64_TO_F64,
#endif
#ifdef EXTFLOAT80
UI64_TO_EXTF80,
#endif
#ifdef FLOAT128
UI64_TO_F128,
#endif
#ifdef FLOAT16
I32_TO_F16,
#endif
I32_TO_F32,
#ifdef FLOAT64
I32_TO_F64,
#endif
#ifdef EXTFLOAT80
I32_TO_EXTF80,
#endif
#ifdef FLOAT128
I32_TO_F128,
#endif
#ifdef FLOAT16
I64_TO_F16,
#endif
I64_TO_F32,
#ifdef FLOAT64
I64_TO_F64,
#endif
#ifdef EXTFLOAT80
I64_TO_EXTF80,
#endif
#ifdef FLOAT128
I64_TO_F128,
#endif
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
#ifdef FLOAT16
F16_TO_UI32,
F16_TO_UI64,
F16_TO_I32,
F16_TO_I64,
F16_TO_UI32_R_MINMAG,
F16_TO_UI64_R_MINMAG,
F16_TO_I32_R_MINMAG,
F16_TO_I64_R_MINMAG,
F16_TO_F32,
#ifdef FLOAT64
F16_TO_F64,
#endif
#ifdef EXTFLOAT80
F16_TO_EXTF80,
#endif
#ifdef FLOAT128
F16_TO_F128,
#endif
F16_ROUNDTOINT,
F16_ADD,
F16_SUB,
F16_MUL,
F16_MULADD,
F16_DIV,
F16_REM,
F16_SQRT,
F16_EQ,
F16_LE,
F16_LT,
F16_EQ_SIGNALING,
F16_LE_QUIET,
F16_LT_QUIET,
#endif
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
F32_TO_UI32,
F32_TO_UI64,
F32_TO_I32,
F32_TO_I64,
F32_TO_UI32_R_MINMAG,
F32_TO_UI64_R_MINMAG,
F32_TO_I32_R_MINMAG,
F32_TO_I64_R_MINMAG,
#ifdef FLOAT16
F32_TO_F16,
#endif
#ifdef FLOAT64
F32_TO_F64,
#endif
#ifdef EXTFLOAT80
F32_TO_EXTF80,
#endif
#ifdef FLOAT128
F32_TO_F128,
#endif
F32_ROUNDTOINT,
F32_ADD,
F32_SUB,
F32_MUL,
F32_MULADD,
F32_DIV,
F32_REM,
F32_SQRT,
F32_EQ,
F32_LE,
F32_LT,
F32_EQ_SIGNALING,
F32_LE_QUIET,
F32_LT_QUIET,
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
#ifdef FLOAT64
F64_TO_UI32,
F64_TO_UI64,
F64_TO_I32,
F64_TO_I64,
F64_TO_UI32_R_MINMAG,
F64_TO_UI64_R_MINMAG,
F64_TO_I32_R_MINMAG,
F64_TO_I64_R_MINMAG,
#ifdef FLOAT16
F64_TO_F16,
#endif
F64_TO_F32,
#ifdef EXTFLOAT80
F64_TO_EXTF80,
#endif
#ifdef FLOAT128
F64_TO_F128,
#endif
F64_ROUNDTOINT,
F64_ADD,
F64_SUB,
F64_MUL,
F64_MULADD,
F64_DIV,
F64_REM,
F64_SQRT,
F64_EQ,
F64_LE,
F64_LT,
F64_EQ_SIGNALING,
F64_LE_QUIET,
F64_LT_QUIET,
#endif
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
#ifdef EXTFLOAT80
EXTF80_TO_UI32,
EXTF80_TO_UI64,
EXTF80_TO_I32,
EXTF80_TO_I64,
EXTF80_TO_UI32_R_MINMAG,
EXTF80_TO_UI64_R_MINMAG,
EXTF80_TO_I32_R_MINMAG,
EXTF80_TO_I64_R_MINMAG,
#ifdef FLOAT16
EXTF80_TO_F16,
#endif
EXTF80_TO_F32,
#ifdef FLOAT64
EXTF80_TO_F64,
#endif
#ifdef FLOAT128
EXTF80_TO_F128,
#endif
EXTF80_ROUNDTOINT,
EXTF80_ADD,
EXTF80_SUB,
EXTF80_MUL,
EXTF80_DIV,
EXTF80_REM,
EXTF80_SQRT,
EXTF80_EQ,
EXTF80_LE,
EXTF80_LT,
EXTF80_EQ_SIGNALING,
EXTF80_LE_QUIET,
EXTF80_LT_QUIET,
#endif
/*------------------------------------------------------------------------
*------------------------------------------------------------------------*/
#ifdef FLOAT128
F128_TO_UI32,
F128_TO_UI64,
F128_TO_I32,
F128_TO_I64,
F128_TO_UI32_R_MINMAG,
F128_TO_UI64_R_MINMAG,
F128_TO_I32_R_MINMAG,
F128_TO_I64_R_MINMAG,
#ifdef FLOAT16
F128_TO_F16,
#endif
F128_TO_F32,
#ifdef FLOAT64
F128_TO_F64,
#endif
#ifdef EXTFLOAT80
F128_TO_EXTF80,
#endif
F128_ROUNDTOINT,
F128_ADD,
F128_SUB,
F128_MUL,
F128_MULADD,
F128_DIV,
F128_REM,
F128_SQRT,
F128_EQ,
F128_LE,
F128_LT,
F128_EQ_SIGNALING,
F128_LE_QUIET,
F128_LT_QUIET,
#endif
NUM_FUNCTIONS
};
enum {
ROUND_NEAR_EVEN = 1,
ROUND_MINMAG,
ROUND_MIN,
ROUND_MAX,
ROUND_NEAR_MAXMAG,
#ifdef FLOAT_ROUND_ODD
ROUND_ODD,
#endif
NUM_ROUNDINGMODES
};
enum {
TININESS_BEFORE_ROUNDING = 1,
TININESS_AFTER_ROUNDING,
NUM_TININESSMODES
};
extern const uint_fast8_t roundingModes[NUM_ROUNDINGMODES];
extern const uint_fast8_t tininessModes[NUM_TININESSMODES];
enum {
FUNC_ARG_UNARY = 0x01,
FUNC_ARG_BINARY = 0x02,
FUNC_ARG_ROUNDINGMODE = 0x04,
FUNC_ARG_EXACT = 0x08,
FUNC_EFF_ROUNDINGPRECISION = 0x10,
FUNC_EFF_ROUNDINGMODE = 0x20,
FUNC_EFF_TININESSMODE = 0x40,
FUNC_EFF_TININESSMODE_REDUCEDPREC = 0x80
};
struct functionInfo {
const char *namePtr;
unsigned char attribs;
};
extern const struct functionInfo functionInfos[NUM_FUNCTIONS];
struct standardFunctionInfo {
const char *namePtr;
unsigned char functionCode;
char roundingCode, exact;
};
extern const struct standardFunctionInfo standardFunctionInfos[];
|
A living cell is a complex assembly of molecular elements; to function properly, its constituent molecules must form associations and operate in an organized manner. Certain components bind together to form molecular superstructures, including organelles which compartmentalize cellular activities and filaments which impart order and control motility. Other components exist in soluble form, and may move freely throughout the cell or, alternatively, within a subcellular compartment.
Cells are also equipped with elements that synthesize, process, and secrete a designated subset of proteins. This so-called secretory pathway includes membrane associated structures, such as the endoplasmic reticulum and Golgi apparatus, as well as a number of resident soluble molecules which participate in the processing of secreted proteins. Proteins which are to be secreted pass through the Golgi apparatus, where they are packaged for export from the cell. Accompanying them, by virtue of the continual vesicular transport of membrane and endoplasmic reticulum luminal contents, are soluble proteins properly residing in the endoplasmic reticulum.
To avoid continuously losing and needing to resynthesize these resident proteins, the cell uses a membrane-bound receptor localized in or near the Golgi apparatus for their retrieval (Lewis and Pelham, 1992, Cell 68:353-364). The receptor binds to a specific carboxy-terminal amino acid sequence which serves as a marker of what proteins are to be returned to the endoplasmic reticulum; this sequence is generally lysine-aspartic acid-glutamic acid-leucine (Lys-Asp-Glu-Leu in the three-letter amino acid code, KDEL in the single-letter code, referred to herein as "KDEL"), so that the receptor is generally referred to as the KDEL (SEQ ID NO:37) receptor (Munro and Pelham, 1987, Cell 48:899-907; Pelham, 1988, EMBO J. 7:913-918). The human KDEL receptor has been characterized as a seven-transmembrane domain protein which is a temporary resident of the Golgi apparatus: upon binding to a KDEL (SEQ ID NO:37)-containing ligand, it moves to the endoplasmic reticulum, where the ligand is released (Townsley et al., 1993, EMBO J. 12:2821-2829).
Among the molecules interacting with the KDEL receptor are certain members of a class of proteins, referred to as "heat shock proteins", which form associations with nascent polypeptides in the endoplasmic reticulum and act as molecular "chaperones", escorting a protein through the assembly process prior to its secretion (Frydman et al., 1994, Nature 370:111-117; Hendrick and Hartl, Annu. Rev. Biochem. 62:349-384; Hartl, 1996, Nature 381:571-580). Heat shock proteins constitute a highly conserved class of proteins selectively expressed in cells under stressful conditions, such as sudden increases in temperature or glucose deprivation. Able to bind to a wide variety of other proteins in their non-native state, heat shock proteins participate in the manufacture of these bound proteins, including their synthesis, folding, assembly, disassembly and translocation (Freeman and Morimoto, 1996, EMBO J. 15:2969-2979; Lindquist and Craig, 1988, Annu. Rev. Genet. 22:631-677; Hendrick and Hartl, 1993, Annu. Rev. Biochem. 62:349-384).
Two heat shock proteins which contain ligand sequences for the KDEL receptor are gp96 and BiP. Found in higher eukaryotes but not in Drosophila or yeast, gp96 appears to have evolved relatively recently, perhaps by a duplication of the gene encoding the cytosolic heat shock protein hsp90, to which it is highly related (Li and Srivastava, 1993, EMBO J. 12:3143-3151; identity between human hsp90 and murine gp96 is about 48 percent; Wiech et al., 1992, Nature 358:169-170; Melnick et al., 1992, J. Biol. Chem. 267:21303-21306; Melnick et al., 1994, Nature 370:373-375; Schaiff et al., 1992, J. Exp. Med. 176:657-666; Ramakrishnan et al., 1995, DNA and Cell Biol. 14:373-384). BiP (also referred to in the literature as grp78) forms a complex with newly synthesized immunoglobulin chains (Bole et al., 1986, J. Cell Biol. 102:1558-1566).
Under certain circumstances, it may be desirable to interfere with the normal control of KDEL (SEQ ID NO:37)-mediated protein redistribution. According to the present invention, a subject may benefit, for example, from the secretion of heat shock proteins which are normally retained in the endoplasmic reticulum but which have beneficial immunogenic effects when released.
Heat shock proteins are believed to play a role in the immune response in several contexts. Inoculation with heat shock protein prepared from tumors of experimental animals has been shown to induce immune responses in a tumor-specific manner; that is to say, heat shock protein gp96 purified from a particular tumor could induce an immune response which would inhibit the growth of cells from the identical tumor of origin, but not other tumors, regardless of relatedness (Srivastava and Maki, 1991, Curr. Topics Microbiol. 167:109-123). High-resolution gel electrophoresis has indicated that tumor-derived gp96 may be heterogeneous at the molecular level; evidence suggests that the source of this heterogeneity may be populations of small peptides adherent to the heat shock protein, which may number in the hundreds (Feldweg and Srivastava, 1995, Int. J. Cancer 63:310-314). Indeed, an antigenic peptide of vesicular stomatitis virus has been shown to associate with gp96 in virus infected cells (Nieland et al., 1996, Proc. Natl. Acad. Sci. U.S.A. 93:6135-6139). It has been suggested that this accumulation of peptides is related to the localization of gp96 in the endoplasmic reticulum, where it may act as a peptide acceptor and accessory to peptide loading of major histocompatability complex class I molecules (Li and Srivastava, 1993, EMBO J. 12:3143-3151; Suto and Srivastava, 1995, Science 269:1585-1588). Recent studies have shown that protein disulfide isomerase ("PDI"), a resident luminal protein of the endoplasmic reticulum having a molecular weight of approximately 60kDa, may also function as a peptide acceptor (Lammert et al., 1997, Eur. J. Immunol. 27:1685-1690).
Further, the use of heat shock proteins as adjuvants to stimulate an immune response has been proposed (see, for example, Edgington, 1995, Bio/Technol. 13:1442-1444; PCT Application International Publication Number WO 94/29459 by the Whitehead Institute for Biomedical Research, Richard Young, inventor, and references infra). One of the best known adjuvants, Freund's complete adjuvant, contains a mixture of heat shock proteins derived from mycobacteria (the genus of the bacterium which causes tuberculosis); Freund's complete adjuvant has been used for years to boost the immune response to non-mycobacterial antigens. A number of references suggest, inter alia, the use of isolated mycobacterial heat shock proteins for a similar purpose, including vaccination against tuberculosis itself (Lukacs et al., 1993, J. Exp. Med. 178:343-348; Lowrie et al., 1994, Vaccine 12:1537-1540; Silva and Lowrie, 1994, Immunology 82:244-248; Lowrie et al., 1995, J. Cell. Biochem. Suppl. 0(19b):220; Retzlaff et al., 1994, Infect. Immun. 62:5689-5693; PCT Application International Publication No. WO 94/11513 by the Medical Research Council, Colston et al., inventors; PCT Application International Publication No. WO 93/1771 by Biocine Sclavo Spa, Rappuoli et al., inventors).
Increased levels of autologous heat shock proteins may also lead to an improved immune response by virtue of the association of heat shock proteins with endogenous antigenic peptides (International Application No. PCT/US96/13233 by Rothman et al.). Such activity is distinct from the traditionally utilized adjuvant activity of heterologous heat shock proteins.
The present invention is directed toward increasing the secretion of antigenic heat shock protein complexes by inhibiting KDEL receptor-mediated return of such complexes to the endoplasmic reticulum. Analogous methods may be used to increase the secretion of other proteins of interest which normally would tend to be retained via the KDEL receptor. |
The invention relates generally to input/output data processing in computer systems and particularly to reducing the number of interrupts required for the processing of such I/O data.
Today""s networks transmit data at rates equal to multi-gigabytes per second and these rates continue to increase as user demands for ever faster transmission increase. Computing systems usually include input/output drivers that receive data packets from incoming lines, store the packets, and interrupt a host processor to alert the host of the presence of data for the host to process. Traditionally, an I/O device interrupts a host each time a complete packet of data is received and stored. As data transmission rates rise, this traditional technique of interrupting for each received packet consumes more and more of a host""s processing resources, to the point that the traditional technique is unacceptable. Consequently, there have been attempts to reduce the interrupt rate to more efficiently utilize a host processor""s resources. For example, one improved technique is disclosed in U.S. Pat. No. 5,659,758, which issued to Gentry et al on Aug. 19, 1997 Gentry teaches a technique that reduces the number of interrupts, while guaranteeing that a host will eventually be interrupted, based on elapsed time or the number of packets received. In Gentry, the I/O device is initially placed in a state such that the first received packet generates an interrupt. Thereafter, an interrupt will be generated each time N packets are received or for the next packet received after the expiration of a fixed time interval T. Thus, after receipt of an initial packet, if a burst of packets are received in short order, an interrupt is generated after each N of these packets. On the other hand, if less than N packets are received when the time interval T expires, then the next packet received thereafter will cause an interrupt. Gentry also mentions that the parameters N and T may be changed by the host. However, Gentry does not teach any algorithm that the host might use for changing these parameters.
While meritorious, Gentry still suffers from certain deficiencies. For example, it is possible for less than N packets to arrive before the expiration of T. In this event, the number of received packets is insufficient to trigger the interrupt based on N. When T expires, the I/O driver is primed to interrupt on the next received packet. However, if there is a long delay in receipt of the next packet, the interrupt is delayed and the resulting latency in processing of the already received packets may be intolerable. More important, however, is the fact that Gentry still generates a significant number of interrupts, which as transmission rates continue to increase can still present a performance problem. Further improvements are needed.
The invention improves the known methods of generating interrupts for the servicing of packets. The method is based on dynamic communication between an I/O adapter and a host I/O driver for which the data is destined. The invention has the capability to receive data and pass the data to the host for long periods of time with only a single initial interrupt of the host. If the host begins to fall behind in its processing of received data, the invention has the capability to monitor the situation and to initiate additional interrupts to the host. If additional interrupts are needed because the host is falling behind, the invention can initiate additional processes for the processing of the data to relieve the host situation,
In the preferred embodiment, an arriving block of data is stored in a next element of an ordered array of storage elements by a data receiving process. That element is then marked as filled. If an I/O process for processing the elements is already executing, in general, no I/O interrupt is generated. The I/O process is designed to continue executing as long as there elements marked as filled to process. If an I/O process is not executing, an interrupt is generated to initiate the I/O process. Thereafter, the processing of elements by the I/O process is monitored by the data receiving process. If the I/O process falls behind the data receiving process by a specified threshold, another interrupt is generated by the data receiving process. When the I/O process begins to process a given element, that element is marked as not filled.
In the preferred embodiment, monitoring of the I/O process begins after the data receiving process fills an element and then determines that processing of an earlier filled element in the array has not begun. This earlier element is the element immediately preceding the element just filled in the preferred embodiment. During monitoring, the number of previously filled elements that are still marked as filled are counted and if this count exceeds a specified threshold, an additional interrupt is generated. Monitoring also includes measuring the time interval between the filling of an element with arriving data and the initiation of processing of that element by the input/output process. Another interrupt is generated if this time interval exceeds a specified time threshold. |
Toxic shock syndrome presenting as postoperative diarrhea in a postmenopausal woman. Three days after laminectomy, toxic shock syndrome (TSS) presented as acute diarrhea, rash, and fever in a 62-year-old postmenopausal woman. Forty-eight hours later, the full syndrome of TSS developed. Exploration of a benign-appearing wound revealed an occult Staphylococcus aureus infection. This report and literature review underscore the need to consider TSS in the differential diagnosis of acute diarrhea regardless of age, sex, race, and menstrual status, particularly when there has been recent soft tissue infection, injury, or surgery of any type. |
//! An alternative AWS Lambda runtime for Rust. It was written based on the official
//! `lambda_runtime` and was designed to be used along with the trustworthy
//! `aws_lambda_event` crate.
//!
//! The idea behind this crate is to provide an easy-to-use api for AWS Serverless Developers,
//! leveraging enterprise-grade semantics in the powerful Rust ecosystem.
pub use runtime::*;
pub use model::Context;
pub use error::Error;
// Modules
pub mod runtime;
pub mod model;
pub mod lambda_api;
pub mod error;
|
/* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */
package test;
import oracle.jbo.client.Configuration;
import oracle.jbo.*;
public class Test {
public static void main(String[] args) {
String _am = "test.hr.HRModule", _cf = "HRModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(_am,_cf);
ViewObject vo = am.findViewObject("Departments");
System.out.println(vo.getDefFullName());
Configuration.releaseRootApplicationModule(am,true);
}
}
|
import * as val from "./lib/caller";
export default val;
|
<filename>src/i586-zephyr-elf/lib/gcc/i586-zephyr-elf/6.3.0/plugin/include/cfgloopmanip.h
/* Loop manipulation header.
Copyright (C) 2014-2016 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_CFGLOOPMANIP_H
#define GCC_CFGLOOPMANIP_H
enum
{
CP_SIMPLE_PREHEADERS = 1,
CP_FALLTHRU_PREHEADERS = 2
};
#define DLTHE_FLAG_UPDATE_FREQ 1 /* Update frequencies in
duplicate_loop_to_header_edge. */
#define DLTHE_RECORD_COPY_NUMBER 2 /* Record copy number in the aux
field of newly create BB. */
#define DLTHE_FLAG_COMPLETTE_PEEL 4 /* Update frequencies expecting
a complete peeling. */
extern edge mfb_kj_edge;
extern bool remove_path (edge);
extern void place_new_loop (struct function *, struct loop *);
extern void add_loop (struct loop *, struct loop *);
extern void scale_loop_frequencies (struct loop *, int, int);
extern void scale_loop_profile (struct loop *, int, gcov_type);
extern edge create_empty_if_region_on_edge (edge, tree);
extern struct loop *create_empty_loop_on_edge (edge, tree, tree, tree, tree,
tree *, tree *, struct loop *);
extern struct loop *loopify (edge, edge,
basic_block, edge, edge, bool,
unsigned, unsigned);
extern void unloop (struct loop *, bool *, bitmap);
extern void copy_loop_info (struct loop *loop, struct loop *target);
extern struct loop * duplicate_loop (struct loop *, struct loop *);
extern void duplicate_subloops (struct loop *, struct loop *);
extern bool can_duplicate_loop_p (const struct loop *loop);
extern bool duplicate_loop_to_header_edge (struct loop *, edge,
unsigned, sbitmap, edge,
vec<edge> *, int);
extern bool mfb_keep_just (edge);
basic_block create_preheader (struct loop *, int);
extern void create_preheaders (int);
extern void force_single_succ_latches (void);
struct loop * loop_version (struct loop *, void *,
basic_block *, unsigned, unsigned, unsigned, bool);
#endif /* GCC_CFGLOOPMANIP_H */
|
/*
* uart.h
*
* Created: 28-03-2018 05:05:48
* Author: vikas
*/
#ifndef UART_H_
#define UART_H_
#include <avr/io.h>
#include <stdio.h>
static void USART_Init(unsigned int);
static int USART_Transmit(char , FILE* );
static int USART_Receive(FILE* );
static FILE mystdout;
void USART_Init(unsigned int ubrr)
{
/*Set baud rate */
UBRR0H = (unsigned char)(ubrr>>8);
UBRR0L = (unsigned char)ubrr;
// Enable transmitter and receiver
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
/* Set frame format: 8data, 2stop bit */
UCSR0C = (1<<USBS0)|(3<<UCSZ00);
fdev_setup_stream(&mystdout, USART_Transmit, USART_Receive, _FDEV_SETUP_RW);
stdout = &mystdout;
stdin = &mystdout;
}
// function to send data - NOT REQUIRED FOR THIS PROGRAM IMPLEMENTATION
inline int USART_Transmit(char data, FILE* stream)
{
/* Wait for empty transmit buffer */
if (data == '\n')
USART_Transmit('\r',stream);
while ( !( UCSR0A & (1<< UDRE0)) )
;
/* Put data into buffer, sends the data */
UDR0 = data;
return 0;
}
// function to receive data
inline int USART_Receive(FILE* stream)
{
/* Wait for data to be received */
while ( !(UCSR0A & (1<<RXC0)) );
/* Get and return received data from buffer */
return UDR0;
}
#endif /* UART_H_ */ |
Design and Development of Caged Ball Heart Valve Using Solid Works Currently, over 2, 90,000 heart valve surgeries are performed worldwide annually and that number is estimated to triple by 2050. Even though patients with prosthetic valves lead a life relatively free from symptoms, problems like physiological complications and valve failure are significant. To date, all mechanical heart valves are plagued with complications associated with hemolysis and coagulation. These complications are believed to be associated with non-physiological blood flow patterns in the vicinity of the artificial heart valves. The geometry of the valve prosthesis with respect to the mitral valve annulus may significantly affect the flow dynamics in the human heart. It is thus essential to assess the hemodynamics of mitral prosthetic caged ball valve to improve the design of the device. This research work presents a 3D model of the left human heart with optimized mitral caged ball valve engineered by a computational tool (SolidWorks 2009). The performance of the valve like hemodynamics across the valve, stress analysis and physical properties like mass, surface area, etc. is assessed virtually. This limits the need to perform extensive, costly and timeconsuming in-vitro and animal tests. Thus optimization of the caged ball heart valve design facilitates reduction of flow-induced thrombogenicity and reduces the need for post-implant anticoagulants. |
A Novel Optical Tissue Clearing Protocol for Mouse Skeletal Muscle to Visualize Endplates in Their Tissue Context Neuromuscular junctions (NMJs) mediate skeletal muscle contractions and play an important role in several neuromuscular disorders when their morphology and function are compromised. However, due to their small size and sparse distribution throughout the comparatively large, inherently opaque muscle tissue the analysis of NMJ morphology has been limited to teased fiber preparations, longitudinal muscle sections, and flat muscles. Consequently, whole mount analyses of NMJ morphology, numbers, their distribution, and assignment to a given muscle fiber have also been impossible to determine in muscle types that are frequently used in experimental paradigms. This impossibility is exacerbated by the lack of optical tissue clearing techniques that are compatible with clear and persistent NMJ stains. Here, we present MYOCLEAR, a novel and highly reproducible muscle tissue clearing protocol. Based on hydrogel-based tissue clearing methods, this protocol permits the labeling and detection of all NMJs in adult hindleg extensor digitorum longus muscles from wildtype and diseased mice. The method is also applicable to adult mouse diaphragm muscles and can be used for different staining agents, including toxins, lectins, antibodies, and nuclear dyes. It will be useful in understanding the distribution, morphological features, and muscle tissue context of NMJs in hindleg muscle whole mounts for biomedical and basic research. INTRODUCTION Vertebrate NMJs are the synapses between cholinergic motor neurons and skeletal muscle fibers that mediate voluntary muscle contraction. They are embedded in a complex of many different cellular tissue components, with their pre-and postsynaptic apparatuses juxtaposed onto each other. Depending on the species, NMJs are about 10-50 m in diameter and come in varying forms, such as grape-, plaque-, or pretzel-shaped structures (Lu and Lichtman, 2007). The latter design is of particular interest as it is prevalent in rodent NMJs and is often used as an indicator for neuromuscular disorders or other disease states when fragmentation, simplification, growth, shrinkage, and other such deviations occur (Lyons and Slater, 1991;;;). In healthy adult mouse muscle, each syncytial fiber is roughly 50 m in diameter and up to 4 cm in length; it contains thousands of myonuclei and is precisely innervated by one NMJ. This is different during embryonic development and the perinatal stages, where most muscle fibers are contacted by more than one neuron (). This sort of polyinnervation is corrected within the first 2 to 3 postnatal weeks. Nevertheless, it can reappear during denervation-reinnervation cycles and other non-physiological conditions that frequently occur in genetic, acquired, and aging muscle diseases (). Previous and more recent studies increasingly suggest important feed forward and feedback mechanisms between the different cell types that mutually affect cell behavior (;;;;). So far, synoptic consideration of pathophysiological processes on the entire musculoskeletal organ has been severely hampered by two main factors. First, the mentioned mono-innervation of muscle fibers in combination with the extreme discrepancy between small NMJ size and large muscle fiber dimensions leads to an unequal distribution of these components in the organ; therefore, effects seen in one part of the muscle might not occur in others. Second, from a technical point of view, optical tissue clearing methods that would allow for such analysis of NMJs in their whole mount context have been lacking so far. Introduced by Chung et al., CLARITY (Clear Lipid-exchanged Acrylamide-hybridized Rigid Imaging/Immunostaining/in situ hybridization-compatible Tissue-hydrogel) is one of the many new tissue clearing methods available and has gained a great deal of attention due to its robustness and compatibility with many different stainings (Chung and Deisseroth, 2013;. This protocol and its variations (;;;;;;;) address Refractive Index (RI) heterogeneity by first embedding the tissue in an acrylamide/bis-acrylamide based hydrogel. In addition to increasing tissue stability and porosity, this stabilizes the RI across the tissue from the estimated n = 1.50 of dry tissue to n = 1.457. Lipids are then drawn out of the embedded samples via active clearing in an electrophoresis chamber that applies a current and a continual stream of SDS over the tissue. This process increases the homogeneity of the RI throughout the sample even further, since lipids tend to have varying RIs and can increase light scattering when imaging deep into tissue. Even though this is a very promising method, Milgroom et al found it was incompatible with -bungarotoxin (BGT) (Milgroom and Ralston, 2016), the most widely used postsynaptic NMJ marker, which labels nicotinic acetylcholine receptors (AChRs) with unmatched specificity. Their hypothesis was that the additional cross-linking and fixation prevented access of the toxin to the acetylcholine receptors (AChR). This incompatibility was further validated by Zhang et al., who found that even a modified passive CLARITY method resulted in the absence of BGT signals and appears to be very sensitive to standard optical clearing procedures. Another study did report the presence of BGT fluorescence signals with the use of in vivo injected BGT in combination with a modified organic-solvent clearing protocol based on 3DISCO (). Nonetheless, the combination of fluorophore compatibility/stability, tissue shrinkage, and the fact that in vivo injection of BGT hampers post-hoc stainings make this protocol and other organic solvent-based methods less than ideal for most applications. Here, we address many of these issues by introducing a new optical tissue clearing protocol that is based on aldehyde fixation and hydrogel embedding. This robust protocol enables transparency of samples with a thickness >700 m and is compatible with mouse diaphragm as well as EDL muscles. Additionally, it presents long-term fluorophore stability of NMJ staining in mouse skeletal muscle whole mounts. Animals and Sample Preparation In the current study, adult C57BL/10J, and BL10/JMDX mice were used. Animals were maintained in a local animal facility and their use and care were approved by German authorities according to EC directive 2010/63. For all experiments, adult mice were euthanized by cervical dislocation. Either whole hind limbs or just EDL muscles as well as diaphragm muscles were freshly dissected. Samples were then immediately immersed in 4% PFA/1x PBS and incubated for a minimum of 24 h on a roller mixer at 4 C. MYOCLEAR A detailed protocol including reagent and equipment lists, photos of custom-made devices, and troubleshooting can be found in the Supplementary Methods section. Briefly, muscles were either freshly dissected or taken from PFA fixed mouse muscles. However, we recommend dissecting muscles from PFA fixed specimens since this tends to drastically reduce accidental damage to the tissue. Then, 100 mg of VA-044 initiator (final concentration 0.25%) and 40 ml of freshly prepared hydrogel monomer solution (A4P0) were added to 50 ml light resistant Falcon tubes, briefly hand mixed, and kept on ice to prevent premature polymerization. One muscle was then placed in each falcon tube and incubated on a roller mixer for 5 days at 4 C. After, muscles were degassed for 1 h via a custom-built degassing apparatus which allowed nitrogen to bubble over the samples (see Supplementary Methods section for photograph). The caps of the Falcon tubes were then loosely placed back on and the tubes transferred to an air tight desiccator where they were vacuumed under a 90 kPa negative pressure for an additional hour in order to purge any remaining oxygen from the sample. The desiccator was then flushed with nitrogen, Falcon tube caps tightened, and placed in a hot water bath at 37 C for 4 h with shaking for polymerization. Samples were then removed from the Falcon tube and excess hydrogel removed by washing samples with 1x PTwH overnight on a roller mixer at room temperature. It is important to note that in lieu of using a desiccator and hot water bath, we found that using Life Canvas's EasyGel system resulted in comparable results and made sample handling simpler and easier. However, the custom-built nitrogen bubbling apparatus was still needed to ensure uniform hydrogel polymerization. For NMJ plus nuclei labeling, samples were stained as follows, inspired by the iDISCO staining protocol (): Samples were washed in 1x PTwH with solution changes every hour for 2 h. After washing, samples were incubated in blocking and permeabilization solution (BnP) with shaking at 37 C for 48 h. Then, the BnP solution was replaced with 1 ml of fresh BnP solution, the dyes added , and allowed to incubate for 5 days at 37 C with shaking. After, samples were thoroughly washed in 1x PTwH with solution changes every 10 min, 15 min, 30 min, 1 h, and then every 2 h for a minimum of 2 days. The detergent was then removed by washing samples in distilled water for 4-8 h with frequent solution changes. Lastly, samples were incubated in 88% glycerol at room temperature for a minimum of 24 h for RI matching and long-term storage. Additionally, it was found that samples were stable for many months when stored in this manner. For indirect immunofluorescence staining, samples were processed as described above, with modifications as detailed in the Supplementary Methods. A list of primary and secondary antibodies and their dilutions can also be found there. X-CLARITY For all samples stained after active clearing, a Biozym X-CLARITY protocol was followed, excluding the perfusion step. This is available for download from their website, https://www. biozym.com/. Briefly, EDL muscles were dissected from PFA fixed hind limbs and washed for 3 h in PBS at 4 C. Samples were then transferred to 50 ml light resistant falcon tubes containing 40 ml of freshly prepared 4% PFA/A4P0 monomer solution and 100 mg of VA-044 initiator, followed by a 5-day incubation on a roller mixer at 4 C. Then, samples were degassed via partial vacuum for 1 h, flushed with nitrogen, and incubated at 37 C for 3 h in a hot water bath to induce polymerization. Afterwards, samples were washed for 1-2 h in 1x PBS on a roller mixer at RT to remove excess hydrogel, transferred to an X-Clarity brain slice tissue holder, and lowered into the X-Clarity ETC chamber, where they were cleared for 3 h with 4% SDS buffer at a flow rate of 30 rpm; temperature: 37 C; current: 1.5 A. After, samples were thoroughly washed in PBST at 37 C for 24 h, then stored at 4 C in 1x PBS. For staining, samples were processed following the immunostaining section described in the Biozym protocol, with a dilution factor of 1:200 and 1:500 for BGT-AF647 and Wheat Germ Agglutinin CF488 conjugate (WGA-488; Biotium), respectively. Lastly, prepared samples were kept in 88% glycerol for storage and imaging. Active and Passive CLARITY EDL muscles were processed following the MYOCLEAR protocol described above, followed by either active or passive clearing for 24 h in the X-CLARITY ETC tissue clearing system. Here, a steady flow of 4% SDS at a rate of 30 rpm was applied to the samples and the current either left off for passive clearing or adjusted according to the experiment for active clearing, with the maximum temperature recorded at the end of each run, see Supplementary Methods section. For experiments that addressed the effect refixation would have on preserving BGT fluorescence, samples were stained, incubated in 4% PFA for 24 h at 4 C, and then cleared. Lastly, all samples were stored and mounted in 88% Glycerol for imaging and kept at room temperature. Microscopy Single stack acquisitions were imaged using a Leica Microsystems TCS SP2 equipped with a Leica Microsystems HC PL AP0 20x/0.75 IMM CORE CS2 objective, Leica confocal software version 2.61, a KrAr laser (488 nm, 514 nm), a diode-pumped laser (561 nm), and a HeNe laser (633 nm). For tile scans, an upright Leica Microsystems TCS SP8 equipped with LAS X software, a 488 nm laser, a 561 nm laser, a 633 nm laser, and Leica Microsystems clarity objective HC FLUOTAR L 25x/1.00 IMM (ne = 1.457) was used. 3D imaging of whole mount muscle samples was performed in 88% glycerol immersion using 6cm round plastic dishes. Muscles were fixed by surgical thread knotted around the distal and proximal tendons. Visualization worked best after at least 24 h of temperature adjustment of the sample in the microscope room. During this period, the sample was kept in the dark. Fiber Number and Image Analysis, Figure Preparation, and Statistics Transversal EDL cryo-sections (15-m thick) from C57BL/10J mice were stained with WGA-488 (1:1,000 dilution in 2% BSA/PBS) for 15 min at RT to outline muscle fibers. After washing and embedding in Mowiol, sections were imaged with an inverted Leica SP8 microscope. After acquisition, all images were electronically processed using either Leica Microsystems LAS X core or ImageJ software. Signal-to-Noise-Ratio (SNR) measurements were done in ImageJ. Here, NMJs were segmented and mean intensities of the NMJs and standard deviation (SD) of adjacent fiber background regions were measured. The ratio of NMJ intensities vs. background SD was determined as SNR for each synapse. Numbers displayed in the text indicate the average of several SNR values per sample. For quantitative analysis of NMJ and fiber numbers, position of all observed NMJs / fibers was completed using the multi-point tool of ImageJ. This determined the xyz-position of the center of each NMJ / fiber. For analysis of critical morphological parameters of NMJs according to Jones et al., five square ROIs, each 500 500 m, were selected per muscle. Then, all en face NMJs per ROI were manually thresholded and segmented using the magic wand tool in ImageJ. Then, area, perimeter and bounding rectangle diagonal were measured for every segmented NMJ. The number of AChR clusters per NMJs was counted manually. The diagonal of the bounding rectangle was calculated from the bounding rectangle sides while the fragmentation index was determined using the term: fragmentation index = 1-. Spectral un-mixing () used the ImageJ plugin SpectralUnmixing (https://imagej.nih.gov/ ij/plugins/spectral-unmixing.html). All figures were assembled using Adobe Illustrator. Mean values and standard deviations were calculated in Microsoft Excel. Normal distribution and homo/heteroscedasticity of data were probed using Kolmogorov-Smirnov test and F-test, respectively. According to these results and the type of data, statistical significance was evaluated using either one-way Analysis of Variance (ANOVA) with Tukey's posthoc test, unpaired two-tailed t-test, or Kruskal-Wallis test. Bar graphs are presented as mean ± SD. P-values were indicated as * (p < 0.05), * * (p ≤ 0.01), * * * (p ≤ 0.001), or * * * * (p ≤ 0.0001). P ≥ 0.05 was considered not significant. An SDS-Free Hydrogel-Based Clearing Protocol Retains NMJ Staining Previous attempts of optically clearing whole skeletal muscles using hydrogel-based, CLARITY-derived protocols yielded good tissue transparency but led to a quantitative loss of BGT fluorescence. To address possible reasons for this, we tested several variations of the procedure that was previously described by Milgroom and Ralston. Samples were PFA fixed, embedded in hydrogel, and then stained with BGT-AF647 for NMJ labeling. Once stained, muscles were thoroughly washed for a minimum of 2 days, incubated in 88% glycerol overnight, and imaged to check for BGT-AF647 fluorescence. Notably, BGT-AF647 fluorescence was observed in all hydrogel-embedded samples (Supplementary Figure 1A, left panels). After initial imaging, glycerol was removed from the samples by washing for 24 h in PTwH at RT and were then actively cleared using an X-CLARITY tissue clearing system. A variety of settings, including different electrophoresis strengths, the addition of PFA fixation after BGT-AF647 staining, as well as a passive CLARITY protocol using a constant flow of SDS with no current, were tested. These modifications resulted in a reduced SNR of NMJ labeling in the cleared tissue (Supplementary Figure 1A, see lower left angles in panels for SNR values); samples that were post-fixed with PFA before clearing were less affected. However, also these refixed samples exhibited a large decrease in fluorescence intensity of the BGT-AF647 staining and were still far from acceptable quality. Thus, supporting the findings of previous studies which state the incompatibility of CLARITY-based protocols with BGT-NMJ staining. The next step was to determine the effects of SDS on BGT staining: whether it washed out the membrane bound AChRs, simply quenched the fluorophore, or denatured the AChRs to the point BGT would not be able to bind. Samples were processed following the X-CLARITY protocol. Briefly, samples were PFA fixed, hydrogel embedded, actively cleared using an X-CLARITY machine, stained with either WGA-488 or BGT-AF647, and incubated in 88% glycerol for imaging. It was found here that staining the samples post-clearing with BGT-AF647 continued to result in an absence of NMJ signals, data not shown. However, NMJs in total were not destroyed by these techniques. Indeed, the lectin WGA could nicely identify the proteoglycan-rich ECM at the NMJs (Supplementary Figures 1B,C, see arrowheads in Supplementary Figure 1C for some examples of NMJs) besides other structures, such as blood vessels. Therefore, it might be assumed that SDS caused either quenching of the fluorophores or that it denatured the AChRs. The latter would, in turn, release BGT-AF647 from the AChR for samples stained before clearing and impede BGT-AF647 from binding altogether for samples stained post-clearing. With this in mind, SDS was excluded from all other experiments due to its role as a potential risk factor for the maintenance of BGT binding sites on NMJs. With the recent introduction of a new free-of-acrylamide SDS based tissue clearing protocol (), the necessity of the embedded hydrogel and its effect on tissue needed to be explored. In theory, the embedded hydrogel not only homogenizes the RI throughout the sample but also increases the porosity of it; resulting in better penetration and uniformity of staining (Chung and Deisseroth, 2013;. To test the effects of the hydrogel, samples were PFA fixed and either embedded in hydrogel, then stained with BGT-AF647 or vice versa. Both being compared in Figure 1, we found that staining samples after hydrogel embedding led to a better SNR (Figure 1G, Supplementary Figure 2) and increased the overall imaging depth of the sample (Figure 1G, Supplementary Figure 2). This confirmed the need of embedding samples with hydrogel and resulted in the final protocol termed MYOCLEAR. This method represents a passive hydrogel-based clearing method for the visualization of NMJs in fixed mouse muscles and is summarized in Figure 2. Muscle Fibers, Nuclei, and NMJs Can Be Visualized by Virtue of Green/Red Autofluorescence and Spectral Unmixing of Near-Infrared Fluorescence Signals Number and position of myonuclei can serve as relevant parameters in muscle research. Specifically, detection of centronucleated fibers in diseased and regenerating muscle or analyzing the presence of fundamental subsynaptic nuclei at NMJs would need determination of these parameters. Thus, we sought to use Draq5, a near-infrared nuclear dye, in combination with a red-fluorescent BGT-AlexaFluor555 conjugate on MYOCLEARtreated EDL muscles. As shown in red in Figures 3A,B, nuclei were well-stained and visible in the Draq5 channel. Conversely, NMJs, indicated by arrowheads in Figure 3B, were barely visible due to massive, PFA-induced autofluorescence (both shown in green). Consequently, this made the quality of these results inadequate for analysis. Furthermore, the intense level of autofluorescence was also observed in the 500-550 nm wavelength range when samples were stained with BGT-AlexaFluor488, data not shown. To mitigate the autofluorescence-induced limitation observed in short-wavelength fluorescence channels, we utilized two slightly spectrally separated near-infrared dyes, BGT-AF647 (maxima of excitation and emission, 650 and 665 nm, respectively) and Draq5 (maxima of excitation and emission, 646 and 681 nm, respectively). Muscles were PFA fixed, hydrogel embedded, co-stained with the dyes mentioned above, incubated in 88% glycerol, and then imaged using a 633 nm wavelength excitation laser for both. Each dye was acquired separately and FIGURE 1 | Sequence of staining and hydrogel embedding affects overall imaging depth and quality of muscle samples. All samples were imaged in 3D using a Leica SP8 confocal microscope and images were processed with Leica LAS X software. (A-C) Mouse EDL muscle was PFA-fixed, hydrogel embedded, stained with BGT-AF647, and then RI matched in 88% glycerol before imaging. (D-F) Mouse EDL was PFA-fixed, stained with BGT-AF647, hydrogel embedded, and then RI matched in 88% glycerol before imaging. (A,D) depict overviews of the whole mouse EDL muscles with the boxed region representing zooms shown in (B,E). (C,F) portray cross sections cropped from the center of the EDL imaging data and depth-coded on the z-axis in order to visualize imaging depth and quality for both methods. (G) Graphical display of NMJ-signal SNRs in correspondence to muscle tissue depth and staining / clearing order. Muscle tissue extension in the central muscle region is depicted in the background as reddish round shape. Mean SNR values are shown as horizontal bars with corresponding numbers next to it. Left and right halves correspond to muscles shown in (C,F), respectively. their emission detection windows adjusted to 643-679 nm and 685-778 nm for BGT-AF647 and Draq5, respectively. Figure 3C depicts a maximum-z projection of an EDL-whole mount scanned over a thickness of 1.2 mm. In addition, Figure 3D and Supplementary Video S1 show a zoom view of the boxed region and a rotation of the data projection, respectively. Nuclei and NMJs could be clearly distinguished. An additional spectral un-mixing step (see chapter Fiber number and image analysis, figure preparation, and statistics) was then added for more accurate segmentation results. Figures 3E,F show depth-coded side views of BGT-AF647 and Draq5, respectively, and reveal a good signal penetration for both over a depth range of about 1 mm. Figure 3F displays some elongated structures, which likely represent blood vessels traversing the muscle. To assess the compatibility of MYOCLEAR with muscle types other than EDL, we applied the protocol to adult mouse diaphragm. Confocal analysis revealed that the procedure was good to achieve complete penetration of diaphragm muscle in z (Figures 4A-D). Photographs next to processing days 0, 10, and 17 show the appearance of EDL muscles at the start of the clearing protocol, before staining, and upon RI matching, respectively. The insert in Figure 4A shows that NMJs were well-preserved in these samples. The apparent fragmentation in the large overview in Figure 4A is due to nuclei partially covering many synapses. Whole Mount Analysis Detects Local Heterogeneity of NMJ Fragmentation Index in mdx Muscle Wildtype skeletal muscle, as tested so far, is characterized by extremely homogeneous tissue composition. Conversely, diseased muscles might exhibit large amounts of fibrosis, fatty tissue, immune cell aggregates, or other changes that can affect the optical characteristics of muscle tissue and their transparency after clearing. Thus, we looked at muscles from wildtype and dystrophic mdx mice. The latter are characterized by extensive fibrosis () and fragmented NMJs (Lyons and Slater, 1991;). We found that applying MYOCLEAR to wildtype and mdx muscles resulted in data of comparable quality. As expected, NMJ structure was clearly different between the two; with wildtype NMJs displaying coherent pretzel-like structures and mdx NMJs demonstrating fragmented morphology. Next, whole mount imaging data was acquired for some wildtype and mdx mouse EDLs that were processed with MYOCLEAR and stained with BGT-AF647. The numbers of visible NMJs were then quantified by hand using the multi-point tool in ImageJ. Representative muscles are depicted in Figures 5A,B which illustrates the ability of this protocol to detect hundreds of NMJs. In quantitative terms, 1082.3 ± 29.5 and 1019.5 ± 14.8 (each mean ± SD) NMJs were counted in wildtype and mdx muscles, respectively. Figures 5A',B' show representative high-power images of a few NMJs from each of the corresponding muscles. These panels demonstrate the normal, pretzel-like structure of NMJs in wildtype (Figure 5A') as compared to the fragmented appearance in the mdx muscle (Figure 5B'). An important advantage of whole mounts should be that heterogeneity of objects or effects of treatments within the entire organ can be better observed than in individual tissue sections. To assess this point, key morphological parameters of NMJs from different ROIs of both, wildtype and mdx muscles were determined and compared. Therefore, a subset of criteria recently introduced by Jones et al. was applied (). In detail, area, fragmentation index, perimeter, and bounding rectangle diagonal of NMJs from five different ROIs (Figures 5C-F) per muscle were determined. NMJ areas, perimeters, and bounding rectangle diagonals were similar between all ROIs of a given muscle and also apparently not different between wildtype and mdx. Conversely, NMJ fragmentation index was higher in mdx than in wildtype and, furthermore, varied considerably within a given mdx muscle. VAChT Antibody Staining Confirms Integrity of NMJ Presynaptic Apparatus Upon MYOCLEAR BGT-AF647 and lectin staining data suggested that the NMJ ECM and postsynaptic apparatus remained intact during MYOCLEAR processing. To address presynaptic integrity and the amenability of the clearing protocol for immunofluorescence staining, we first processed EDL muscles with the MYOCLEAR protocol and then stained nuclei and the presynaptic NMJ marker protein vAChT using Draq5 and anti-vAChT antibody, respectively. As depicted in Figure 6A, the obtained antibody staining was concentrated in the NMJ regions, although considerable noisy signals were also observed outside the synaptic regions. Yet, NMJ presynapses showed normal coherent appearance, demonstrating that the clearing procedure did not affect this part either. The general integrity of the major muscle compartment was also confirmed by immunostaining with a FIGURE 3 | MYOCLEAR enables imaging of muscle fibers, myonuclei, and NMJs by using red autofluorescence and spectral unmixing of far-red wavelengths dyes. (A,B) Mouse EDL was processed via the MYOCLEAR protocol and stained with BGT-AF555 and Draq5. (A) depicts a confocal section of the EDL, with (B) representing a zoom of the boxed region. Strong autofluorescence of the tissue in the AF555 channel (green) resulted in a poor SNR for NMJ detection (some NMJs are highlighted in B, arrowheads). In contrast, the near-infrared dye Draq5 displayed crisp and clear nuclei. (C-F) Mouse EDL muscle was processed via the MYOCLEAR protocol and stained with BGT-AF647 and Draq5. In order to overcome the auto-fluorescence shown in this figure, the emission windows for each dye were adjusted according to their peak values and acquired separately using the same 633-nm excitation laser on a SP8 confocal microscope. The images were processed using Leica LAS X software and spectrally un-mixed in ImageJ. (C) Maximum-z projection of the whole EDL before applying spectral un-mixing. Draq5, red; BGT-AF647, green. Green autofluorescence of the thread keeping the muscle in place for imaging is visible at the proximal and distal ends of the muscle. few additional antibodies. Nicely, dystrophin outlined muscle fibers and was also enriched in the NMJ regions as expected ( Figure 6B). Further labeling with collagen I antibody showed the distribution of large blood vessels, capillaries, and fascia cells ( Figure 6C). Finally, immunostaining of troponin I retrieved the regular pattern of sarcomeric striations (Figure 6D). DISCUSSION Although previous attempts of optically clearing whole skeletal muscles using hydrogel-based, CLARITY-derived protocols yielded sufficient muscle tissue transparency, they led to a quantitative loss of BGT fluorescence. This was true for both, active (Milgroom and Ralston, 2016) and passive CLARITY protocols. The interpretation in these studies was that hydrogel cross-linking coupled with PFA fixation prevented access of the toxin to AChRs. Conversely, we present a hydrogel and PFA based skeletal muscle clearing protocol that nicely retains BGT-based NMJ staining and exhibits a good light penetration of approximately 1,000 m in mouse EDL muscle. This suggests, that SDS rather than hydrogel or PFA led to the loss of BGT staining. For simplicity, this method was termed MYOCLEAR. It allows for the analysis of whole mount NMJ FIGURE 4 | MYOCLEAR is functional with adult mouse diaphragm muscle. Adult mouse diaphragm muscles were processed using the MYOCLEAR protocol and stained with Draq5 and BGT-AF647. (A) Maximum-z projection of a representative tile stack showing fluorescence signals of BGT and Draq5 in green and red, respectively. Note, that NMJs are not fragmented but partially covered by myonuclei. This is evident in the insert, which shows only BGT signals of a small region. counts in correlation to myonuclei analysis and is also compatible with diaphragm, as well as with other dyes, including lectins and antibodies. Given that the protocol is based on an initial PFA fixation step, it should be compatible with easy handling and material exchange. Permutation of the protocol settings revealed that staining and image quality were superior if BGT labeling occurred after PFA fixation and hydrogel embedding. Since both methods (i.e., staining before or after hydrogel embedding) received ample washing steps, it is safe to assume the hydrogel either supports BGT-AF647 in a way that it can reach its target more accurately or aids in washing out unspecific BGT-AF647 signals. The present protocol presents strong autofluorescence in the blue to red fluorescence wavelength range, which is most likely due to PFAfixation induced chromophore formation (). In the near infrared range, though, the autofluorescence issue was not present and thus AlexaFluo647 and Draq5 dyes worked well. Although the autofluorescence obtained in the green and red fluorescence channels might be considered a limitation of the MYOCLEAR protocol, it can also be rather useful for tracking individual muscle fibers over their whole length. Additionally, it can be used to assess pathophysiologically relevant features, including centro-nucleated regions, fiber atrophy, fiber splitting, the occurrence of poly-innervation, and other general structural information. Given that most standard available fluorescence microscopy systems exhibit excitation lasers typically up to 633 nm wavelength, the use of near infrared dyes compatible with MYOCLEAR is somewhat limited. To permit at least two different structures to be simultaneously marked, we used the slightly wavelength-shifted dyes AlexaFluor647 and Draq5 in combination with spectral unmixing (). Using hand segmentation of BGT-AF647 stained and cleared EDL wholemounts, slightly more than one thousand NMJs were identified in each muscle. According to literature, the amount of muscle fibers in an adult mouse EDL ranges from 758 to 1,147 (;Bloemberg and Quadrilatero, 2012). To confirm this, we performed fiber counts from our own FIGURE 6 | Integrity of NMJ presynapse and other muscle structures is maintained upon clearing. Adult mouse EDL muscles were processed using the MYOCLEAR protocol and co-stained with Draq5 and antibodies against either NMJ presynapse (A, vAChT), sarcolemma (B, dystrophin), ECM (C, collagen I), or sarcomere (D, troponin I). Images show maximum-z projections of confocal z-stacks with an interplane interval of 2 m and depths from muscle surface of 466, 665, 104, and 214 m for (A-D), respectively. animals by analyzing cross sections of contralateral muscles. This revealed fiber numbers of 1,052 ± 42 (mean ± SD) per EDL muscle. Thus, taking into account that each muscle fiber in adult muscle is innervated by one single NMJ, this finding supports that the total number of NMJs obtained in our cleared muscles represents most, if not all, of the NMJs in the tissue. However, it must be stated that NMJs beyond a depth of about 700 to 800 m from the surface were hardly above background and would render automated segmentation, volumetric, or in-depth morphological analyses of these synapses impossible. If such information is needed, it would be necessary to image muscles from both sides and eliminate the overlapping NMJs. MYOCLEAR was found to retain morphological integrity of presynapse, synaptic cleft, and postsynapse. In many experimental paradigms, considerable regional heterogeneity of critical morphological parameters of the neuromuscular apparatus might be expected, such as for NMJ degeneration/regeneration in dystrophic mouse models (), terminal sprouting upon neurotoxin application (;), or in aging muscle (). Therefore, a more holistic picture of observed changes in the whole mount might yield relevant new insights. For wildtype and mdx EDL muscles, we addressed the principal applicability of our samples to study a subset of morphological criteria as recently proposed by Jones et al.. This revealed differences with respect to the amplitude and regional heterogeneity of NMJ fragmentation index between wildtype and mdx, suggesting that whole mount analysis might serve as a valuable tool for future investigations of neuromuscular disorders. Certainly, immunofluorescence procedures will be a relevant asset to perform more in-depth analyses in this context. Thus, it was evaluated, whether the present clearing protocol is compatible with antibody staining. Indeed, immunostaining with all tested antibodies against presynapse (vAChT), sarcomere (troponin I), sarcolemma (dystrophin), and extracellular matrix (collagen I) yielded the expected staining patterns, although depth penetration still needs to be optimized. Apart from vAChT, which was visible beyond 500 m deep in the tissue, the other markers were visible only for about 200-300 m of depth. It will be necessary to examine if additional techniques for dye distribution, such as stochastic electrotransport or similar procedures (;) might solve the issue of penetration. Also, the limitation of MYOCLEAR to near-infrared dyes requests evaluation of further dye combinations that would be compatible with AF647 and Draq5. We tested secondary antibodies coupled to PE-Cy7, but were not successful due to low secondary antibody specificity. In summary, future work will have to deal with skeletal muscle clearing protocols that are compatible with a wider spectral range to incorporate more than just two dyes in one sample as well as with reaching a higher depth penetration of antibodies. Furthermore, besides improving the MYOCLEAR protocol, an automated quantitative determination of NMJ numbers and characteristics, such as size and fragmentation, would likely be a major analytical request for cleared muscles. We have started to work on such automated detection algorithms, but they need further improvement before being valid. Though, Supplementary Video S2 shows a future prospect of advantages of such an approach. It depicts a 3D view of all NMJs detected in the muscle sample shown in Figure 5C. Yellow-coded NMJs were detected by auto segmentation, blue NMJs were detected by hand. It is evident that three-dimensional information gives a much more plastic view on the synapse band in this muscle. ETHICS STATEMENT This study was carried out in accordance with the recommendations of EC directive 2010/63. The protocol was approved by the Regierungsprsidium Karlsruhe. |
/// Dispatch virtual interrupts, if enabled
///
/// For each interrupt in the queue:
///
/// - Halt the hosted kmain thread (kmain hooks will park the thread)
/// - Call the [`HostedInterrupt::dispatch`] method for the interrupt
/// - Unhalt the hosted kmain thread
/// - Manually unpark the hosted kmain thread
///
/// This function should be spawned in a new thread immediately after spawning
/// the thread running [`hosted_kmain`][crate::host::hosted_kmain].
pub fn dispatcher(kmain_thread: Thread) {
while !SYSTEM.return_next_iter {
thread::sleep(Duration::from_millis(20));
if !SYSTEM.interrupts_enabled {
continue;
}
while let Some(interrupt) = SYSTEM.get().pending_interrupts.pop() {
trace!("dispatching {:?}", interrupt);
// Halt the CPU, which will park the thread at the next opportunity
SYSTEM.get().halted = true;
// Dispatch the interrupt
interrupt.dispatch();
// Unhalt the CPU and manually unpark the thread
SYSTEM.get().halted = false;
kmain_thread.unpark();
}
}
} |
. The study on the effect of mytilan on the local suppurative processes caused by administration of a virulent staphylococcal culture to the mouse pad showed that this polysaccharide isolated from Crenomytilus grayanus had a pronounced antiexudative and antinecrotic effect. The positive results of the experiments may be explained by stimulation of the phagocytic activity of polymorphonuclear leukocytes and macrophages by mytilan which results in acceleration of the reparative processes in local staphylococcal infection. Hence, nonspecific stimulation of the defense mechanisms in local suppurative infection by mytilan and its antiexudative and antinecrotic effect are promising for investigation of the possibility of the mytilan clinical use. |
//
// VidLoader.h
// VidLoader
//
// Created by Petre on 20.11.19.
// Copyright © 2019 Petre. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for VidLoader.
FOUNDATION_EXPORT double VidLoaderVersionNumber;
//! Project version string for VidLoader.
FOUNDATION_EXPORT const unsigned char VidLoaderVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <VidLoader/PublicHeader.h>
|
/**
* Base implementation of Event that contains the common functionality.
*/
public abstract class BaseEventImpl implements Event, DebugDumpable, ShortDumpable {
private static final Trace LOGGER = TraceManager.getTrace(BaseEventImpl.class);
@NotNull private final LightweightIdentifier id;
private SimpleObjectRef requester;
private SimpleObjectRef requestee;
/**
* If needed, we can prescribe the handler that should process this event, in addition to the handlers
* defined by the system configuration.
*
* It is recommended only for specific (ad-hoc) situations.
* A better is to define handlers in system configuration.
*/
private final EventHandlerType adHocHandler;
private transient MidpointFunctions midpointFunctions;
private transient TextFormatter textFormatter;
private transient PrismContext prismContext;
private String channel;
BaseEventImpl() {
this(ApplicationContextHolder.getBean(LightweightIdentifierGenerator.class));
}
BaseEventImpl(@NotNull LightweightIdentifierGenerator lightweightIdentifierGenerator) {
this(lightweightIdentifierGenerator, null);
}
BaseEventImpl(@NotNull LightweightIdentifierGenerator lightweightIdentifierGenerator, EventHandlerType adHocHandler) {
id = lightweightIdentifierGenerator.generate();
this.adHocHandler = adHocHandler;
}
@NotNull
public LightweightIdentifier getId() {
return id;
}
boolean changeTypeMatchesOperationType(ChangeType changeType, EventOperationType eventOperationType) {
switch (eventOperationType) {
case ADD:
return changeType == ChangeType.ADD;
case MODIFY:
return changeType == ChangeType.MODIFY;
case DELETE:
return changeType == ChangeType.DELETE;
default:
throw new IllegalStateException("Unexpected EventOperationType: " + eventOperationType);
}
}
abstract public boolean isCategoryType(EventCategoryType eventCategory);
public boolean isUserRelated() {
return false; // overridden in ModelEvent
}
public SimpleObjectRef getRequester() {
return requester;
}
// TODO make requester final and remove this method
public void setRequester(SimpleObjectRef requester) {
this.requester = requester;
}
public SimpleObjectRef getRequestee() {
return requestee;
}
// TODO we need the operation result parent here
@Nullable
private ObjectType resolveObject(SimpleObjectRef ref) {
if (ref == null) {
return null;
}
return ref.resolveObjectType(new OperationResult(BaseEventImpl.class + ".resolveObject"), true);
}
@Override
public ObjectType getRequesteeObject() {
return resolveObject(requestee);
}
@SuppressWarnings("WeakerAccess")
public ObjectType getRequesterObject() {
return resolveObject(requester);
}
@Override
public PolyStringType getRequesteeDisplayName() {
return getDisplayName(getRequesteeObject());
}
@SuppressWarnings("unused")
public PolyStringType getRequesterDisplayName() {
return getDisplayName(getRequesterObject());
}
@Nullable
private PolyStringType getDisplayName(ObjectType object) {
if (object == null) {
return null;
}
if (object instanceof UserType) {
return ((UserType) object).getFullName();
} else if (object instanceof AbstractRoleType) {
return ((AbstractRoleType) object).getDisplayName();
} else {
return object.getName();
}
}
@Nullable
private PolyStringType getName(ObjectType object) {
return object != null ? object.getName() : null;
}
@SuppressWarnings("unused")
public PolyStringType getRequesteeName() {
return getName(getRequesteeObject());
}
@SuppressWarnings("unused")
public PolyStringType getRequesterName() {
return getName(getRequesterObject());
}
public void setRequestee(SimpleObjectRef requestee) {
this.requestee = requestee;
}
public void createVariablesMap(VariablesMap variables, OperationResult result) {
variables.put(ExpressionConstants.VAR_EVENT, this, Event.class);
variables.put(ExpressionConstants.VAR_REQUESTER, resolveTypedObject(requester, false, result));
variables.put(ExpressionConstants.VAR_REQUESTEE, resolveTypedObject(requestee, true, result));
}
TypedValue<ObjectType> resolveTypedObject(SimpleObjectRef ref, boolean allowNotFound, OperationResult result) {
ObjectType resolved = ref != null ? ref.resolveObjectType(result, allowNotFound) : null;
if (resolved != null) {
return new TypedValue<>(resolved, resolved.asPrismObject().getDefinition());
} else {
PrismObjectDefinition<ObjectType> def = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ObjectType.class);
return new TypedValue<>(null, def);
}
}
// Finding items in deltas/objects
// this is similar to delta.hasItemDelta but much, much more relaxed (we completely ignore ID path segments and we take sub-paths into account)
//
// Very experimental implementation. Needs a bit of time to clean up and test adequately.
@SuppressWarnings("WeakerAccess")
public boolean containsItem(ObjectDelta<?> delta, ItemPath itemPath) {
if (delta.getChangeType() == ChangeType.ADD) {
return containsItem(delta.getObjectToAdd(), itemPath);
} else //noinspection SimplifiableIfStatement
if (delta.getChangeType() == ChangeType.MODIFY) {
return containsItemInModifications(delta.getModifications(), itemPath);
} else {
return false;
}
}
private boolean containsItemInModifications(Collection<? extends ItemDelta<?, ?>> modifications, ItemPath itemPath) {
for (ItemDelta<?, ?> itemDelta : modifications) {
if (containsItem(itemDelta, itemPath)) {
return true;
}
}
return false;
}
private boolean containsItem(ItemDelta<?, ?> itemDelta, ItemPath itemPath) {
ItemPath namesOnlyPathTested = itemPath.namedSegmentsOnly();
ItemPath namesOnlyPathInDelta = itemDelta.getPath().namedSegmentsOnly();
if (namesOnlyPathTested.isSubPathOrEquivalent(namesOnlyPathInDelta)) {
return true;
}
// however, we can add/delete whole container (containing part of the path)
// e.g. we can test for activation/administrativeStatus, and the delta is:
// ADD activation VALUE (administrativeStatus=ENABLED)
if (!namesOnlyPathInDelta.isSubPath(namesOnlyPathTested)) {
return false;
}
// for ADD values we know
// for REPLACE values we know - for values being added, but NOT for values being left behind
// for DELETE we have a problem if we are deleting "by ID" - we just don't know if the value being deleted contains the path in question or not
ItemPath remainder = namesOnlyPathTested.remainder(namesOnlyPathInDelta);
return containsItemInValues(itemDelta.getValuesToAdd(), remainder) ||
containsItemInValues(itemDelta.getValuesToReplace(), remainder) ||
containsItemInValues(itemDelta.getValuesToDelete(), remainder);
}
// remainder contains only named segments and is not empty
private boolean containsItemInValues(Collection<?> values, ItemPath remainder) {
if (values == null) {
return false;
}
for (Object value : values) {
if (value instanceof PrismContainerValue) { // we do not want to look inside references nor primitive values
if (containsItem((PrismContainerValue<?>) value, remainder)) {
return true;
}
}
}
return false;
}
boolean containsItem(List<ObjectDelta<AssignmentHolderType>> deltas, ItemPath itemPath) {
for (ObjectDelta<?> objectDelta : deltas) {
if (containsItem(objectDelta, itemPath)) {
return true;
}
}
return false;
}
// itemPath is empty or starts with named item path segment
private boolean containsItem(PrismContainer<?> container, ItemPath itemPath) {
if (container.size() == 0) {
return false; // there is a container, but no values
}
if (itemPath.isEmpty()) {
return true;
}
for (PrismContainerValue<?> o : container.getValues()) {
if (containsItem(o, itemPath)) {
return true;
}
}
return false;
}
// path starts with named item path segment
private boolean containsItem(PrismContainerValue<?> prismContainerValue, ItemPath itemPath) {
ItemName first = ItemPath.toName(itemPath.first());
Item<?, ?> item = prismContainerValue.findItem(first);
if (item == null) {
return false;
}
ItemPath pathTail = stripFirstIds(itemPath);
if (item instanceof PrismContainer) {
return containsItem((PrismContainer<?>) item, pathTail);
} else if (item instanceof PrismReference) {
return pathTail.isEmpty(); // we do not want to look inside references
} else //noinspection SimplifiableIfStatement
if (item instanceof PrismProperty) {
return pathTail.isEmpty(); // ...neither inside atomic values
} else {
return false; // should not occur anyway
}
}
private ItemPath stripFirstIds(ItemPath itemPath) {
while (!itemPath.isEmpty() && itemPath.startsWithId()) {
itemPath = itemPath.rest();
}
return itemPath;
}
@Override
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
@Override
public String getStatusAsText() {
if (isSuccess()) {
return "SUCCESS";
} else if (isOnlyFailure()) {
return "FAILURE";
} else if (isFailure()) {
return "PARTIAL FAILURE";
} else if (isInProgress()) {
return "IN PROGRESS";
} else {
return "UNKNOWN";
}
}
@Override
public EventHandlerType getAdHocHandler() {
return adHocHandler;
}
protected void debugDumpCommon(StringBuilder sb, int indent) {
DebugUtil.debugDumpWithLabelToStringLn(sb, "id", getId(), indent + 1);
DebugUtil.debugDumpWithLabelLn(sb, "requester", getRequester(), indent + 1);
DebugUtil.debugDumpWithLabelLn(sb, "requestee", getRequestee(), indent + 1);
}
@Override
public void shortDump(StringBuilder sb) {
sb.append(this.getClass().getSimpleName()).append("(").append(getId()).append(")");
}
MidpointFunctions getMidpointFunctions() {
if (midpointFunctions == null) {
midpointFunctions = ApplicationContextHolder.getBean(MidpointFunctions.class);
}
return midpointFunctions;
}
private ModelService getModelService() {
return ApplicationContextHolder.getBean(ModelService.class);
}
PrismContext getPrismContext() {
if (prismContext == null) {
prismContext = ApplicationContextHolder.getBean(PrismContext.class);
}
return prismContext;
}
TextFormatter getTextFormatter() {
if (textFormatter == null) {
textFormatter = ApplicationContextHolder.getBean(TextFormatter.class);
}
return textFormatter;
}
/**
* As {@link MidpointFunctions#resolveReferenceIfExists(ObjectReferenceType)} but a bit more intelligent
* (e.g. it stores resolved object right in the reference).
*/
@Nullable ObjectType resolveReferenceIfExists(@Nullable ObjectReferenceType reference) {
if (reference == null) {
return null;
}
if (reference.getObject() != null) {
return (ObjectType) reference.getObject().asObjectable();
}
QName type = reference.getType(); // TODO what about implicitly specified types, like in resourceRef?
PrismObjectDefinition<ObjectType> objectDefinition =
PrismContext.get().getSchemaRegistry().findObjectDefinitionByType(reference.getType());
try {
if (objectDefinition == null) {
throw new SchemaException("No definition for type " + type);
}
Collection<SelectorOptions<GetOperationOptions>> options = SchemaService.get().getOperationOptionsBuilder()
.executionPhase()
.allowNotFound(true)
.build();
PrismObject<ObjectType> object = getModelService().getObject(
objectDefinition.getCompileTimeClass(),
reference.getOid(),
options,
getCurrentTask(),
getCurrentResult());
if (!reference.asReferenceValue().isImmutable()) {
reference.asReferenceValue().setObject(object);
}
return object.asObjectable();
} catch (ObjectNotFoundException e) {
LoggingUtils.logException(LOGGER, "Couldn't resolve object from reference: {}", e, reference);
return null;
} catch (Exception e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't resolve object from reference: {}", e, reference);
return null;
}
}
@Nullable PolyStringType getNameFromReference(@Nullable ObjectReferenceType reference) {
if (reference == null) {
return null;
} else if (reference.getTargetName() != null) {
return reference.getTargetName();
} else if (reference.getObject() != null) {
return reference.getObject().asObjectable().getName();
} else {
ObjectType resolved = resolveReferenceIfExists(reference);
if (resolved != null) {
return resolved.getName();
} else {
return PolyStringType.fromOrig(
reference.getOid()); // At least something
}
}
}
protected @Nullable PolyStringType getDisplayNameFromReference(@Nullable ObjectReferenceType reference) {
if (reference == null) {
return null;
} else if (reference.getObject() != null) {
return getDisplayName((ObjectType) reference.getObject().asObjectable());
} else {
ObjectType resolved = resolveReferenceIfExists(reference);
if (resolved != null) {
return getDisplayName(resolved);
} else {
return PolyStringType.fromOrig(
reference.getOid()); // At least something
}
}
}
private Task getCurrentTask() {
return getMidpointFunctions().getCurrentTask();
}
private OperationResult getCurrentResult() {
return getMidpointFunctions().getCurrentResult();
}
public void setRequesterAndRequesteeAsTaskOwner(@NotNull Task task, @NotNull OperationResult result) {
PrismObject<? extends FocusType> ownerObject = task.getOwner(result);
if (ownerObject != null) {
FocusType owner = ownerObject.asObjectable();
setRequester(new SimpleObjectRefImpl(owner));
setRequestee(new SimpleObjectRefImpl(owner));
} else {
LOGGER.debug("No owner for {}, therefore no requester and requestee will be set for event {}", task, getId());
}
}
@Override
public String toString() {
return toStringPrefix() + '}';
}
/**
* Prefix for {@link #toString()} after which other attributes can be added; final `}` needs be added too.
* Useful for event subclasses.
*/
@NotNull
protected String toStringPrefix() {
return getClass().getSimpleName() + "{" +
"id=" + id +
",requester=" + requester +
",requestee=" + requestee;
}
} |
<reponame>ghsecuritylab/bcwifi
/*
* This file Copyright (C) Mnemosyne LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* $Id: utils.h 13448 2012-08-19 16:12:20Z jordan $
*/
#ifndef QTR_UTILS
#define QTR_UTILS
#include <QString>
#include <QObject>
#include <QIcon>
#include <cctype> // isxdigit()
#include "speed.h"
class Utils: public QObject
{
Q_OBJECT
public:
Utils( ) { }
virtual ~Utils( ) { }
public:
static QString remoteFileChooser( QWidget * parent, const QString& title, const QString& myPath, bool dir, bool local );
static const QIcon& guessMimeIcon( const QString& filename );
// Test if string is UTF-8 or not
static bool isValidUtf8 ( const char *s );
// meh
static void toStderr( const QString& qstr );
///
/// URLs
///
static bool isMagnetLink( const QString& s ) { return s.startsWith( QString::fromAscii( "magnet:?" ) ); }
static bool isHexHashcode( const QString& s )
{
if( s.length() != 40 ) return false;
foreach( QChar ch, s ) if( !isxdigit( ch.toAscii() ) ) return false;
return true;
}
static bool isUriWithSupportedScheme( const QString& s )
{
static const QString ftp = QString::fromAscii( "ftp://" );
static const QString http = QString::fromAscii( "http://" );
static const QString https = QString::fromAscii( "https://" );
return s.startsWith(http) || s.startsWith(https) || s.startsWith(ftp);
}
};
#endif
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from ...v5_0.core.models import *
from .core_client import CoreClient
__all__ = [
'GraphSubjectBase',
'IdentityData',
'IdentityRef',
'JsonPatchOperation',
'OperationReference',
'Process',
'ProcessReference',
'ProjectInfo',
'ProjectProperty',
'Proxy',
'ProxyAuthorization',
'PublicKey',
'ReferenceLinks',
'TeamMember',
'TeamProject',
'TeamProjectCollection',
'TeamProjectCollectionReference',
'TeamProjectReference',
'WebApiConnectedService',
'WebApiConnectedServiceDetails',
'WebApiConnectedServiceRef',
'WebApiTeam',
'WebApiTeamRef',
'CoreClient'
]
|
/**
* Created by muhammadsaadshamim on 8/4/15.
*/
public class MainMenuBar extends JMenuBar {
private static final long serialVersionUID = 2342324643L;
private static final int recentMapListMaxItems = 10;
private static final int recentLocationMaxItems = 20;
private static final String recentMapEntityNode = "hicMapRecent";
private static final String recentLocationEntityNode = "hicLocationRecent";
private static final String recentStateEntityNode = "hicStateRecent";
//private static JMenuItem loadOldAnnotationsMI;
private static RecentMenu recentMapMenu, recentControlMapMenu;
private static RecentMenu recentLocationMenu;
private static JMenuItem saveLocationList;
private static JMenuItem saveStateForReload;
private static RecentMenu previousStates;
private static JMenuItem exportSavedStateMenuItem;
private static JMenuItem importMapAsFile;
private static JMenuItem slideShow;
private static JMenuItem showStats, showControlStats;
//private static JMenu annotationsMenu;
private static JMenu viewMenu;
private static JMenu assemblyMenu;
private static JMenuItem exportAssembly;
private static JMenuItem resetAssembly;
private static JMenuItem exitAssembly;
private static JCheckBoxMenuItem enableAssembly;
private static JMenuItem setScale;
private static JMenuItem importModifiedAssembly;
private final JCheckBoxMenuItem layersItem = new JCheckBoxMenuItem("Show Annotation Panel");
// created separately because it will be enabled after an initial map is loaded
private final JMenuItem loadControlFromList = new JMenuItem();
public MainMenuBar(SuperAdapter superAdapter) {
createMenuBar(superAdapter);
}
public static void exitAssemblyMode() {
resetAssembly.setEnabled(false);
exportAssembly.setEnabled(false);
// setScale.setEnabled(false);
importModifiedAssembly.setEnabled(false);
exitAssembly.setEnabled(false);
}
public boolean unsavedEditsExist() {
File unsavedSampleFile = new File(DirectoryManager.getHiCDirectory(), HiCGlobals.BACKUP_FILE_STEM + "0.bedpe");
return unsavedSampleFile.exists();
}
public void addRecentMapMenuEntry(String title, boolean status) {
recentMapMenu.addEntry(title, status);
recentControlMapMenu.addEntry(title, status);
}
private void addRecentStateMenuEntry(String title, boolean status) {
recentLocationMenu.addEntry(title, status);
}
private void createMenuBar(final SuperAdapter superAdapter) {
//======== fileMenu ========
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenuItem newWindow = new JMenuItem("New Window");
newWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProcessHelper p = new ProcessHelper();
try {
p.startNewJavaProcess();
} catch (IOException error) {
superAdapter.launchGenericMessageDialog(error.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
fileMenu.add(newWindow);
//---- openMenuItem ----
// create control first because it is enabled by regular open
loadControlFromList.setText("Open as Control...");
loadControlFromList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.loadFromListActionPerformed(true);
}
});
loadControlFromList.setEnabled(false);
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.loadFromListActionPerformed(false);
}
});
fileMenu.add(openItem);
fileMenu.add(loadControlFromList);
recentMapMenu = new RecentMenu("Open Recent", recentMapListMaxItems, recentMapEntityNode, HiCGlobals.menuType.MAP) {
private static final long serialVersionUID = 4202L;
public void onSelectPosition(String mapPath) {
String delimiter = "@@";
String[] temp;
temp = mapPath.split(delimiter);
// initProperties(); // don't know why we're doing this here
superAdapter.loadFromRecentActionPerformed((temp[1]), (temp[0]), false);
}
};
recentMapMenu.setMnemonic('R');
fileMenu.add(recentMapMenu);
recentControlMapMenu = new RecentMenu("Open Recent as Control", recentMapListMaxItems, recentMapEntityNode, HiCGlobals.menuType.MAP) {
private static final long serialVersionUID = 42012L;
public void onSelectPosition(String mapPath) {
String delimiter = "@@";
String[] temp;
temp = mapPath.split(delimiter);
//initProperties(); // don't know why we're doing this here
superAdapter.loadFromRecentActionPerformed((temp[1]), (temp[0]), true);
}
};
//recentControlMapMenu.setMnemonic('r');
recentControlMapMenu.setEnabled(false);
fileMenu.add(recentControlMapMenu);
fileMenu.addSeparator();
showStats = new JMenuItem("Show Dataset Metrics");
showStats.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
superAdapter.showDataSetMetrics(false);
}
});
showStats.setEnabled(false);
showControlStats = new JMenuItem("Show Control Dataset Metrics");
showControlStats.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
superAdapter.showDataSetMetrics(true);
}
});
showControlStats.setEnabled(false);
fileMenu.add(showStats);
fileMenu.add(showControlStats);
fileMenu.addSeparator();
// TODO: make this an export of the data on screen instead of a GUI for CLT
if (!HiCGlobals.isRestricted) {
JMenuItem dump = new JMenuItem("Export Data...");
dump.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
superAdapter.exportDataLauncher();
}
});
fileMenu.add(dump);
}
JMenuItem creditsMenu = new JMenuItem();
creditsMenu.setText("About");
creditsMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon(getClass().getResource("/images/juicebox.png"));
JLabel iconLabel = new JLabel(icon);
JPanel iconPanel = new JPanel(new GridBagLayout());
iconPanel.add(iconLabel);
JPanel textPanel = new JPanel(new GridLayout(0, 1));
textPanel.add(new JLabel("<html><center>" +
"<h3 style=\"margin-bottom:30px;\" class=\"header\">" +
"Juicebox: Visualization software for Hi-C data" +
"</h3>" +
"</center>" +
"<p>" +
"Juicebox is the Aiden Lab's software for visualizing data<br>" +
"from proximity ligation experiments, such as Hi-C.<br>" +
"Juicebox was created by Jim Robinson, Neva C. Durand,<br>" +
"and Erez Aiden. Ongoing development work is carried<br>" +
"out by " +
"Neva C. Durand, Muhammad S. Shamim, Ido <br>Machol, Zulkifl Gire, " +
"and Marie Hoeger.<br><br>" +
"Current version: " + HiCGlobals.versionNum + "<br>" +
"Copyright © 2014. Broad Institute and Aiden Lab" +
"<br><br>" +
"" +
"If you use Juicebox in your research, please cite:<br><br>" +
"" +
"<strong>Neva C. Durand*, James T. Robinson*, Muhammad S.<br>Shamim, " +
"Ido Machol, Jill P. Mesirov, Eric S. Lander, and<br>Erez Lieberman Aiden.<br>" +
" \"Juicebox provides a visualization system for Hi-C<br>contact maps " +
"with unlimited zoom.\" <em>Cell Systems</em><br>July 2016.</strong>" +
"<br><br>" +
"<strong>Suhas S.P. Rao*, Miriam H. Huntley*, Neva C. Durand, <br>" +
"Elena K. Stamenova, Ivan D. Bochkov, James T. Robinson,<br>" +
"Adrian L. Sanborn, Ido Machol, Arina D. Omer, Eric S.<br>Lander, " +
"Erez Lieberman Aiden. \"A 3D Map of the<br>Human Genome at Kilobase " +
"Resolution Reveals<br>Principles of Chromatin Looping.\" <em>Cell</em> 159, 2014.</strong><br>" +
"* contributed equally" +
"</p></html>"));
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(textPanel);
mainPanel.add(iconPanel, BorderLayout.WEST);
JOptionPane.showMessageDialog(superAdapter.getMainWindow(), mainPanel, "About", JOptionPane.PLAIN_MESSAGE);//INFORMATION_MESSAGE
}
});
fileMenu.add(creditsMenu);
//---- exit ----
JMenuItem exit = new JMenuItem();
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.exitActionPerformed();
}
});
fileMenu.add(exit);
JMenu bookmarksMenu = new JMenu("Bookmarks");
//---- Save location ----
saveLocationList = new JMenuItem("Save Current Location");
saveLocationList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//code to add a recent location to the menu
String stateString = superAdapter.getLocationDescription();
String stateDescription = superAdapter.getDescription("location");
if (stateDescription != null && stateDescription.length() > 0) {
addRecentStateMenuEntry(stateDescription + "@@" + stateString, true);
recentLocationMenu.setEnabled(true);
}
}
});
bookmarksMenu.add(saveLocationList);
saveLocationList.setEnabled(false);
//---Save State test-----
saveStateForReload = new JMenuItem();
saveStateForReload.setText("Save Current State");
saveStateForReload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//code to add a recent location to the menu
try {
String stateDescription = superAdapter.getDescription("state");
if (stateDescription != null && stateDescription.length() > 0) {
stateDescription = previousStates.checkForDuplicateNames(stateDescription);
if (stateDescription == null || stateDescription.length() < 0) {
return;
}
previousStates.addEntry(stateDescription, true);
superAdapter.addNewStateToXML(stateDescription);
previousStates.setEnabled(true);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
saveStateForReload.setEnabled(false);
bookmarksMenu.add(saveStateForReload);
recentLocationMenu = new RecentMenu("Restore Saved Location", recentLocationMaxItems, recentLocationEntityNode, HiCGlobals.menuType.LOCATION) {
private static final long serialVersionUID = 4204L;
public void onSelectPosition(String mapPath) {
String delimiter = "@@";
String[] temp;
temp = mapPath.split(delimiter);
superAdapter.restoreLocation(temp[1]);
superAdapter.setNormalizationDisplayState();
}
};
recentLocationMenu.setMnemonic('S');
recentLocationMenu.setEnabled(false);
bookmarksMenu.add(recentLocationMenu);
//---Export States----
exportSavedStateMenuItem = new JMenuItem();
exportSavedStateMenuItem.setText("Export Saved States");
exportSavedStateMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new SaveFileDialog(HiCGlobals.xmlSavedStatesFile);
}
});
// restore recent saved states
previousStates = new RecentMenu("Restore Previous States", recentLocationMaxItems, recentStateEntityNode, HiCGlobals.menuType.STATE) {
private static final long serialVersionUID = 4205L;
public void onSelectPosition(String mapPath) {
superAdapter.launchLoadStateFromXML(mapPath);
}
@Override
public void setEnabled(boolean b) {
super.setEnabled(b);
exportSavedStateMenuItem.setEnabled(b);
}
};
bookmarksMenu.add(previousStates);
//---Import States----
importMapAsFile = new JMenuItem();
importMapAsFile.setText("Import State From File");
importMapAsFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
superAdapter.launchImportState(HiCGlobals.xmlSavedStatesFile);
importMapAsFile.setSelected(true);
}
});
//---Slideshow----
slideShow = new JMenuItem();
slideShow.setText("View Slideshow");
slideShow.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
superAdapter.launchSlideShow();
HiCGlobals.slideshowEnabled = true;
}
});
//bookmarksMenu.add(slideShow);
bookmarksMenu.addSeparator();
bookmarksMenu.add(exportSavedStateMenuItem);
bookmarksMenu.add(importMapAsFile);
//---View Menu-----
viewMenu = new JMenu("View");
layersItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (layersItem.isSelected()) {
superAdapter.setLayersPanelVisible(true);
} else {
superAdapter.setLayersPanelVisible(false);
}
}
});
viewMenu.add(layersItem);
viewMenu.setEnabled(false);
final JMenuItem colorItem = new JMenuItem("Change Heatmap Color");
colorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JColorChooser colorChooser = new JColorChooser(HiCGlobals.HIC_MAP_COLOR);
JDialog dialog = JColorChooser.createDialog(MainMenuBar.this, "Select Heatmap Color",
true, colorChooser, null, null);
dialog.setVisible(true);
Color color = colorChooser.getColor();
if (color != null) {
HiCGlobals.HIC_MAP_COLOR = color;
superAdapter.getMainViewPanel().resetAllColors();
superAdapter.refresh();
}
}
});
viewMenu.add(colorItem);
final JCheckBoxMenuItem darkulaMode = new JCheckBoxMenuItem("Darkula Mode");
darkulaMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HiCGlobals.isDarkulaModeEnabled = !HiCGlobals.isDarkulaModeEnabled;
superAdapter.getMainViewPanel().resetAllColors();
//superAdapter.safeClearAllMZDCache();
superAdapter.refresh();
}
});
darkulaMode.setSelected(HiCGlobals.isDarkulaModeEnabled);
viewMenu.add(darkulaMode);
JMenuItem addCustomChromosome = new JMenuItem("Make Custom Chromosome (from .bed)...");
addCustomChromosome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.createCustomChromosomesFromBED();
}
});
if (HiCGlobals.isDevCustomChromosomesAllowedPublic) {
viewMenu.add(addCustomChromosome);
}
viewMenu.addSeparator();
//---Axis Layout mode-----
final JCheckBoxMenuItem axisEndpoint = new JCheckBoxMenuItem("Axis Endpoints Only");
axisEndpoint.setSelected(HiCRulerPanel.getShowOnlyEndPts());
axisEndpoint.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HiCRulerPanel.setShowOnlyEndPts(axisEndpoint.isSelected());
superAdapter.repaint();
}
});
viewMenu.add(axisEndpoint);
//---ShowChromosomeFig mode-----
//drawLine, drawArc or draw polygon// draw round rect
// fill Rect according to the chormsome location.
final JCheckBoxMenuItem showChromosomeFig = new JCheckBoxMenuItem("Chromosome Context");
showChromosomeFig.setSelected(HiCRulerPanel.getShowChromosomeFigure());
showChromosomeFig.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
superAdapter.setShowChromosomeFig(showChromosomeFig.isSelected());
superAdapter.repaint();
}
});
viewMenu.add(showChromosomeFig);
//---Grids mode-----
// turn grids on/off
final JCheckBoxMenuItem showGrids = new JCheckBoxMenuItem("Gridlines");
showGrids.setSelected(superAdapter.getShowGridLines());
showGrids.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
superAdapter.setShowGridLines(showGrids.isSelected());
superAdapter.repaint();
}
});
viewMenu.add(showGrids);
viewMenu.addSeparator();
//---Export Image Menu-----
JMenuItem saveToPDF = new JMenuItem("Export PDF Figure...");
saveToPDF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.launchExportPDF();
}
});
viewMenu.add(saveToPDF);
JMenuItem saveToSVG = new JMenuItem("Export SVG Figure...");
saveToSVG.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
superAdapter.launchExportSVG();
}
});
viewMenu.add(saveToSVG);
final JMenu devMenu = new JMenu("Dev");
final JCheckBoxMenuItem displayTiles = new JCheckBoxMenuItem("Display Tiles");
displayTiles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HiCGlobals.displayTiles = !HiCGlobals.displayTiles;
superAdapter.getHeatmapPanel().repaint();
}
});
displayTiles.setSelected(HiCGlobals.displayTiles);
if (HiCGlobals.isDevAssemblyToolsAllowedPublic) {
devMenu.add(displayTiles);
}
final JCheckBoxMenuItem colorFeatures = new JCheckBoxMenuItem("Recolor 1D Annotations in Assembly Mode");
colorFeatures.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IGVFeatureCopy.invertColorFeaturesChk();
repaint();
}
});
colorFeatures.setSelected(IGVFeatureCopy.colorFeaturesChk);
if (HiCGlobals.isDevAssemblyToolsAllowedPublic) {
devMenu.add(colorFeatures);
}
// todo MSS and Santiago - is this to be deleted?
final JCheckBoxMenuItem useAssemblyMatrix = new JCheckBoxMenuItem("Use Assembly Chromosome Matrix");
useAssemblyMatrix.setEnabled(!SuperAdapter.assemblyModeCurrentlyActive);
useAssemblyMatrix.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MainViewPanel.invertAssemblyMatCheck();
superAdapter.createAssemblyChromosome();
AssemblyFileImporter assemblyFileImporter;
assemblyFileImporter = new AssemblyFileImporter(superAdapter);
assemblyFileImporter.importAssembly();
// superAdapter.assemblyModeCurrentlyActive = true;
System.out.println(assemblyFileImporter.getAssemblyScaffoldHandler().toString());
}
});
useAssemblyMatrix.setSelected(MainViewPanel.assemblyMatCheck);
if (HiCGlobals.isDevAssemblyToolsAllowedPublic) {
devMenu.add(useAssemblyMatrix);
}
JMenuItem editPearsonsColorItem = new JMenuItem("Edit Pearson's Color Scale");
editPearsonsColorItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
superAdapter.launchPearsonColorScaleEditor();
}
});
devMenu.add(editPearsonsColorItem);
JMenuItem mapSubset = new JMenuItem("Select Map Subset...");
mapSubset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Private.launchMapSubsetGUI(superAdapter);
}
});
devMenu.add(mapSubset);
final JTextField numSparse = new JTextField("" + Feature2DHandler.numberOfLoopsToFind);
numSparse.setEnabled(true);
numSparse.isEditable();
numSparse.setToolTipText("Set how many 2D annotations to plot at a time.");
final JButton updateSparseOptions = new JButton("Update");
updateSparseOptions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (numSparse.getText().length() > 0) {
Feature2DHandler.numberOfLoopsToFind = Integer.parseInt(numSparse.getText());
}
}
});
updateSparseOptions.setToolTipText("Set how many 2D annotations to plot at a time.");
final JPanel sparseOptions = new JPanel();
sparseOptions.setLayout(new GridLayout(0, 2));
sparseOptions.add(numSparse);
sparseOptions.add(updateSparseOptions);
sparseOptions.setToolTipText("Set how many 2D annotations to plot at a time.");
devMenu.addSeparator();
devMenu.add(sparseOptions);
/** Assembly Menu **/
assemblyMenu = new JMenu("Assembly");
assemblyMenu.setEnabled(false);
enableAssembly = new JCheckBoxMenuItem("Enable Edits");
enableAssembly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (enableAssembly.isSelected()) {
superAdapter.getHeatmapPanel().enableAssemblyEditing();
} else {
superAdapter.getHeatmapPanel().disableAssemblyEditing();
}
}
});
resetAssembly = new JMenuItem("Reset Assembly");
resetAssembly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset?", "warning", JOptionPane.YES_NO_OPTION);
if (option == 0) { //The ISSUE is here
superAdapter.getAssemblyStateTracker().resetState();
superAdapter.refresh();
}
}
});
exitAssembly = new JMenuItem("Exit Assembly");
exitAssembly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset?", "warning", JOptionPane.YES_NO_OPTION);
if (option == 0) {
superAdapter.exitAssemblyMode();
}
}
});
exportAssembly = new JMenuItem("Export Assembly");
exportAssembly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String mapName = SuperAdapter.getDatasetTitle();
new SaveAssemblyDialog(superAdapter.getAssemblyStateTracker().getAssemblyHandler(), mapName.substring(0, mapName.lastIndexOf("."))); //find how to get HiC filename
}
});
final JMenuItem importMapAssembly = new JMenuItem("Import Map Assembly");
importMapAssembly.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (superAdapter.getLayersPanel() == null) {
superAdapter.intializeLayersPanel();
}
new LoadAssemblyAnnotationsDialog(superAdapter);
}
});
importModifiedAssembly = new JMenuItem("Import Modified Assembly");
importModifiedAssembly.addActionListener(new ActionListener() {
//TODO: add warning if changes are present
@Override
public void actionPerformed(ActionEvent e) {
if (superAdapter.getLayersPanel() == null) {
superAdapter.intializeLayersPanel();
}
new LoadModifiedAssemblyAnnotationsDialog(superAdapter);
}
});
setScale = new JMenuItem("Set Scale");
setScale.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double scale;
String newScale = MessageUtils.showInputDialog("Specify a scale", Double.toString(HiCGlobals.hicMapScale));
try {
scale = Double.parseDouble(newScale);
if (scale == 0.0) { // scale cannot be zero
scale = 1.0;
}
HiCGlobals.hicMapScale = scale;
// Rescale resolution slider labels
superAdapter.getMainViewPanel().getResolutionSlider().reset();
// Rescale axis tick labels
superAdapter.getMainViewPanel().getRulerPanelX().repaint();
superAdapter.getMainViewPanel().getRulerPanelY().repaint();
// Rescale and redraw assembly annotations
if (superAdapter.getAssemblyStateTracker() != null) {
superAdapter.getAssemblyStateTracker().resetState();
}
} catch (NumberFormatException t) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
}
});
boolean enabled = superAdapter.getAssemblyStateTracker() != null && superAdapter.getAssemblyStateTracker().getAssemblyHandler() != null;
exportAssembly.setEnabled(enabled);
resetAssembly.setEnabled(enabled);
enableAssembly.setEnabled(enabled);
setScale.setEnabled(superAdapter.getHiC() != null && !superAdapter.getHiC().isWholeGenome());
importModifiedAssembly.setEnabled(enabled);
exitAssembly.setEnabled(enabled);
assemblyMenu.add(importMapAssembly);
assemblyMenu.add(importModifiedAssembly);
assemblyMenu.add(exportAssembly);
assemblyMenu.add(resetAssembly);
assemblyMenu.add(resetAssembly);
setScale.setEnabled(true);
assemblyMenu.add(setScale);
assemblyMenu.add(exitAssembly);
// assemblyMenu.add(enableAssembly);
add(fileMenu);
//add(annotationsMenu);
add(viewMenu);
add(bookmarksMenu);
if (HiCGlobals.isDevAssemblyToolsAllowedPublic) {
add(assemblyMenu);
}
add(devMenu);
}
public RecentMenu getRecentLocationMenu() {
return recentLocationMenu;
}
public void setEnableForAllElements(boolean status) {
//annotationsMenu.setEnabled(status);
viewMenu.setEnabled(status);
assemblyMenu.setEnabled(status);
saveLocationList.setEnabled(status);
saveStateForReload.setEnabled(status);
saveLocationList.setEnabled(status);
}
public void enableAssemblyMenuOptions() {
resetAssembly.setEnabled(true);
exportAssembly.setEnabled(true);
enableAssembly.setEnabled(true);
setScale.setEnabled(true);
importModifiedAssembly.setEnabled(true);
exitAssembly.setEnabled(true);
}
public void enableAssemblyEditsOnImport(SuperAdapter superAdapter) {
enableAssembly.setState(true);
superAdapter.getHeatmapPanel().enableAssemblyEditing();
}
public void updatePrevStateNameFromImport(String path) {
previousStates.updateNamesFromImport(path);
}
public void updateMainMapHasBeenLoaded(boolean status) {
loadControlFromList.setEnabled(status);
recentControlMapMenu.setEnabled(status);
// if a control map can be loaded, that means main is loaded and its stats can be viewed
showStats.setEnabled(status);
}
public void updateControlMapHasBeenLoaded(boolean status) {
showControlStats.setEnabled(status);
}
public void setAnnotationPanelMenuItemSelected(boolean status) {
layersItem.setSelected(status);
}
} |
In 2013, Tarjei Skaar was about to start his last year in high school in his native Norway when his father, Knut, was appointed as the representative for the Nordic Delegation to the International Civil Aviation Organization. Similar to a diplomatic posting (ICAO is a United Nations agency), Skaar senior’s job required the family to move from Bergen to Montreal for three years — an upheaval for the family (his wife is an air traffic controller), but also something of an adventure.
Skaar junior was able to transfer into Quebec’s CEGEP system and he ultimately ended up at McGill, where he is in his final year in chemical engineering. When his parents relocated back to Norway, Tarjei remained in Montreal, as did his brother, Ivar, who is also a student.
At McGill, Tarjei met Emma Little, a fellow chemical engineering student from Vancouver. After dating for some time (they are both 22), they moved in together in September 2018.
Their 4½, which is on the top floor of a triplex in a building that has seen better days, is very much a starter home with simple furnishings. Nonetheless, the apartment is in an area they both love, Mile End.
Q: You said it was quite a challenge to find this place?
Emma: We were keen to find a rental for the beginning of the school year rather than for July 1, but that proved easier said than done. Tarjei had taken a summer job back in Norway and I was working full time in Vancouver. Luckily, Ivar stayed on in Montreal, so he was a big help.
Tarjei: We would check out apartments on Kijiji, Craigslist, Facebook and so on and my brother would check them out. We communicated by Skype — that was a challenge too because of the time differences — and he’d give us feedback.
Q: So why did you choose this particular apartment?
T: It was one of the best options.
T: The combination of the area, the price and good access to public transport.
Q: But neither of you had seen the apartment in person until you were back in Montreal?
E: One thing we’re really happy about is the large kitchen. We both enjoy cooking. Shuffling around in a galley kitchen trying not to bump into one another wouldn’t have been fun.
Q: You said you already had most of your furniture?
E: Before we moved in together, I had a place in the Plateau and Tarjei was living in the McGill Ghetto. We’d put all of our stuff in storage.
Q: Where did you get the orange-patterned sectional couch in the living room?
T: That came from my parents. I think it’s an Ikea model circa 1980!
Q: What about the TV and the pine chest of drawers it’s standing on?
T: The chest of drawers came from friends of my parents who were downsizing and I bought the TV from my former roommate when he moved out. I made the little coffee table. I cut the legs off an old one that I didn’t like very much and bought the wood for the top from Home Depot.
Q: Your Oriental-style rug is very attractive. Did that come from the Middle East?
E: I’m not sure. I got it from my parents. They may have picked it up on their travels. They were both flight attendants for Air Canada.
Q: It sounds as if you were both lucky to have parents who gave you a lot of useful things to help you furnish your home?
E: Absolutely, but we also bought some things second-hand.
E: The desk at the far end of the living room came from Kijiji. The fellow who sold it to us said it had been his son’s work table. It’s solid wood, not veneer.
Q: What about the desk chair?
E: That was a street find.
Q: I’ve just noticed that you don’t seem to have a dining table.
T: (Laughs.) We’ve yet to figure out where to put one. Right now, we just eat sitting on the couch, but obviously, that’s not the ideal scenario.
Q: It sounds as if your home is still somewhat of a work in progress?
E: Well, we’ve been here only a short while and we had quite a lot to do when we moved in. One of our first jobs was to paint all the walls white.
Q: Were they a colour you couldn’t live with?
E: No. That wasn’t it. For some reason the previous tenants had painted outlines of furniture on the walls! There were “frames” for example, where pictures had obviously been hanging before.
Q: How odd! Didn’t the landlord object? You said he lived downstairs?
E: Frankly, I don’t think the landlord knew anything about it. We had to paint over the top of all this silly stuff but at least he repaid us for the materials. |
Medical scheme expenditure on dental care--a smaller slice of the pie. Medical schemes play an important part in financing dental care in the private sector and provide many dental practitioners with a substantial source of income. Data on medical scheme expenditure indicates a steady decline in their proportional pay-out for dental care during the period 1985 to 1994. In 1985 more than 12 per cent of total medical scheme expenditure was spent on dental care. In 1994 this had reduced to 8.37 per cent. In the present study, the historical trend of medical scheme expenditure on dental care is analysed. By using the least squares method, the annual medical scheme expenditure on dental care is computed for the next eleven years. If the secular trend continues, less than 4 per cent of medical scheme expenditure will be paid for dental care by the year 2005. |
Calcium Binding, but Not a Calcium-Myristoyl Switch, Controls the Ability of Guanylyl Cyclase-activating Protein GCAP-2 to Regulate Photoreceptor Guanylyl Cyclase* Guanylyl cyclase-activating protein 2 (GCAP-2) is a recoverin-like calcium-binding protein that regulates photoreceptor guanylyl cyclase (RetGC) (Dizhoor, A. M., and Hurley, J. B. J. Biol. Chem. 271, 1934619350). It was reported that myristoylation of a related protein, GCAP-1, was critical for its affinity for RetGC (Frins, S., Bonigk, W., Muller, F., Kellner, R., and Koch, K.-W. J. Biol. Chem. 271, 80228027). We demonstrate that the N terminus of GCAP-2, like those of other members of the recoverin family of Ca2+-binding proteins, is fatty acylated. However, unlike other proteins of this family, more GCAP-2 is present in the membrane fraction at low Ca2+ than at high Ca2+ concentrations. We investigated the role of the N-terminal fatty acyl residue in the ability of GCAP-2 to regulate RetGCs. Myristoylated or nonacylated GCAP-2 forms were expressed inEscherichia coli. Wild-type GCAP-2 and the Gly2→ Ala2 GCAP-2 mutant, which is unable to undergo N-terminal myristoylation, were also expressed in mammalian HEK293 cells. We found that compartmentalization of GCAP-2 in photoreceptor outer segment membranes is Ca2+- and ionic strength-sensitive, but it does not require the presence of the fatty acyl group and does not necessarily directly reflect GCAP-2 interaction with RetGC. The lack of myristoylation does not significantly affect the ability of GCAP-2 to stimulate RetGC. Nor does it affect the ability of the Ca2+-loaded form of GCAP-2 to compete with the GCAP-2 mutant that constitutively activates RetGC. We conclude that while Ca2+ binding plays a major regulatory role in GCAP-2 function, it does not operate through a calcium-myristoyl switch similar to the one found in recoverin. |
national
Rare bioluminescent waves make second appearance this week in Mumbai's popular Juhu beach. it will be visible for 2 days
A photograph of the bioluminescent waves clicked by Niklesh Mane in January
The waves of Juhu beach took on a fluorescent blue hue last night, delighting several nightwalkers and revellers.
The rare phenomenon, described as bioluminescence, is the second of its kind to be seen along the Mumbai coast. Bioluminescence is basically the production and emission of light by living marine organisms. Mumbaikars will be able to witness the phenomenon first-hand over the course of the next two days.
Dr Parvish Pandya, vice-principal and associate professor of Zoology at Bhavan’s College, who recorded this phenomenon on his mobile phone, during a stroll on the beach, said, “I am really excited to report that the bioluminescence phenomenon along Mumbai’s coast can be seen once again at Juhu beach.” Pandya, who is well-known in the wildlife and environment circles, posted the photographs of the bioluminescent waves on Facebook and urged people to visit Juhu beach today and tomorrow night, if they wanted to experience it.
Dr Parvish Pandya, vice-principal of Bhavan’s College, captured the phenomenon on his mobile phone on Tuesday night
“I think those who are interested in seeing bioluminescence should not miss this wonderful opportunity. I have posted the link of the Google location on my Facebook post. “You can climb the jetty and see the blue sparkles in the sea as the waves come in [high tide, at around 1.30 am to 2 am]. Be careful to walk back to the beach before the jetty gets surrounded by water,” he added.
Earlier this year, Niklesh Mane and his friend Abir Jain had seen the bioluminescent waves for the very first time in Mumbai in January.
What: The bioluminescence phenomenon
When: When phytoplanktons get washed ashore, a protein called luciferase is activated triggering a series of chemical reactions that produces the neon blue glow.
Where to locate the glow? 19°05’14.8”N 72°49’34.8”E |
<reponame>valkuc/esp8266-ir-remote
/*
* ir_remote_def.h
*
* Version 1.1, 08.03.2016
* Written by <NAME>
* For details, see https://github.com/valkuc/esp8266-ir-remote
*
* IR code defines are based on https://github.com/shirriff/Arduino-IRremote by <NAME>
*/
#ifndef __IR_REMOTE_DEF_H__
#define __IR_REMOTE_DEF_H__
#define TOPBIT 0x80000000
#define NEC_FREQUENCY 38400
#define NEC_HDR_MARK 9000
#define NEC_HDR_SPACE 4500
#define NEC_BIT_MARK 562
#define NEC_ONE_SPACE 1687
#define NEC_ZERO_SPACE 562
#define PANASONIC_FREQUENCY 35000
#define PANASONIC_HDR_MARK 3502
#define PANASONIC_HDR_SPACE 1750
#define PANASONIC_BIT_MARK 502
#define PANASONIC_ONE_SPACE 1244
#define PANASONIC_ZERO_SPACE 400
#define SONY_FREQUENCY 40000
#define SONY_HDR_MARK 2400
#define SONY_HDR_SPACE 600
#define SONY_ONE_MARK 1200
#define SONY_ZERO_MARK 600
#define SAMSUNG_FREQUENCY 38400
#define SAMSUNG_HDR_MARK 5000
#define SAMSUNG_HDR_SPACE 5000
#define SAMSUNG_BIT_MARK 560
#define SAMSUNG_ONE_SPACE 1600
#define SAMSUNG_ZERO_SPACE 560
#define RC5_FREQUENCY 36000
#define RC5_T1 889
#define RC6_FREQUENCY 36000
#define RC6_HDR_MARK 2666
#define RC6_HDR_SPACE 889
#define RC6_T1 444
#endif
|
<reponame>charliebruce/waxbee<filename>WaxBeeConfig/src/org/waxbee/CoordinatesEditor.java
package org.waxbee;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.lang.reflect.Method;
import javax.swing.JPanel;
import javax.swing.JWindow;
import org.waxbee.teensy.extdata.WaxbeeConfig;
@SuppressWarnings("serial")
public class CoordinatesEditor extends JWindow
{
WaxbeeConfig itsWaxbeeConfig;
Monitor itsMonitor;
public CoordinatesEditor(MainApplication mainApplication, WaxbeeConfig waxbeeConfig, Monitor monitor)
{
super(mainApplication);
itsWaxbeeConfig = waxbeeConfig;
itsMonitor = monitor;
add(new CoordinatesEditorPanel(), BorderLayout.CENTER);
setSemiTransparent();
setBounds(itsMonitor.itsBounds);
}
void setSemiTransparent()
{
try
{
Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
mSetWindowOpacity.invoke(null, this, 0.50f);
}
catch(Exception ex)
{
}
}
class CoordinatesEditorPanel extends JPanel implements MouseListener, MouseMotionListener
{
private Point itsCurrentMousePosition = null;
private Point itsDraggingPosition = null;
public CoordinatesEditorPanel()
{
super(true);
setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
setCursor(getBlankCursor());
}
private Cursor itsBlankCursor = null;
private Cursor getBlankCursor()
{
if(itsBlankCursor == null)
{
// Transparent 16 x 16 pixel cursor image.
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
itsBlankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank");
}
return itsBlankCursor;
}
@Override
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
Graphics2D g = (Graphics2D)graphics;
Rectangle rect = getBounds();
g.setColor(Color.WHITE);
g.fillRect(0, 0, rect.width, rect.height);
int rad = 5;
int rad2 = 30;
g.setStroke(new BasicStroke(1.0f));
if(itsCurrentMousePosition != null)
{
g.setColor(Color.BLACK);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaintMode();
g.drawOval(itsCurrentMousePosition.x-rad, itsCurrentMousePosition.y-rad, rad*2, rad*2);
g.drawOval(itsCurrentMousePosition.x-rad2, itsCurrentMousePosition.y-rad2, rad2*2, rad2*2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setXORMode(Color.WHITE);
g.drawLine(0, itsCurrentMousePosition.y, rect.width, itsCurrentMousePosition.y);
g.drawLine(itsCurrentMousePosition.x, 0, itsCurrentMousePosition.x, rect.height);
}
if(itsDraggingPosition != null)
{
g.setColor(Color.RED);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaintMode();
g.drawOval(itsDraggingPosition.x-rad, itsDraggingPosition.y-rad, rad*2, rad*2);
g.drawOval(itsDraggingPosition.x-rad2, itsDraggingPosition.y-rad2, rad2*2, rad2*2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setXORMode(Color.WHITE);
g.drawLine(0, itsDraggingPosition.y, rect.width, itsDraggingPosition.y);
g.drawLine(itsDraggingPosition.x, 0, itsDraggingPosition.x, rect.height);
}
}
@Override
public void mouseDragged(MouseEvent e)
{
itsDraggingPosition = e.getPoint();
repaint();
}
@Override
public void mouseMoved(MouseEvent e)
{
itsDraggingPosition = null;
itsCurrentMousePosition = e.getPoint();
repaint();
}
@Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e)
{
itsCurrentMousePosition = null;
repaint();
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
dispose();
}
}
}
|
Change in retinal vessel diameter and choroidal thickness in patients with severe COVID-19 Purpose : To compare the differences in retinal vascular structure and choroidal thickness between the active disease and post-recovery periods in COVID-19 patients and healthy controls. Material and Methods : This prospective, cross-sectional study included 30 eyes from 30 patients with severe COVID-19 and 30 eyes of 30 sex-matched healthy controls. Central macular thickness (CMT), subfoveal choroidal thickness (CT) and retinal vascular changes of patients were measured after positive polymerase chain reaction (PCR) (where the patient had COVID-19-related symptoms) and then three months after two negative PCRs. Laboratory parameters, including C-reactive protein and d-dimer levels, were also recorded. Results : The mean age of the patients was 47.90 ± 9.06 years in patients group, 49.07 ± 8.41 years in control goups (p = 0.467). In terms of choroidal thicknesses subfoveal, nasal and temporal region were significantly higher in the active disease period than control group (p = 0.019, p = 0.036, p = 0.003, respectively). When the after recovery period was compared with the control group in terms of choroidal thickness, although the choroidal thickness was higher in all regions, this difference was not found statistically significant. There was no statistically significant difference in CMT between groups (p = 0.506).The mean venous and arterial wall thicknesses were significantly higher in the active period than after recovery (p = 0.023, p = 0.013, respectively) but there were no differences between after recovery and control groups in the pairwise comparison (p = 0.851, p = 0.715, respectively). Conclusion : In patients with severe COVID-19, there are changes in thickness of the choroid and retinal vessel walls. While vascular wall thickness increases due to inflammation, the absence of lumen changes may be associated with hemodynamic variables. Introduction An outbreak of coronavirus disease (COVID- 19), which causes severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), has emerged in China and has rapidly spread worldwide. In histopathological studies, COVID-19 has been shown to cause endotheliitis and vasculitis in the arterial and venous circulation, mainly in the lung, heart, kidney, intestine and brain; this is caused directly by a viral infection. Ultimately, the small vessels' endothelial cell edema, congestion and thrombosis cause ischemia/reperfusion injury, resulting in multiple organ dysfunction. Current information shows that SARS-CoV-2 binds to host cells through a metallopeptidase, angiotensin-converting enzyme 2 (ACE-2) receptor, resulting in the downregulation of cell-surface ACE-2 expression. These receptors are found in all major organs, especially in the lungs, heart, veins, arteries, aqueous humor and retina. The downregulation of cell-surface ACE-2 expression can damage the retina either by a direct cytopathic effect through the ACE-2 receptor or indirectly through an inflammatory response. Extensive endothelial damage and thromboembolic events affecting different body parts other than COVID-19 patients' lungs have been reported in several studies. The retina's arteries and vessels, which show changes in many systemic diseases, may indicate when the vascular system undergoes the same pathological processes. Retinal vessel analysis is an emerging technique for the non-invasive assessment of the microvasculature. In recent years, choroidal thickness and retinal thickness in particular have been considered as potential structural inflammatory markers. We aimed to investigate whether retinal vasculature and choroidal thickness as an indicator of systemic inflammation are affected in both patients with severe COVID-19 pneumonia and in recovered patients. Study population and design This prospective, cross-sectional study was conducted at the Ophthalmology Department in our pandemic hospital between December 2020 and May 2021. Patients hospitalized due to severe COVID-19 were asked to participate in the study. The local ethics committee approved the study, and oral and written informed consent was obtained from all participants. The procedures used conformed to the tenets of the Declaration of Helsinki. This study included 30 eyes of 30 patients who were diagnosed with severe COVID-19 and 30 eyes of 30 age and sex-matched healthy controls. Healthy controls were selected from individuals with no prior COVID-19 history and confirmed PCR negativity during the study. The inclusion criteria were as follows: 1) having a positive polymerase chain reaction (PCR) and COVID-19 related symptoms; 2) being classified as having severe COVID-19; 3) being able to sit in front of the OCT; and 4) having onset of symptoms within one week before the evaluation. We determined severe COVID-19 based on the following findings: oxygen saturation <93% for room air (or PaO2/FiO2 <300 mmHg); respiratory rate >30 breaths per minute; more than 50% involvement of the lung parenchyma in chest imaging. For all patients, the exclusion criteria were as follows: 1) refractive error ≥ ±3 D; 2) other previous or concomitant retinal diseases; 3) any history of ocular surgery within 6 months; 4) uncontrolled systemic hypertension or other systemic diseases; 5) eyes with low-quality OCT image scores (quality scores <25). OCT imaging and measurements Retinal vessel diameters were evaluated using Spectralis OCT+HRA with infrared reflectance (IR) images (Fig. 1). IR images were obtained by scanning a circular region with a diameter of 3.42-4.04 mm centered on the optic disk and then analyzed using Spectralis software. Firstly, all OCT and IR images of the eyes were reviewed by a single retina specialist. Retinal vessels were then classified as arteries and veins, according to an experienced retinal specialist's anatomical features in IR images. Retinal artery and vein diameters, including the vertical vessel outer diameter (VOD), vertical vessel inner diameter (VID), and vessel wall thickness (VWT), within each of the four quadrants around the optic disk, were measured from IR images using the manual caliper tool ( Fig. 1). Central macular thickness (CMT), subfoveal choroidal thickness (CT) and retinal vessel diameters of patients were measured after a positive PCR with COVID-19-related symptoms and three months after two negative PCRs. Two experienced retinal specialists independently measured the vessel diameters in each IR image according to a published method, and intraclass correlation coefficients (ICC) were calculated. The average inner, outer diameter and wall thickness of the retinal artery and vein were calculated using the average of the data in the four quadrants. Central macular thickness (CMT) was defined as the mean thickness of the central 1 mm zone of the Early Treatment Diabetic Retinopathy Study (ETDRS) grid and measured by spectral-domain OCT (Fig. 1). Subfoveal choroidal thickness (CT) was described as the distance between the RPE line base and the scleral layer's inner surface. CT was manually measured at nasal and temporal regions of 1500 m from the center of the fovea using the SD-OCT software's caliper tool (Fig. 1). For all OCT images, each scan was averaged 100 times during acquisition to reduce speckle noise, and was evaluated for analysis if ART averaging ≥ 75 times. According to signal strength, the OCT images with a quality score ≥ of 25 dB (range: 0-40 dB) were assessed for analysis. Statistical analysis All statistical tests were performed using the SPSS program (Version 26.0, Armonk, NY: IBM Corp). Quantitative descriptive variables were presented as the mean ± standard deviation and qualitative descriptive variables were expressed as frequencies and percentages. The normal distribution of all variables was determined with the Kolmogorov-Smirnov test. The differences among active disease period, after recovery, and healthy controls were compared with a one-way analysis of variance for parametric data. When a significant result was obtained, the Scheffe test was performed for post hoc comparisons. Pearson's chisquare test was used for the comparison of categorical variables. Kruskal-Wallis test was used to compare the differences in nonparametric data and applied Bonferroni corrections in cases of significant differences. The intraclass correlation coefficient (ICC) was calculated to determine the interobserver reliability of retinal vessel diameters, and ICC values of greater than 0.80 were accepted as good agreement. A p-value less than 0.05 was accepted as significant. Results Thirty eyes of 30 patients with COVID-19, confirmed both clinically and by the laboratory, were enrolled in this study. The mean age of patients was 47.90 ± 9.06 years (range: 29-65 years), and 18 (60%) patients were male and 12 (40%) patients were female. The mean age of controls was 49.07 ± 8.41 years (range: 31-65 years), and 19 (63.3%) patients were male and 11 (36.6%) patients were female. The two groups were statistically similar in age and gender (p = 0.467 and p = 0.802, respectively). Demographics and laboratory parameters of the patients are shown in Table 1. Nineteen (63.3%) of patients had a fever, 24 (80%) of patients had a cough, 25 (83.3%) of patients had respiratory distress and 6 (20%) of patients had ocular findings (hyperemia, epiphora, episcleritis and follicular conjunctivitis). The mean duration of hospital admission was 3.7 ± 1.8 days, while the time from onset of symptoms to the time ophthalmologic examinations was 8.3 ± 2.3 days. There was a statistically significant difference between groups in terms of choroidal thickness. Although the choroidal thickness increased in all regions when the active disease period was compared with the recovery period, there was a significant difference only in subfoveal choroidal thickness (p = 0.036). In terms of choroidal thicknesses subfoveal, nasal and temporal region were significantly higher in the active disease period than control group (p = 0.019, p = 0.036, p = 0.003 respectively). When the recovery period was compared with the control group in terms of choroidal thickness, although the choroidal thickness was higher in all regions, this difference was not found statistically significant. There was no statistically significant difference in CMT between groups (p = 0.506) ( Table 2). Table 3 presents the artery and vein diameters with the average inner, outer diameter and wall thickness within each of the four quadrants of the controls' and the patients' eyes at admission to the hospital and in the third month of follow-up. While the mean venous and arterial wall thicknesses were significantly higher in the active period than after recovery (p = 0.023, p = 0.013 respectively) but there were no differences between after recovery and control groups in the pairwise comparison (p = 0.851, p = 0.715 respectively). The mean venous and arterial outer diameter were statistically different between the groups (p = 0.002, p = 0.022 respectively). The venuler and arterial outer diameters were higher in the active disease period than after recovery (p = 0.010, p = 0.044 respectively), but there was no difference between after recovery and control groups in the pairwise comparison (p = 0.783, p = 0.817 respectively). Also the mean venous and arterial VID values were not significantly different between groups (p = 0.865, p = 0.074 respectively), (table 3). The graphs in Figs. 2 and 3 present the mean inner, outer diameter and wall thickness of the artery and vein in all groups comparatively. No significant relationship was found between the reduction in choroidal thickness and the retinal vessel diameter change and patients' laboratory parameters. There was excellent interobserver reproducibility for 20 randomly selected images in the measurement of VID and VWT thickness. Interobserver intraclass correlation coefficient values for VID and VWT thickness were 0.812 (0.788-0.940) and 0.843 (0.802-0.895), respectively. Discussion Our study found that retinal artery and vein wall thickness, in addition to central macular and choroidal thickness, increased in patients with severe COVID-19. Previous studies showed that COVID-19 attacks tissues with ACE receptors and causes pathologies through this receptor. The blood retina barrier, RPE and blood endothelial cells formed by the endothelial cells of retinal vessels and epithelial cells with retinal pigment express ACE2. These findings suggest that vessels in the eye (retinal, choroid) and vitreous containing ACE receptors may also have pathologies because of COVID-19 infection. Animal studies have shown that in the conjunctiva of feline (feline infectious peritonitis virus or FIPV), infection with coronavirus is common and can cause conjunctivitis, anterior uveitis, retinal vasculitis and choroiditis with retinal detachment. Endothelial changes and endotheliitis are essential determinants of microvascular dysfunction since this process activates vasoconstriction, ischemia, tissue edema and procoagulant tendency. It is not fully understood whether the virus directly activates this process and results from local and systemic inflammatory processes. However, these findings suggest a close relationship between inflammation and the coagulation cascade. Alfredo Insausti-Garca et al. described papillophlebitis presenting with dilated and tortuous retinal vessels, disk edema, macular edema and retinal hemorrhages in a patient with COVID-19. Studies have shown that more than 30% of COVID-19 patients develop venous and arterial thrombotic events, especially venous thromboembolic events (27%). Vascular occlusion associated with thrombotic susceptibility and changes such as chorioretinitis or vasculitis directly mediated by the virus can be observed in the retina, a privileged site for non-invasive and in vivo evaluation of systemic diseases. Similarly, we detected vascular structure, choroid and retinal changes in patients with COVID-19, a systemic disease affecting many organs. Subsegmental vascular enlargement has been reported on computed tomography of the chest in COVID-19 patients, which may be due to an inflammatory response or increased blood flow due to direct endothelial damage. Invernizzi et al. investigated alterations of the retina and its vasculature in patients with COVID-19 within 30 days of onset of symptoms. The authors found that retinal arteries and veins were larger in COVID-19 patients than in the non-infected group. In more severe cases, the vessel diameter was larger and inversely correlated with the onset of symptoms. However, in this study, the total vessel diameter was measured, and lumen and wall thickness were not evaluated in detail. It is unknown whether the increase in total wall diameter is due to lumen enlargement or increased wall thickness. Our study performed retinal analysis within the first week after hospitalization, and we evaluated both lumen diameter and wall thickness in arteries and veins in detail. We found that while the lumen diameter did not change in either artery or vein, the vessel wall thickness increased. In another study evaluating retinal vessel diameters, vasodilation was demonstrated during active disease compared to control and after recovery, but detailed vessel analysis was not evaluated. In stress situations such as a decrease in O2 or an increase in CO2, and with an increase in inflammatory mediators, the retinal arteries actively enlarge, while the veins are passively enlarged. The absence of a significant change in vessel lumen diameters despite the increased vessel wall thickness, hemodynamic stimuli caused by shear stress and the negative effect of endothelial-induced vessel wall edema may have caused the lumen diameter to not increase as expected. We think that the increase in the vessel walls' thickness is due to edema associated with inflammation and endotheliitis in a severe COVID-19 period. Retinal arteries and vein diameters, which are significantly associated with various systemic factors, have been studied with concern to systemic diseases and conditions. Retinal vascular changes may be seen in patients with viral diseases such as HIV. HIV targets the vascular endothelium and causes retinopathy to damage the microvasculature. Similarly, COVID-19 is systemically involved throughout the vascular system and the primary pathology is vasculitis. Our study showed that COVID-19 could affect the entire vascular system regardless of the artery and vein. Casagrande et al. detected CoV-2-SARS viral RNA in the retina of COVID-19 patients in a biopsy study. Marinho et al. described Table 1 Demographics and laboratory parameters of the patients. *The variables were expressed as mean ± standard deviation (range). Table 2 The mean central macular thickness and choroidal thickness at active disease period, in period after recovery and control group.. Also, COVID-19 has been described as a multi-organ dysfunction characterized by multisystem inflammatory syndrome (MIS). Subclinical choroidal involvement has been shown in multisystem inflammatory diseases, even without any evidence of ocular involvement. It is thought that choroidal pathologies may also occur because COVID-19 causes both vascular damage and systemic inflammatory syndrome. Indeed, it has been shown that choroidal thickness is increased in severe COVID-19 patients in a recent study. In our study, the increased in choroidal thickness in the active disease period Table 3 The mean vessel diameter measurements of patients' eyes at active disease period, in period after recovery and control group. compared to the after recovery and control group supports this study. In our study evaluating the 3rd month after the disease, it was shown that most findings were reversible and in a study with a longer follow-up period of 9 months, all available findings were found to be similar to the control group. Blood retina barrier consists of endothelial cells of retinal vessels and RPE cells and expresses ACE2 due to this endothelial cell component. It has been shown in the literature that SARS-CoV-2 triggers a peripheral immune response by increasing the release of proinflammatory cytokines that can disrupt the blood retina barrier. Thus, it can damage the retina either by a direct cytopathic effect through the ACE-2 receptor or indirectly through an inflammatory response. In our study, increased central retinal thickness during the disease period supports the presence of retinal involvement. However, decreased retinal thickness after recovery suggests that it is a temporary finding. One of the limitation of this study is that retinal vessel diameters were measured by manuel caliper tool. In this study, ICC values of greater than 0.80 were accepted as good agreement in all manual measurements. When the examiners' measurements were not consistent, they were repeated until good agreement was obtained and the average of both measurements was used for the statistical analysis. Despite all these measures, it should be taken into account that retinal vessel diameters were measured on IR images using manuel caliper tool, the errors caused by the manual technique may not be completely eliminated. Another point to be noted is that the retinal vessel diameters may differ between the participants. Another limitation is that we included only severe cases, so we could not examine the correlation between disease severity and vessel diameter changes. Therefore, there is a need for larger and subgroup studies that classify disease severity. In conclusion, in patients with severe COVID-19, there may be structural changes in the retinal vessels and choroid level, but the findings regress after the disease heals. While vascular wall thickness increases due to inflammation, the absence of lumen changes may be due to hemodynamic variables. However, more advanced physiopathological studies are needed. Disclosures financial support No financial support was received for this submission. Ethic Our prospective study conducted in accordance with the Declaration of Helsinki |
Effect of Gamma Irradiation on the Physical Properties of PVA Polymer Polyvinyl alcohol (PVA) films were prepared by casting method. The optical properties was measured in the wavelength rang of (200900) nm, by using UV-visible spectroscopy. The effect of irradiation lead to degradation on the physical properties such as absorbance, transmittance, refractive index, extinction coefficient in addition of the real and imaginary part of dielectric constant was studied. This study reveals that all these parameters affected by the increasing of them irradiation, and also found that the optical energy gap has been increased with the increasing of the irradiation. The structural properties are studied by using XRD, FTIR spectrum, and FESEM. Islam Shukri Elashmawi et al, studied the effect of irradiation at different time's Nd:YAG laser on optical properties of PVA/Ag, the absorbance spectra is increase with increase times of irradiated (5, 10 and 15) min, and the energy gap before irradiation for PVA and PVA/Ag nanocomposite are(3.96 eV, 3.33 eV), but for irradiation the energy gap for PVA is (3.96 eV) and for PVA/Ag the energy gap are ( 3.01, 2.19 and 1.94) eV at different irradiation of time's (5, 10 and 15) min respectively. It is clear the energy gap is decrease with increase irradiation times. F.M. Alia et al, studied the optical properties of PVA films doped with methyl violet-6B (MV-6B) which are prepared by casting method, show the addition MV-6B to PVA has a strong effect on the optical properties, and energy gap is decrease with increase concentration of PVA. The aim of the present work is to prepare PVA films using casting method. PVA thin film will be irradiated by -rays and physical properties will be tested before and after irradiation. Theoretical Part The relationship between the intensity of incident and transmitted light is given by the equation I = Io e −t. Where (Io) and (I) are the intensities of the incident and transmitted light, respectively, () is the optical absorption coefficient; (t) is the thickness of film and absorbance is defined by A=log (Io/I). The optical absorption coefficient () can be calculated from the optical absorbance spectra by using the relation : = log ( I o ) = 2.303 The extinction coefficient (K) is related to absorption coefficient (), by the following equation : Where, is the wavelength of incident light. The reflectance (R) can be calculated from the values of the absorbance and transmission coefficient from the equation: The refractive index (n) depends on the reflectance (R) and extinction coefficient (K) and it can be calculated from the following equation : The absorption edge for direct and indirect transition can be obtained in the view of the proposed by Tauc et al. Where (h ) is the energy of photon, (A) is the proportional constant, (Eg) is the allowed or forbidden energy gap of direct and indirect transition and (r) is constant depended on the electronic transition, r=1/2, 3/2, 2 or 3 for allow direct, forbidden direct, allow indirect and forbidden indirect transition, respectively. The Dielectric constant clarified the ability of material to polarization and can be express by the following equation: The dielectric constant is divided into two parts real ( r ) and imaginary ( i ) and described by the following equations: Experimental Work Polyvinyl alcohol (PVA) is a light, white, powdery solid polymer when it is pure.The structure of PVA is shown in figure. PVA solution was prepared by taking certain amount of PVA powder (0.5) g in 15 ml distilled water, stirred for 3 to 4 hours at room temperature by magnetic stirrer (hot plate) in ( 25 -35) o C to ensure for fully dissolving. Forming the PVA films by pouring out the solution in glass plates with diameter cm and allowed it to evaporate slowly at room temperature for (3 to 4) days to get homogeneous films. The samples were irradiated with irradiation dose(1, 3, 5, 8, 10 and 15) kGy, using 60 Co Gamma Cell-900, of strength rate 3.7Ci and dose rate 53 Gy/h, which emits mono-energetic 1.17 and 1.33 MeV, and a half- Figure, shows the UV/Vis absorption spectra of unirradiated and irradiated PVA films. The results from figure shows the absorbance spectra as a function of the wavelength of the incident light for PVA film. As it is clear in figure, shows absorption spectrum is increase with increase in irradiation dose but we note full of some absorption spectra at (3, 8 and 10) kGy because of during irradiation process increase in the movement energy of the molecules in the polymeric chain with increase in the irradiation doses, which lead to a weakening of the bonding forces between the partial chains of the polymer. This result corresponds to A.H. R.H. Al-Azzawi. Transmission Spectrum The transmittance spectrum for irradiated PVA films with different irradiation doses exhibit opposite behavior in absorbance spectra as shown in figure because the transmission relationship with absorption is a logarithmic relationship. These results are in agreement with A.J. Almusawe, et al. Reflection Spectrum The reflection spectra after irradiation by Gamma ray for pure PVA is showed in figure. The reflection spectrum is calculated from absorption and transmission spectrum according to equation. shows the refractive index for pure PVA films after irradiated by gamma ray. The refractive index like reflection spectrum where the refractive index for pure PVA increased after irradiated, but it is decreased at (8 and 10) kGy. These changes in the refractive index and reflection spectrum of irradiated PVA may be due to degradation process that is predominant. Absorption Coefficient The absorption coefficient is defined as the ability of material to absorption light with a limited wavelength per unit length and it is a characteristic property for every absorber molecule or ion. The value of absorption coefficient () is calculated from equation for all samples. The absorption coefficient helps to deduce the nature of electronic transition. Optical Energy Gap The optical energy gap is the value of optical energy gap that is necessary to develop the electronic band structure of film material. Figure show the relationship between absorption edge (h) 1/m and energy of photon for the pure PVA film. It can be noted that the energy gap for pure PVA film can be measured and equal to (4.66 eV) at 0kGy, for allowed and forbidden transition. When irradiated PVA polymer with different radiation dose, the value of energy gap for PVA increase with increasing radiation dose to become (4.88 eV) at 10kGy and (5eV) at 15kGy. These different changes in energy gap occurred for PVA illustrated in table. Extinction coefficient The extinction coefficient depends on absorbance so that the behavior of extinction coefficient is similar to the absorption spectrum for all samples. Figure illustrates the extinction coefficient for irradiated pure PVA films at different radiation doses. Dielectric constants The optical constants are very important for the quantitative determination of the electronic band structure of solids from information of optical reflectivity; transmission and refraction provide the way to determine the dielectric constants of solid, which is related to the band structure. Equations and dielectric constants, respectively. The real part of dielectric constants for pure PVA films at different radiation dose which showed in figure. The real dielectric constant increases with increasing radiation dose that mean the real dielectric constant depend on the square of refractive index and the square of extinction coefficient. The behavior of these figures is similar to refractive index because of the smaller value of k 2 compared to n 2. Figure : real dielectric constant for PVA films at different irradiation doses The imaginary part of dielectric constants for pure PVA films at different irradiation doses in figure. Imaginary dielectric constant for pure PVA film films increased with increasing radiation dose, and this constant depends on the k value, which is related to the variation of the absorption coefficient. X-ray Diffraction The XRD shall provide information on the crystallinity of the materials for unirradiated and irradiated samples. The XRD pattern for pure PVA film exhibited one broad peak with 2 = 19.4174, intensity is 1735.25, this means the semi crystalline nature of pure PVA film; this result correspond with the research. The XRD pattern for irradiated pure PVA by Gamma radiation at irradiation dose (3kGy), the intensity that equal (1952.05) and 2 = 19.4005 clear in figure. The XRD pattern for irradiated PVA film shows the intensity is equal (880.56) and 2 = (19.3544). Figure illustrates the XRD pattern for irradiated PVA films by gamma ray at irradiation dose (15kGy). It is clear the intensity is increase with increase irradiation dose. FTIR Characterization The FTIR spectroscopy has real important because it has given the main characteristics peaks of pure PVA. All (FTIR) spectra are taken in transmittance mode. Figure shows the FTIR spectrum for pure PVA polymer. The many bands are listed in the table. The peaks appear between cm -1 refers to C-H out of plane bending. The peak cm -1 refer to C-O stretching vibration is disappear. The peaks appeared at 1328.29 cm -1 and 1373.64 cm -1 refers to C-(CH3) symmetric bending vibration. The peak appeared between cm -1 refers to carbonyl stretching vibration (C=O). The two peaks appeared at 2912.57 cm -1 and 2939.54 cm -1 refer to symmetric and asymmetric CH 3 stretching vibration respectively, the broad band at 3231.73cm -1 refer to O-H hydrogenbonded alcohols. The effect of gamma irradiation to PVA polymer on FTIR spectrum is shown in figure and these bands are listed in the table for different irradiation doses (1, 3, 5, 8, 10 and 15). In irradiation the band at (919 cm -1 ) refer to C-H out phase bend for (15 kGy) is disappear, and the band at cm -1 at irradiation dose (8 kGy), and the band at cm -1 at irradiation doses (5, 8 and 10) kGy respectively refers to C-O stretch are disappeared, and the band at (1328 cm -1 ) refers to CH 2 bending is disappeared at irradiation dose ( 3 kGy), the new peak at (1579.50 cm -1 ) is appeared for PVA-pure refer to the C=O stretch irradiation dose 8 kGy. The peaks appeared between cm -1 refer to stretch aliphatic. The broad band between cm -1 refers to O-H hydrogen-bonded alcohols. The FT-IR analysis of PVA polymer after exposure to gamma irradiation showed approximately the same spectrum for pure polymer, before irradiation with no shift in the peak positions. These findings suggest that gamma irradiation did not cause structural changes in the polymer chains. FESEM Results The FESEM image for un-irradiated PVA films show in the figure, the surface is rough until after irradiation dose (3kGy), after irradiation dose (8kGy) the roughness is decreased to that disappear at irradiation dose (15kGy). Conclusions UV-VIS spectrophotometric studies optical properties for irradiated pure PVA films with different irradiation doses, gamma ray lead to degradation in polymer chains, and indirect bandgap increase with increase irradiation dose, and each optical constants have changed value after irradiation. The XRD show the polymer (PVA) is semi crystalline and the intensity is increase with increase irradiation dose, FTIR spectrophotometric studied the effect of irradiation on the chemical bond of the materials, we show the irradiation doesn't effect on the bond of polymer, but FESEM results show the polymer surface is rough, and it is continuously reduces irradiation until it disappear. |
Reliable methods to study some nonlinear conformable systems in shallow water In this paper, consider the eminent coupled BoussinesqBurger (BB) equations and the coupled WhithamBroerKaup (WBK) equations with time fractional derivative arising in the investigation of shallow water waves. The derivative is described in the sense of conformable derivative. We introduce the fundamental (G/G)-expansion method and its extension, namely the two-variable (G/G, 1/G)-expansion method, to establish general solutions, some typical wave solutions existing in the literature, and some new and compatible soliton solutions comprised with certain parameters. For the definite values of these parameters, we derive and show in figures the well-known kink, singular kink, bell-shape soliton, periodic soliton, cuspon, and so on. The obtained solutions affirm that the introduced methods are reliable and efficient techniques to examine a wide variety of nonlinear fractional systems in the sense conformable derivative. Introduction Although the concept of fractional derivative is as old as that of the classical one, its advancement is not so old. Though relatively new, its use is increasing day by day due to its advantages in modeling and widespread applications to real-world problems, and thus it has generated much interest among researchers. There are many physical phenomena and processes, such as anomalous diffusion processes in physics, chemistry, and biology, complex diffusion process, diffusion in heterogeneous medium, diffusion processes in porous medium, viscoelasticity, viscoelastic deformation, viscous fluid, groundwater investigations, and so on, which can be analyzed more accurately through fractional differential equations than through integer-order differential equations. Fractional differential and integral operators have eliminated the drawback of classical integer-order difficulties considering their nonlocal characteristics. There are different definitions of fractional derivatives and integrals, such as variable-order fractional derivative, Riemann-Liouville fractional derivative, Jumarie fractional derivative, Caputo fractional derivative, Weyl fractional derivative, and so on. To describe anomalous diffusion phenomena, constant-order fractional diffusion equations are introduced and have had great success. On the contrary, to characterize some complex diffusion processes, for instance, diffusion processes in heterogeneous medium and diffusion processes in porous medium, if the medium structure or external field changes with time, then the variable-order fractional diffusion equations properly model the incidents. The Riemann-Liouville and Jumarie derivatives are recognized as a powerful modeling approach in the fields of viscoelasticity, viscoelastic deformation, viscous fluid, anomalous diffusion, and so on. The problem in groundwater investigation can be better analyzed by the Weyl fractional-order derivative. The Caputo-type fractional derivative is useful in investigating numerical solutions of a model equation. Therefore, in the recent years, fractional calculus has become an emerging and interesting branch of applied mathematics and analysis. The exact traveling solutions to the coupled BB equation have been established in. By using the Lie symmetry analysis Mhlanga and Khalique described the traveling wave solutions to the generalized coupled BB equation. The envelope soliton and periodic wave solutions have been studied by Ebadi et al.. The coupled WBK equations are examined by other researchers using different analytical and numerical methods, such as the exp-function method, the Adomian decomposition method, the (G /G 2 )-expansion method, the hyperbolic function method, the Lie symmetry analysis, the differential transformation method, the homotopy analysis method, and so on. Recently, Amjad et al. used the result of a standard order coupled fractional-order Whitham-Broer-Kaup equation by the Laplace decomposition method. To the best of our knowledge, the coupled Boussinesq-Burger and Whitham-Broer-Kaup nonlinear fractional differential equations have not been examined through the (G /G)-expansion method and the (G /G, 1/G)-expansion method. Therefore, motivated by the studies mentioned, the objective of our study is to extract general solutions, some classical wave solutions, and some compatible soliton solutions entangled with parameters to the equations mentioned. When we set definite values of the parameters, bell-shape soliton, kink, periodic, and other solitary wave solutions are originated from the broad-ranging general solution. The rest of the paper is arranged as follows: In Sect. 2, we present the properties of the conformable derivative. In Sect. 3, we present the basic idea of the (G /G)-expansion method. In Sect. 4, we give the algorithm of the (G /G, 1/G)-expansion method. In Sect. 5, we implement the methods to extract soliton solutions to the coupled BB and coupled WBK systems of time-fractional order. In Sect. 6, we provide a physical explanation and graphs of the solutions. In Sect. 7, we present conclusions. The algorithm of the (G /G)-expansion method for FNDEs Consider an FNDE of the form where F is a polynomial of v and fractional partial derivatives of s, and v = v(x, t) is an unidentified function to be computed. By using the wave transformation where w is the wave velocity, and k is the wave number, both nonzero constants, the FNDE (3.1) can be rewritten as the following ordinary differential equation (ODE): Assume that Eq. (3.3) has the formal solution where i (i = 0, 1,..., N ) are constants, and the function G( ) satisfies the auxiliary equation The constant N in Eq. (3.4) can be determined by balancing the highest-order derivatives and nonlinear terms turn up in Eq. (3.3). Substituting solution (3.4) into (3.3), using (3.5), summing up all terms of the same order of (G /G), and setting the coefficients to zero yield a system of algebraic equations for i (i = 0, 1,..., N ), k, w,, and. We obtain the values of constants i (i = 0, 1,..., N ), k, w,, and by unraveling this system, and substituting these constants and the general solutions of (3.5) into solution (3.4), we attain adequate travelling wave solutions to the FNDE (3.1). Description of the (G /G, 1/G)-expansion method for FNDEs In this section, we interpret the (G /G, 1/G)-expansion method as follows. For the auxiliary differential equation Thus from (4.1) and (4.2) we can derive The solutions of Eq. (4.1) are subject to the following three cases. Case 1: If < 0, then the formal solution of Eq. (4.1) is (4.4) and the corresponding relation is where = A 2 1 -A 2 2. Case 2: If > 0, then the standard solution of Eq. (4.1) is Thus the relation between and is where = A 2 1 + A 2 2. Case 3: If = 0, then the typical solution of Eq. (4.1) is 8) and the relations between and is where A 1, A 2 are integral constants. The major steps of the (G /G, 1/G)-expansion method are described as follows. Step 1: We assume that Eq. (3.3) has the general solution where G is the solution of the auxiliary Eq. Step 2: Substituting (4.10) into (3.3) with (4.3) and (4.5), we obtain a polynomial in and, where the degree of is not greater than one. Setting all coefficients of the polynomial to zero yields a set of algebraic equations, which can be solved with the help of Maple software package, and substituting the values of k, w,,, i, i into (4.10), we get analytical exact solutions to Eq. (3.3) expressed by the hyperbolic function. Extraction of soliton solutions In this section, we extract the traveling wave, including periodic, kink, bell-shape soliton, and so on wave solutions to the following fractional systems utilizing the methods described in Sects. 3 and 4. First, we consider the model based on the nonlinear time fractional coupled BB equations : where u(x, t) represents the horizontal velocity field, and v(x, t) indicates the water surface height above a horizontal level from the bottom. Second, we consider a model based on the nonlinear time fractional coupled WBK equations : where the constants b and c represent the coefficients of diffusion and dissipation, respectively, u(x, t) represents the horizontal field of horizontal velocity, and v(x, t) indicates the height of deviation from the liquid equilibrium position. The time-fractional coupled BB equations For the time-fractional coupled BB equations, we put the wave transformation We will take the advantage of fractional wave transformation to turn system (5.1) into the ODEs: By integrating we obtain where c 1 and c 2 are integrating constants. Balancing between V and U 2, U, and UV in (5.5), we find N 1 = 1 and N 2 = 2. Therefore the formal solutions of (5.5) can be presented by a polynomial in (G /G): Embedding (5.6) into (5.5) and applying the procedure stated in Sect. 3, we get the following result: where w is an arbitrary constant. By means of the values assembled in (5.7) and the general solutions of (3.5), from solution (5.6) we accomplish three types of solitary wave solutions to the coupled BB Eq. (5.1) as follows. Type I: When ( 2 -4) > 0, we attain the hyperbolic function solutions of (5.1): where = xw t. Solution (5.8) is the general hyperbolic type of the coupled BB equation, from which different compact-form solutions can be extracted for definite values of the integral constants. For B 1 = 0, B 2 = 0, we get the squeezed bell-shape and kink-type solitary wave solutions to the coupled BB Eqs. (5.1): On the other hand, if we put B 2 = 0, B 1 = 0, we gain singular solitary wave solutions of (5.1): Again, if we set B 2 = 0, B 2 2 > B 2 1, we accomplish the solitary wave solutions of (5.1): we attain the singular solitary wave solutions of (5.1): where 0 = tanh -1 B 2 B 1. Type II: When ( 2 -4) < 0, we derive the trigonometric function solutions of (5.1): Since B 1 and B 2 are integral constants; someone is able to accept their values spontaneously. Therefore, if we accept B 1 = 0, B 2 = 0, we attain the subsequent singular periodic wave solutions to the nonlinear coupled Boussinesq-Burger equations: (5.14) Furthermore, if we accept B 2 = 0, B 1 = 0, then we determine the following singular periodic wave solutions to the nonlinear coupled BB equations: However, if B 2 = 0, B 2 2 > B 2 1, then we obtain the singular periodic wave solutions of (5.1) as follows:, then we attain the periodic wave solutions of (5.1) as follows: where 0 = tan -1 B 2 B 1. Type III: When ( 2 -4) = 0, we ensure the subsequent rational function solutions of (5.1): wherein B 1 could be zero, but B 2 cannot be zero; otherwise, solution (5.18) would turn into steady solution, which has no physical significance. Now we use the two-variable (G /G, 1/G)-expansion method to analyze the wave solutions to the coupled BB equation. Accordingly, we look for the solutions in the form where a 0, a 1, b 1, 0, 1, 2, 1, and 2 are constants to be determined. As we mentioned in Sect. 4, we have three cases. Result 1 (5.20) From (4.4), (5.19), and (5.20) with (5.3) we derive the following hyperbolic function solutions of (5.1): Inasmuch as A 1, A 2, and are free parameters, choosing A 1 = 0, = 0, and A 2 > 0, from (5.21) we attain the following solitary wave solutions: Alternatively, choosing A 2 = 0, = 0, and A 1 > 0, we attain the solitary wave solutions In particular, if we set A 1 = 0, = 0, and A 2 > 0 into (5.25), we attain the following solitary wave solutions: On the contrary, if we set A 2 = 0, = 0, and A 1 > 0, we attain the solitary wave solu- From result 3 we gain other hyperbolic function solutions of (5.1): Similarly, if the parameters take distinct values, then we deduce many other solitary wave solutions, but for conciseness, here we do not document the other solutions. Case 2 When > 0, substituting (5.19) into (5.5) and using (4.3), (4.6), and (4.7), system (5.5) can be expressed as a polynomial in and. Vanishing all coefficients from this polynomial, we obtain a system of algebraic equations, which can be solved by utilizing Maple software package to get different results. In particular, by taking A 1 = 0, = 0, and A 2 > 0 in (5.31), we achieve the following periodic wave solutions: whereas for A 2 = 0, = 0, and A 1 > 0, we deduce the periodic wave solutions In particular, if we set A 1 = 0, = 0, and A 2 > 0 into (5.35), then we get the following periodic wave solutions: Moreover, if we set A 2 = 0, = 0, and A 1 > 0, then we find the periodic wave solutions From result, we have other trigonometric function solutions of (5.1): Similarly, By taking special values of the parameters we deduce many other periodic wave solutions. Case 3 When = 0, substituting (5.19) into (5.5), by (4.3), (4.8), and (4.9) system (5.5) can be exposed as a polynomial in and. Equating each coefficient of this polynomial to zero, we obtain a system of algebraic equations, which is analyzed by applying Maple software package, and get the following results: In this case the rational function solutions to the coupled BB (5.1) are: The nonlinear time-fractional coupled WBK equations In this section, we use transformation (5.3) to reduce system (5.2) into the following ODEs: wV -UV -bU + cV + 2 = 0. (5.47) By balancing theory, from V and U 2 and from U and UV appearing in (5.47) we get N = 1 and S = 2. Therefore the formal solutions to Eq. (5.47) are of the following form: Substituting (5.48) into (5.47) and applying the same procedure discussed in Sect. 3, we get the following results: Type I: When ( 2 -4) > 0, we acquire the hyperbolic function solutions of (5.2): where = xw t. Here B 1 and B 2 are integral constants. Therefore we can randomly select their values. Thus, if we select B 1 = 0, B 2 = 0, then we accomplish the kink and bell-shape solitary wave solutions of (5.2) of the form Moreover, if we select B 2 = 0, B 1 = 0, then we obtain the singular solitary wave solutions of (5.2): In addition, if we select B 2 = 0, B 2 2 > B 2 1, then we get the solitary wave solutions of (5.2): where However, if we select B 1 = 0, B 2 1 > B 2 2, then we carry out the solitary wave solutions of (5.2): where 0 = tanh -1 B 2 B 1. Type II. When ( 2 -4) < 0, we get trigonometric function solutions of (5.2) of the form We might accept B 1 = 0, B 2 = 0, Since B 1 and B 2 are integral constants, we find the following periodic wave solutions of (5.2): In addition, if we put B 2 = 0, B 1 = 0, then we find the following the periodic wave solutions of (5.2): Besides, if we set B 2 = 0, B 2 2 > B 2 1, then we achieve the following periodic wave solutions of (5.2): where Additionally, if we set B 1 = 0, B 2 1 > B 2 2, then we achieve the periodic wave solutions of (5.2): where 0 = tan -1 B 2 B 1. Type III: When ( 2 -4) = 0, we find the following rational function solutions of (5.2): Now we examine the coupled WBK equations by means of the (G /G, 1/G)-expansion method. For the balance number attained in the earlier section for this equation, the shape of the solution is of the form where a 0, a 1, b 1, 0, 1, 2, 1, and 2 are constants to be determined. Now we take into account the following three cases. In particular, by taking A 1 = 0 and A 2 = 0 in (5.63), we attain the following solitary wave solution: (5.64) When A 2 = 0 and A 1 = 0, we obtain the previously mentioned wave solutions a 1c), where = xw t. In particular, if we substitute A 1 = 0, = 0, and A 2 > 0 into (5.67), we get the following wave solutions: (5.68) On the other hand, if we introduce A 2 = 0, = 0, and A 1 > 0, then we get the following wave solutions: For the values of the parameters organized in (5.70), we carry out other hyperbolic function solutions of (5.2) given in the underneath: where = xw t. Similarly, by taking special values of the parameters we might attain many other solitary wave solutions, but for simplicity, the solutions are not designated here. Case 2: When > 0, in this case, solving the system of algebraic equations with Maple software package, we obtain three different sets of results. Conclusion By means of the basic (G /G)-expansion method and the two-variable (G /G, 1/G)expansion method, in this study, we have ascertained further general solitary wave solutions to the time-fractional coupled Boussinesq-Burger equations and the coupled Whitham-Broer-Kaup system as a linear combination of the exponential, rational, and hyperbolic functions or separately including several free parameters. For definite values of the associated parameters, some well-known solutions are extracted from the broadranging solutions, which are available in the literature, and some fresh solutions are de- Modulus plot of solution (5.64) which is a bell-shape soliton rived, which confirm the correctness and validity of the general solutions and the method. We have exposed the graphical representations and discussed the physical significance of the obtained solutions. Every nonlinear equation is distinct and atypical; therefore not all equations can be examined through a single method. The greater the scope of application of a method, the greater the acceptability of that method. Since this study shows that the introduced methods are straightforward, compatible, and powerful mathematical tools for obtaining abundant traveling wave solutions, to test the range of applicability and consistency, the method can be implemented to other types of nonlinear fractional differential systems to analyze closed-form soliton solutions, and this is the concern of further research. Numerical solutions to these equations can also be explored in the future by following the effective schemes discussed in. |
package com.rakesh.eventbus.models;
public class DefaultPayment extends PaymentItem {
public DefaultPayment(Long amount) {
super(amount);
}
@Override
public String toString() {
return "Received default payment method of amount " + super.toString();
}
}
|
A Phase I, pharmacokinetic (PK) and pharmacodynamic (PD) study of a novel histone deacetylase inhibitor LAQ824 in patients with hematologic malignancies. 3024 Background: LAQ824 is a novel cinnamic acid hydroxamate that inhibits HDAC activity, IC50 of 0.03 M, and acetylates hsp90 thereby inducing proteosomal degradation of Bcr-Abl and her-2. METHODS LAQ824 is administered by a 3 hr IV infusion on days 1-3 of a 21 day cycle to pts with ALL, AML, CLL, CML in blast crisis or advanced MDS. Modified continuous reassessment method (MCRM) was utilized for dose escalation. RESULTS 21 pts (median age: 68 yrs; 14 M, 7 F) with AML (15 pts), MDS (4 pts) and CLL (2 pts) have been treated at dose levels (mg/m2): 6 (2 pts); 12 (3 pts); 24 (3 pts); 36 (4 pts); 54 (4 pts); 80 (5 pts). One patient experienced DLT, at the 54 mg/m2 dose level, (cerebral bleed secondary to thrombocytopenia in a CLL patient with rapid disease progression). Grade 2 hyperbilirubinemia was seen in 6 pts. but was rapidly reversible (generally in < 1 week). Monitoring with > 400 ECGs, demonstrates no QTc prolongation. One patient with de novo M1 AML achieved a CR after 2 cycles, and remains in CR after 6 cycles. Six patients had stable disease (5 pts, 4 AML, 1 MDS) or hematologic improvement (1 pt, MDS). PD study for increased histone acetylation (HA) in peripheral lymphocytes was seen on days of dosing ≥ 12 mg/m2, and at ≥ 36 mg/m2 was present for 24 hours after the last dose. PK in 15 pts receiving LAQ824 over a dose range of 6-54 mg/m2 were evaluated by noncompartmental analysis. Plasma LAQ824 concentrations were determined using HPLC/MS/MS assay. Exposure (AUC) increased proportionally with increasing dose. The mean AUCs were 165.4 and 1816.8 ng.h/mL, respectively, for 6 and 54 mg/m2 on Day 1. The mean terminal half-lives ranged from 9 to 18 hr. Comparison of AUC between Day 3 and Day 1 indicated a 1.5 fold drug accumulation. Maximum plasma concentrations (Cmax) were observed at 1.5 h after the beginning of infusion, not at the end of infusion, in more than 50% of patients, indicating a non-linear PK. CONCLUSIONS LAQ824 is a novel HDAC inhibitor which is well tolerated, exhibits dose dependent PD effects, and has shown evidence of clinical activity in hematologic malignancies. Further dose escalation is in progress. . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.