content
stringlengths
10
4.9M
<gh_stars>1-10 #include "Modules/UI/Macro Elements/PauseMenu.h" #include "Engine.h" PauseMenu::PauseMenu(Engine& engine) : Menu(engine) { // Title m_title->setText("PAUSE MENU"); // Add 'Start Game' button addButton(engine, "RESUME", [&] { resume(); }); // Add 'Options' button m_optionsMenu = std::make_shared<OptionsMenu>(engine); addButton(engine, " OPTIONS >", [&] { goToOptions(); }); m_optionsMenu->addCallback(static_cast<int>(OptionsMenu::Interact::on_back), [&]() noexcept { returnFromOptions(); }); // Add 'Quit' button addButton(engine, "END GAME", [&] { quit(); }); // Callbacks addCallback(static_cast<int>(UI_Element::Interact::on_resize), [&] { const auto scale = getScale(); m_optionsMenu->setScale(scale); }); // Populate Focus Map m_focusMap = std::make_shared<FocusMap>(); m_focusMap->addElement(m_layout); engine.getModule_UI().setFocusMap(getFocusMap()); } void PauseMenu::resume() { enactCallback(static_cast<int>(PauseMenu::Interact::on_resume_game)); } void PauseMenu::goToOptions() { // Transfer appearance and control to options menu auto& ui = m_engine.getModule_UI(); ui.pushRootElement(m_optionsMenu); ui.setFocusMap(m_optionsMenu->getFocusMap()); m_layout->setSelectionIndex(-1); enactCallback(static_cast<int>(PauseMenu::Interact::on_options)); } void PauseMenu::returnFromOptions() noexcept { // Transfer control back to this menu m_engine.getModule_UI().setFocusMap(getFocusMap()); } void PauseMenu::quit() { m_engine.getModule_UI().clear(); enactCallback(static_cast<int>(PauseMenu::Interact::on_end)); }
package com.quewelcy.omnios.view.mono; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.util.AttributeSet; import com.quewelcy.omnios.view.CircledIcon; public class BookIcon extends CircledIcon { private final Paint mPaint1 = new Paint(); private final Paint mPaint2 = new Paint(); private final Paint mPaint3 = new Paint(); private final Paint mPaint4 = new Paint(); private final Path mPath1 = new Path(); private final Path mPath2 = new Path(); private final Path mPath3 = new Path(); private final Path mPath4 = new Path(); public BookIcon(Context context) { super(context); create(); } public BookIcon(Context context, AttributeSet attrs) { super(context, attrs); create(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawPath(mPath1, mPaint1); canvas.drawPath(mPath3, mPaint3); canvas.drawPath(mPath2, mPaint2); canvas.drawPath(mPath4, mPaint4); } @Override protected void create() { super.create(); mPaint1.setStyle(Style.FILL); mPaint1.setDither(true); mPaint1.setAntiAlias(true); mPaint1.setColor(0xFFFFC107); mPaint2.setStyle(Style.FILL); mPaint2.setDither(true); mPaint2.setAntiAlias(true); mPaint2.setColor(0xFFFFB300); mPaint3.setStyle(Style.FILL); mPaint3.setDither(true); mPaint3.setAntiAlias(true); mPaint3.setColor(0xFFEEFF41); mPaint4.setStyle(Style.FILL); mPaint4.setDither(true); mPaint4.setAntiAlias(true); mPaint4.setColor(0xFFFDD835); buildPath(); } @Override protected void buildPath() { super.buildPath(); int w = getWidth(); int h = getHeight(); if (w <= 0 || h <= 0) { return; } mPath1.reset(); mPath1.moveTo(0.3f * w, 0.15f * h); mPath1.lineTo(0.7f * w, 0.15f * h); mPath1.lineTo(0.7f * w, 0.85f * h); mPath1.lineTo(0.5f * w, 0.7f * h); mPath1.lineTo(0.3f * w, 0.85f * h); mPath1.lineTo(0.3f * w, 0.15f * h); mPath2.reset(); mPath2.moveTo(0.3f * w, 0.15f * h); mPath2.lineTo(0.7f * w, 0.15f * h); mPath2.lineTo(0.3f * w, 0.4f * h); mPath2.lineTo(0.3f * w, 0.15f * h); mPath3.reset(); mPath3.moveTo(0.3f * w, 0.15f * h); mPath3.lineTo(0.4f * w, 0.15f * h); mPath3.lineTo(0.7f * w, 0.5f * h); mPath3.lineTo(0.3f * w, 0.3f * h); mPath3.lineTo(0.3f * w, 0.15f * h); mPath4.reset(); mPath4.moveTo(0.3f * w, 0.6f * h); mPath4.lineTo(0.7f * w, 0.45f * h); mPath4.lineTo(0.7f * w, 0.6f * h); mPath4.lineTo(0.3f * w, 0.85f * h); mPath4.lineTo(0.3f * w, 0.7f * h); } }
<filename>pkg/config/config.go package config import ( "github.com/oschwald/geoip2-golang" "gopkg.in/yaml.v2" "io/ioutil" ) var ( ConfigMap map[string]interface{} ConfigLocation *string GeoLiteDBLocation *string Port *int Debug *bool ListenAddress *string GeoDB *geoip2.Reader ) func FetchConfigMap(c *string) { var configFile, err = ioutil.ReadFile(*c) if err != nil { panic(err) } yaml.Unmarshal([]byte(configFile), &ConfigMap) } func FetchDomain(configMap map[string]interface{}) (domainList []string) { for domain := range configMap { if domain != "regions" { domainList = append(domainList, domain) } } return domainList }
// Copyright (c) <NAME>. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifndef _BLE_LIMITS_H_ #define _BLE_LIMITS_H_ #include <stdlib.h> #ifndef __AVR__ #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #endif #if defined(NRF51) || defined(__RFduino__) #define BLE_ADVERTISEMENT_DATA_MAX_VALUE_LENGTH 26 #define BLE_SCAN_DATA_MAX_VALUE_LENGTH 29 #define BLE_EIR_DATA_MAX_VALUE_LENGTH 29 #define BLE_ATTRIBUTE_MAX_VALUE_LENGTH 20 #define BLE_REMOTE_ATTRIBUTE_MAX_VALUE_LENGTH 22 #else #define BLE_ADVERTISEMENT_DATA_MAX_VALUE_LENGTH 20 #define BLE_SCAN_DATA_MAX_VALUE_LENGTH 20 #define BLE_EIR_DATA_MAX_VALUE_LENGTH 20 #define BLE_ATTRIBUTE_MAX_VALUE_LENGTH 20 #define BLE_REMOTE_ATTRIBUTE_MAX_VALUE_LENGTH 22 #endif #endif
def generate_unit_vectors(n, sigma= 2*np.pi): phi = np.random.uniform(0, sigma, (n, n)) v = np.stack((np.cos(phi), np.sin(phi)), axis=-1) return v
<reponame>nicolasff/river #include <stdlib.h> #include <stdio.h> #include <syslog.h> #include <string.h> #include "server.h" #include "socket.h" #include "channel.h" #include "conf.h" #include "mem.h" int main(int argc, char *argv[]) { struct conf *cfg; if(argc == 2) { cfg = conf_read(argv[1]); } else { cfg = conf_read("river.conf"); } if(!cfg) { fprintf(stderr, "Could not read config file.\n"); return EXIT_FAILURE; } char *s = rmalloc(11); memcpy(s, "0123456789", 10); rfree(s); /* initialize syslog */ openlog(cfg->log_file, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER); int fd = socket_setup(cfg->ip, cfg->port); channel_init(); server_run(fd, cfg->max_connections); printf("bye\n"); return EXIT_SUCCESS; }
def guess_num_nodes_from(edgelist): return np.max(edgelist) + 1
n = int(input()) *a,=map(int, input().split()) from collections import defaultdict da=defaultdict(int) for i in a: da[i]+=1 q = int(input()) suma=sum(a) for i in range(q): b,c=map(int, input().split()) numb=da[b] suma+=(c-b)*numb da[c]+=numb da[b]=0 print(suma)
def collect_reducer(method): method = replace_default_method(method) try: return globals()['collect_reducer_{}'.format(method)] except KeyError: raise ValueError( "Unknown collection method {}".format(method))
Pulsed Radiofrequency Applied to the Sciatic Nerve Improves Neuropathic Pain by Down-regulating The Expression of Calcitonin Gene-related Peptide in the Dorsal Root Ganglion Background: Clinical studies have shown that applying pulsed radiofrequency (PRF) to the neural stem could relieve neuropathic pain (NP), albeit through an unclear analgesic mechanism. And animal experiments have indicated that calcitonin gene-related peptide (CGRP) expressed in the dorsal root ganglion (DRG) is involved in generating and maintaining NP. In this case, it is uncertain whether PRF plays an analgesic role by affecting CGRP expression in DRG. Methods: Rats were randomly divided into four groups: Groups A, B, C, and D. In Groups C and D, the right sciatic nerve was ligated to establish the CCI model, while in Groups A and B, the sciatic nerve was isolated without ligation. After 14 days, the right sciatic nerve in Groups B and D re-exposed and was treated with PRF on the ligation site. Thermal withdrawal latency (TWL) and hindpaw withdrawal threshold (HWT) were measured before PRF treatment (Day 0) as well as after 2, 4, 8, and 14 days of treatment. At the same time points of the behavioral tests, the right L4-L6 DRG was sampled and analyzed for CGRP expression using RT-qPCR and an enzyme-linked immunosorbent assay (ELISA). Results: Fourteen days after sciatic nerve ligation, rats in Groups C and D had a shortened TWL (P<0.001) and a reduced HWT (P<0.001) compared to those in Groups A and B. After PRF treatment, the TWL of the rats in Group D gradually extended with HWT increasing progressively. Prior to PRF treatment (Day 0), CGRP mRNA expressions in the L4-L6 DRG of Groups C and D increased significantly (P<0.001) and were 2.7 and 2.6 times that of Group A respectively. ELISA results showed that the CGRP content of Groups C and D significantly increased in comparison with that of Groups A and B (P<0.01). After PRF treatment, the mRNA expression in the DRG of Group D gradually decreased and the mRNA expression was 1.7 times that of Group A on the 4th day(P> 0.05). On the 8th and 14th days, the mRNA levels in Group D were restored to those of Groups A and B. Meanwhile, the CGRP content of Group D gradually dropped over time, from 76.4 pg/mg (Day 0) to 57.5 pg/mg (Day 14). Conclusions: In this study, we found that, after sciatic nerve ligation, rats exhibited apparent hyperalgesia and allodynia, and CGRP mRNA and CGRP contents in the L4-L6 DRG increased significantly. Through lowering CGRP expression in the DRG, PRF treatment might relieve the pain behaviors of NP. Introduction Neuropathic pain (NP) has been recently redefined by the Neuropathic Pain Special Interest Group (NeuPSIG) as pain arising as a direct consequence of a lesion or disease affecting the somatosensory system . Although there have been progresses in several studies on its mechanism and Ivyspring International Publisher treatment, NP remains a type of pain which is clinically refractory. Pulsed radiofrequency (PRF) is a minimally invasive technique and differs from continuous radiofrequency (CRF) in several aspects. The radiofrequency current emitted in PRF has an interim period of 480 msec following each 20 msec emission, which allows heat to disperse to the surrounding tissues so that the temperature of the therapy target site will not exceed 42 ℃ through which it could avoid a series of side effects caused by irreversible nerve damage in the case of CRF . Since its invention, PRF has been proven by an array of clinical studies in treating kinds of NP, including postherpetic neuralgia , painful diabetic neuropathy , trigeminal neuralgia , etc. Animal experiments have confirmed that PRF can perform actively in treating allodynia and hyperpathia in rat NP models , albeit through an unclear analgesic mechanism. Some researchers have speculated that PRF played an analgesic role via thermal effects. However, studies applying PRF to the dorsal root ganglion (DRG) or sciatic nerve have not demonstrated the irreversible effect of thermal damage . In fact, more studies support the biological effects of PRF rather than its thermal effects. Calcitonin gene-related peptide (CGRP) is a neuropeptide consisting of 37 amino acid residues and it exists in humans and rats in two different CGRP subtypes: CGRPα and CGRPβ respectively. CGRPα is mainly produced in the central and peripheral nervous systems, especially in the DRG, trigeminal ganglion and so on. The primary sensory fibers in the DRG project to laminae I and II of the spinal dorsal horn, the majority of which are pain-conducting Aδ and C fibers . At the spinal cord level, CGRP plays an important role in chronic pain through facilitating the introduction of synaptic pain information via both protein-kinase-A along with protein-kinase-C second-messenger pathways and participating in the generation and maintenance of allodynia as well as hyperpathia . Studies have revealed that applying PRF to the peripheral nerve of normal rats can reduce the proportion of CGRP-positive neurons in the DRG , which suggests that PRF may control the pain symptoms of NP by affecting CGRP expression in the pain transduction pathway. In this study, we employed a rat chronic constriction injury (CCI) model to simulate NP. And we applied PRF to the oppressed portion of the rat sciatic nerve to investigate the pain behaviors at multiple time points before and after PRF treatment and to examine CGRP mRNA and CGRP levels in the L4-L6 DRG, thereby elucidating the possible mechanism of analgesic effect of PRF. Methods All procedures on animals were approved by the Beijing Neurosurgical Institute Experimental Animal Welfare Ethics Committee. The 4-month-old adult male Sprague-Dawley rats (220-250 g) used in this experiment were provided by Vital River Laboratories, Beijing and were raised in a 12-hour light-dark alternation environment at 22-24 ℃. One hundred and twenty rats were randomly divided into four groups and were treated as follows: Group A (n=30): sham-CCI and sham-PRF, in which the right sciatic nerve was exposed, without nerve ligation. Fourteen days after the surgery, the right sciatic nerve was exposed again. A trocar with an electrode needle used for PRF treatment was placed at the sciatic nerve, without applying a pulse RF current. Group B (n=30): sham-CCI and PRF, in which the right sciatic nerve was exposed, without nerve ligation. Fourteen days after the surgery, the right sciatic nerve was re-exposed and treated with PRF. Group C (n=30): CCI procedure and sham-PRF, in which the right sciatic nerve was exposed and ligated to create the CCI model. Fourteen days after the surgery, the right sciatic nerve was once again exposed. A trocar with an electrode needle used for PRF treatment was placed at the sciatic nerve, without applying a pulse RF current. Group D (n=30): CCI procedure and PRF procedure, in which the right sciatic nerve was exposed and ligated to create the CCI model. Fourteen days after the surgery, with the exposure of the right sciatic nerve, PRF treatment was conducted. Fourteen days after the sciatic nerve ligation surgery, each group was subjected to pain behavioral tests before (Day 0) and after 2, 4, 8, and 14 days of PRF treatment. Following the same time points of the behavioral tests, the rats were sacrificed, and the right L4-L6 DRG was sampled to analyze the CGRP mRNA expression and neuropeptide content. Sciatic nerve CCI model The CCI model was established on the basis of the method from Bennett and Xie . After being anesthetized via intraperitoneal injection of sodium pentobarbital (40mg/kg), the rat's sciatic nerve was exposed, and then ligated in four strips with 1-mm spacing using 4/0 chromium catgut, and just not to block the surface vessel of the sciatic nerve is the most appropriate. The wound was closed in layers and cleaned. PRF Fourteen days after the surgery, PRF treatment was performed. The rat's right sciatic nerve was once again exposed, and the trocar (PMF-21-50-2, Baylis, Canada) and electrode needle (PMK-21-50, Baylis, Canada) for PRF treatment were placed vertically at where the sciatic nerve was ligated and after that connected to a PRF generator (PMG-230, Baylis Medical, Inc., Montreal, Canada). The settings were a pulse emission frequency of 2 Hz, a voltage of 45 V, a treatment period of 120 seconds and with the temperature less than 42 ℃. While rats under the sham-PRF treatment took a trocar with electrode needle but no PRF current. Behavioral tests Rats in each group (n=6) were subjected to pain behavioral tests before PRF treatment (Day 0) and after 2, 4, 8, and 14 days of treatment respectively. Thermal withdrawal latency (TWL) and hindpaw withdrawal threshold (HWT) were used to measure the thermal pain threshold and mechanical pain threshold of the rat's right hind paw. TWL In accordance with the methodology of Hargreaves et al , the rats were placed in a bottomless cage made of a plexiglass plate. The mobile radiant heat source of the Plantar Test Instrument (Ugo Basile 37370) which was located under a quartz glass plate would be aligned to the surface of the third metatarsal bone of rats' hind paw. The instrument automatically recorded the duration from the start of radiation to the emergence of the escape reflex, i.e., TWL (sec). The measurements were repeated thrice in 10-min intervals at the same spot, and later averaged. The maximum heat exposure time was set within 22.5 seconds, to avoid burns to the rat's plantar surface. HWT In line with the research of Vivancos et al , absolute withdrawal thresholds were measured by an electronic von Frey apparatus (Electronic von Frey Anesthesiometer 2390, IITC, Inc.). The rat was placed in an experimental cage with a perforated metal sheet (mesh size 0.5 * 0.5 cm) and the measurement commenced after 10-15 minutes. The non-footpad area of the rat's middle plantar was stimulated by an electronic von Frey rigid tip through the mesh bottom, and the stimulated spots were the same as those in the case of TWL. The operator gradually increased the pressure to induce the foot withdrawal response in the rat, in which the maximum strength (g) was recorded by the instrument. The rat would be placed on the cage for 10-15minutes before commencing the measurement. CGRP expression Before PRF treatment (Day 0) and on the second, fourth, eighth and fourteenth day after the treatment, the right L4-L6 DRG of the rats (n=6/group/time point) was quickly excised after anesthesia and rinsed with saline to remove excess tissue and blood. All operations were conducted at 0-4 ℃, and the sampled tissue specimens were stored immediately in liquid nitrogen for later RT-qPCR or enzyme-linked immunosorbent assay (ELISA) analysis. RT-qPCR The sample was homogenized, from which total RNA was extracted using the Trizol reagent (Invitrogen, Carlsbad, CA) and quantified through light absorption at 260 nm. The first strand cDNA was obtained through reverse transcription using the ProtoScript ™ First Strand cDNA Synthesis Kit (NEB, USA) according to the manufacturer's instruction. The CGRP primer sequences are listed in Table 1, with β-actin as the reference gene. CGRP mRNA expression levels in the sample tissues were detected with the cDNA as the template using the fluorescent quantitative PCR method and the Fast SYBR Green Master Mix qPCR kit (Thermo Fisher Scientific, USA) on the ABI StepOnePlus ™ System (ABI, USA). The reaction conditions referred to the user's manuals of the StepOnePlus ™ System and the Fast SYBR Green Master Mix qPCR kit. Each sample was made into three aliquots and subjected to RT-qPCR with averaged the result made. The resultant quantification cycle (Cq) was adopted to calculate the relative amount of CGRP mRNA expression by aid of the 2 -ΔΔCT method and β-actin as the reference. ELISA quantification of CGRP The specimens were collected as described above, after which accurately weighed and homogenized. The homogenized sample was centrifuged with the supernatant collected, from which the CGRP content in the L4-L6 DRG was analyzed. The experiment stuck to the manufacturer's instructions for the ELISA kit (Elabscience Biotechnology Co, Ltd., Wuhan, China). Absorbance at 450 nm was measured through a microplate reader, and a standard curve was generated. The CGRP content of the sample was calculated based on this. Statistical Analysis All the data were presented as the mean±SEM and analyzed with SPSS 20.0. For behavioral test data, two-way repeated measures ANOVA was used, and the Bonferroni post-test for inter-group comparisons. RT-qPCR results of each time point were analyzed in single-factor ANOVA, and the SNK method was utilized for pair-wise inter-group comparisons. ELISA results were analyzed using two-factor ANOVA, whereas the Bonferroni post-test was in use for inter-group comparisons. P<0.05 was set as the significance level of the tests. Behavioral tests TWL Fourteen days after sciatic nerve ligation, while before PRF treatment (Day 0), the TWLs of Groups C and D were significantly shortened compared to those of Groups A and B (P<0.001), whereas there was no significant TWL difference between Groups A and B and so was the situation between Groups C and D. Four days after PRF treatment, the average TWL of Group D rose from 7.0 to 11.1 seconds, being significantly extended compared to that of Group C (P<0.01). On the 8 th and 14 th days after PRF treatment, the average TWLs of Group D returned to 12.6 seconds and 14.7 seconds respectively, being insignificantly different from those of Groups A and B but significantly longer than the average TWLs of Group C (P<0.001). At each time point, the average TWLs of Group C were always distinctly lower than those of Group A or Group B (P<0.001). (Figure 1) HWT The trend of how HWT changed in each group was similar to that of the TWL in each group. Before PRF treatment, the average HWTs of Groups C and D were overtly lower than those of Groups A and B (P<0.001), whereas the average HWT differences between Groups A and B as well as between Groups C and D were marginal. On the 4 th day after PRF treatment, rats in Group D recovered to 50.4 g, which was apparently higher than that in Group C (P<0.05) but still not reaching the levels in Group A (P<0.05). On the 8 th day and 14 th day after PRF treatment, the HWTs of Group D further recovered but there was no significant difference from those of Groups A and B. (Figure 2) RT-qPCR Fourteen days after sciatic nerve ligation and before PRF treatment (Day 0), the CGRP mRNA expression in the DRG of Groups C and D significantly increased (P<0.001) and was 2.7 times and 2.6 times respectively while the level of CGRP mRNA expression in the DRG of Group A. there were no differences between Groups C and D. After PRF treatment, the mRNA expression in the DRG of Group D decreased gradually, and on the 4 th day, it was 1.7 times that of Group A, albeit an insignificant difference (P> 0.05). On the 8 th and 14 th days, the mRNA levels in Group D were restored to levels of Groups A and B. (Figure 3) ELISA On Day 0, the CGRP contents in the L4-L6 DRG of Groups A and B were significantly increased compared with those in Groups C and D (P<0.01). After PRF treatment, the CGRP content of Group D decreased from 76.4 pg/mg (Day 0) to 57.5 pg/mg (Day 14). On Day 4, although the CGRP content of Group D was still higher than that of Group A or Group B, the difference was not obvious. On Day 8, the CGRP content of Group D went up again to the level of Group A and B. The CGRP content of Group C was consistently higher than that of Group A or Group B (P<0.001). (Figure 4) PRF performance on the oppressed site of the sciatic nerve improved hyperalgesia and allodynia in the rat CCI model. In this study, the TWLs of rats in Groups C and D were shortened and the HWTs were declined on the 14th day after sciatic nerve ligation indicating the emergence of allodynia and hyperpathia, which proved the successful establishment of the CCI model. The CCI model is a widely used, reliable NP model which can simulate clinical symptoms of human NP such as spontaneous pain, allodynia, and hyperpathia, among others. On the 2 nd day after the application of PRF to the oppressed site of the sciatic nerve stem (Group D), thermal hyperalgesia and mechanical allodynia were only slightly relieved. On the 4 th day, approximately 50% of pain relief was achieved. The pain was mostly relieved on the 8 th day and it was almost completely relieved on the 14 th day. These results are consistent with those in previous studies and confirm that PRF on an oppressed site of a peripheral nerve can gradually and significantly alleviate the hyperalgesia and allodynia of an NP model. Consisting with the time for PRF to take effect on analgesia, i.e. approximately 4 days after PRF treatment of a peripheral nerve in the spared nerve injury (SNI) model reported by Vallejo et al. , it also took four days for PRF treatment of the CCI model to achieve satisfactory effectiveness. Erdine et al. believed that PRF mainly acts on the Aδ and C fibers of the rat's primary afferent nerve fibers and achieves its analgesic effect by interfering with the integrity of incoming nerve impulses. Tun et al. considered that PRF might interfere or block the signal transduction of nerve pathways by causing the separation of myelin in nerve axons and might further cause reversible inhibition of nerve cell synapses. However, our investigation, consistent with most studies, did not show the immediate interfering effect of PRF on the transduction of nerve impulses, suggesting that PRF may function through other analgesic mechanisms. In this study, PRF acted directly on the sciatic nerve stem of the NP model. Currently, clinical PRF targets of NP include peripheral nerve and the DRG, and in both cases, the treatment exhibited satisfactory effectiveness. PRF treatment on peripheral nerve only requires simple operations, has little puncture risk, and can be positioned using ultrasonography instead of radiological imaging equipment, such as X-rays, CT, etc., thus having certain advantages. However, when PRF acts on the peripheral nerve or DRG of NP, which approach improves better efficacy is still in dispute. Further in-depth studies will lay the foundation for the clinical practice of PRF treatment on NP. CGRP expression increased in the rat CCI model. In this study, it was found that 14 days after sciatic nerve ligation and after the successful establishment of the rat model (Groups C and D), CGRP mRNA expression in the L4-L6 DRG significantly increased, and the CGRP content was significantly higher than that of Group A or Group B (which had no sciatic nerve ligation). This result is different from that gained by Bennett et al. , who found that the number of small-sized neurons expressing CGRP in the L4 and L5 DRG of the rat CCI model continuously decreased for 2-3 months, and on the 10 th and 20 th days after the establishment of the model, the CGRP content of the nerve injury region of the corresponding spinal dorsal horn decreased by 16% and 19% accordingly. Currently, findings on CGRP changes in the nociception transduction pathway of NP model have been inconsistent. The majority of the studies report that the animal NP models derived from peripheral nerve injury exhibit up-regulated CGRP expression in the DRG or spinal cord and the accumulation of CGRP at the nerve injury site is due to blocked CGRP transport . After peripheral nerve injury, many medium and large DRG neurons begin to express CGRP and play an important role in generating and maintaining pain behaviors . Actions antagonistic to CGRP can ease the pain behaviors . Our findings support there is an increase of CGRP expression in NP rats. The cause of the inconsistent findings in previous studies may be associated with the CGRP detection method (measuring the number of immunologically positive cells or the optical density of positive reaction, etc.) or the applications of different peripheral nerve injury models (SNI model, CCI model, sciatic axotomy, etc.). PRF might play an analgesic role through reducing CGRP expression in the DRG. The RT-qPCR results showed that the relative amount of CGRP mRNA expression in the DRG of Group D began to decline on the 2 nd day after PRF treatment. And on the 4 th day, it was restored to a normal level (showing no difference from Group A). The ELISA results revealed that after PRF treatment, the CGRP content in the DRG of Group D was decreased and then restored to the same level of Group A on the 8 th day. The above-mentioned results indicated that PRF could inhibit the transcription and translation of CGRP in the rat's DRG. At present, no consensus on the analgesic mechanism of PRF has been reached, and it is believed that the mechanism might be related to the influences from a variety of neuropeptides, proteins, and inflammatory factors , which may not be independent of each other. Moreover, what type of connection and which is the core part of the PRF role remain unknown. CGRP is mainly synthesized in the DRG, in which primary sensory neurons project nerve fibers to laminae I and II of the spinal dorsal horn . Once peripheral nerve injury occurs, primary sensory fibers that are projected to the spinal dorsal horn in the DRG release CGRP, P substances, etc., leading to the activation of glial cells, which in turn release various pain regulators such as tumor necrosis factor-α (TNF-α), interleukin-6 (IL-6), and nerve growth factor etc., which are involved in central sensitization . It was hypothesized that PRF treatment disrupts the above-described chain reaction through inhibiting CGRP expression in the DRG, which might be one of the analgesic mechanisms of the treatment. However, what type of role the CGRP mechanism plays in easing NP after PRF treatment and its relationship with other mechanisms still requires further investigation. Limitations Although our study showed that PRF can down-regulate CGRP expression in the DRG of the rat CCI model and reduce pain behaviors, the detailed relationship among PRF, CGRP and pain behaviors still requires further experimental clarifications. For instance, after applying a CGRP antagonist or supplementing CGRP, the role of PRF is monitored. This study examined only the translation and transcription level of CGRP in the DRG. The CGRP expression in other parts of the nociception pathway, such as the dorsal horn of the spinal cord, sciatic nerve, etc., was not investigated. After sciatic nerve ligation, anterograde transport of CGRP to nerve endings from the DRG is blocked, and CGRP accumulated at the ligation site; with the recanalization of nerve on the ligation site, the CGRP accumulation is relieved . Whether PRF directly affects the axial transport of CGRP in peripheral nerve is uncertain, and our experiments did not reveal through which mechanism PRF affects CGRP expression and which physical characteristics of PRF (e.g., the current versus the electrical field) generate the biological effect. The therapeutic effect of PRF may be derived from multiple mechanisms that may intercrossed with each other. Our study did not reveal the connection between the CGRP mechanism and the other PRF analgesic mechanisms reported previously. We observed changes in pain behaviors and CGRP expressions only 14 days after PRF treatment. However, longer follow-up is necessary to ascertain whether PRF has long-term efficacy. Conclusions In this study, we found that after sciatic nerve ligation, rats exhibited apparent hyperalgesia and allodynia and that the CGRP mRNA and CGRP content in the L4-L6 DRG significantly increased. All in all, the research revealed that PRF treatment might relieve NP pain behavioral performances by lowering CGRP expression in the DRG. Abbreviations neuropathic pain: NP; calcitonin gene-related peptide: CGRP; dorsal root ganglion: DRG; Thermal withdrawal latency: TWL; hindpaw withdrawal threshold: HWT; enzyme-linked immunosorbent assay: ELISA; Pulsed radiofrequency: PRF; continuous radiofrequency: CRF; chronic constriction injury model: CCI; spared nerve injury: SNI; tumor necrosis factor-α: TNF-α; interleukin-6: IL-6
/** * TODO * * @author smartloli. * * Created by Jan 1, 2019 */ public class TestIM { public static void main(String[] args) { testAlarmClusterByDingDingMarkDown(); //testAlarmClusterByWeChatMarkDown(); //testConsumerHeathyByWeChat(); } /** New alarm im api. */ private static void testAlarmClusterByWeChatMarkDown() { AlarmMessageInfo alarmMsg = new AlarmMessageInfo(); // FF0000 (red), 008000(green), FFA500(yellow) alarmMsg.setTitle("`Kafka Eagle Alarm Notice`\n"); alarmMsg.setAlarmContent("<font color=\"warning\">node.shutdown [ localhost:9092 ]</font>"); // alarmMsg.setAlarmContent("<font color=\"#008000\">node.alive [ // localhost:9092 ]</font>"); alarmMsg.setAlarmDate("2019-10-07 21:43:22"); alarmMsg.setAlarmLevel("P0"); alarmMsg.setAlarmProject("Kafka"); alarmMsg.setAlarmStatus("<font color=\"warning\">PROBLEM</font>"); // alarmMsg.setAlarmStatus("<font color=\"#008000\">NORMAL</font>"); alarmMsg.setAlarmTimes("current(1), max(7)"); IMServiceImpl im = new IMServiceImpl(); im.sendJsonMsgByWeChat(alarmMsg.toWeChatMarkDown(),"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=maMN2krp0GwiyxoA6JCULLk8oLHwfnjnojeYGma_5KG5J_JHqTledeY6AHWE2rwLTF6I5yqu5LJUmUpSn7feXauFySZtnOGlAvRACz33V2UegR596xuyOT4fZIfNzB1cqJi3A-Eahbw7UVG2a8AaHvN0ZrSRPkQiqWola5p71FfCpnuDEAw63THmURdfMIcF3QB5KFzl-qHblqXfQLtpeA"); } /** New alarm im api. */ private static void testAlarmClusterByDingDingMarkDown() { AlarmMessageInfo alarmMsg = new AlarmMessageInfo(); // FF0000 (red), 008000(green), FFA500(yellow) alarmMsg.setTitle("**<font color=\"#FF0000\">Kafka Eagle Alarm Notice</font>** \n\n"); alarmMsg.setAlarmContent("<font color=\"#FF0000\">node.shutdown [ localhost:9092 ]</font>"); // alarmMsg.setAlarmContent("<font color=\"#008000\">node.alive [ // localhost:9092 ]</font>"); alarmMsg.setAlarmDate("2019-10-07 21:43:22"); alarmMsg.setAlarmLevel("P0"); alarmMsg.setAlarmProject("Kafka"); alarmMsg.setAlarmStatus("<font color=\"#FF0000\">PROBLEM</font>"); // alarmMsg.setAlarmStatus("<font color=\"#008000\">NORMAL</font>"); alarmMsg.setAlarmTimes("current(1), max(7)"); IMService im = new IMFactory().create(); im.sendPostMsgByDingDing(alarmMsg.toDingDingMarkDown(),"https://oapi.dingtalk.com/robot/send?access_token=3b7b59d17db0145549b1f65f62921b44bacd1701e635e797da45318a94339060"); //IMServiceImpl im = new IMServiceImpl(); //im.sendPostMsgByDingDing(alarmMsg.toDingDingMarkDown(),"https://oapi.dingtalk.com/robot/send?access_token=3b7b59d17db0145549b1f65f62921b44bacd1701e635e797da45318a94339060"); } private static void testConsumerHeathyByWeChat() { ClusterContentModule ccm = new ClusterContentModule(); ccm.setCluster("cluster2"); ccm.setServer("kafka-node-01:9093"); ccm.setTime(CalendarUtils.getDate()); ccm.setType("Kafka"); ccm.setUser("[email protected]"); LagContentModule lcm = new LagContentModule(); lcm.setCluster("cluster2"); lcm.setConsumerLag("50000"); lcm.setGroup("ke-storm-group"); lcm.setLagThreshold("2000"); lcm.setTime(CalendarUtils.getDate()); lcm.setTopic("ke-t-storm-money"); lcm.setType("Consumer"); lcm.setUser("[email protected]"); IMServiceImpl im = new IMServiceImpl(); im.sendJsonMsgByWeChat(ccm.toWeChatMarkDown(),"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=maMN2krp0GwiyxoA6JCULLk8oLHwfnjnojeYGma_5KG5J_JHqTledeY6AHWE2rwLTF6I5yqu5LJUmUpSn7feXauFySZtnOGlAvRACz33V2UegR596xuyOT4fZIfNzB1cqJi3A-Eahbw7UVG2a8AaHvN0ZrSRPkQiqWola5p71FfCpnuDEAw63THmURdfMIcF3QB5KFzl-qHblqXfQLtpeA"); im.sendJsonMsgByWeChat(lcm.toWeChatMarkDown(),"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=maMN2krp0GwiyxoA6JCULLk8oLHwfnjnojeYGma_5KG5J_JHqTledeY6AHWE2rwLTF6I5yqu5LJUmUpSn7feXauFySZtnOGlAvRACz33V2UegR596xuyOT4fZIfNzB1cqJi3A-Eahbw7UVG2a8AaHvN0ZrSRPkQiqWola5p71FfCpnuDEAw63THmURdfMIcF3QB5KFzl-qHblqXfQLtpeA"); } private static void testClusterHeathyByDingDing() { ClusterContentModule ccm = new ClusterContentModule(); ccm.setCluster("cluster2"); ccm.setServer("zookeeper-node-01:2183"); ccm.setTime(CalendarUtils.getDate()); ccm.setType("Zookeeper"); ccm.setUser("[email protected]"); LagContentModule lcm = new LagContentModule(); lcm.setCluster("cluster2"); lcm.setConsumerLag("50000"); lcm.setGroup("ke-storm-group"); lcm.setLagThreshold("2000"); lcm.setTime(CalendarUtils.getDate()); lcm.setTopic("ke-t-storm-money"); lcm.setType("Consumer"); lcm.setUser("[email protected]"); IMServiceImpl im = new IMServiceImpl(); // im.sendJsonMsgByDingDing(ccm.toDingDingMarkDown()); // im.sendJsonMsgByDingDing(lcm.toDingDingMarkDown()); } }
Analysis of monitoring and multipath support on top of OpenFlow specification In general, traffic is pushed through a single path despite the existence of alternative paths in networks. For example, routing solutions based on spanning tree prune the topology to prevent loops, consequently preventing also the use of alternative paths. Research on quality of service frequently advocates that the use of alternative paths is interesting for enforcing Service Level Agreements (SLAs), bypassing bottlenecks created by shortest paths. In this paper, we are interested in analyzing the support for monitoring network traffic and for provisioning of multipaths in software‐defined networking (SDN), given the strong platform it provides for experimentation of new networked solutions. Our approach firstly enriches the topology view at the control plane with data gathered through fine grain data plane monitoring. On the basis of such enriched view, our system determines the path, or multipaths, necessary to enforce the specified SLA. We propose 2 extension modules to an OpenFlow controller: SDNMon, which monitors the data plane to enrich the topology information at the control plane, and MP‐Routing, which determines a set of paths, in the absence of a single path capable of enforcing the SLA. Both modules are extensively evaluated, and the results not only demonstrate what can be achieved in terms of accuracy in SDNMon and in terms of quality of service benefits in MP‐Routing but also highlight some limitations of OpenFlow specification. On the basis of our findings, we propose a set of new counters to Per Port and Per Flow granularity levels of OpenFlow specification.
class CounterfactualSurvivalModel: """Universal interface to train multiple different counterfactual survival models.""" def __init__(self, treated_model, control_model): assert isinstance(treated_model, SurvivalModel) assert isinstance(control_model, SurvivalModel) assert treated_model.fitted assert control_model.fitted self.treated_model = treated_model self.control_model = control_model def predict_counterfactual_survival(self, features, times): control_outcomes = self.control_model.predict_survival(features, times) treated_outcomes = self.treated_model.predict_survival(features, times) return treated_outcomes, control_outcomes def predict_counterfactual_risk(self, features, times): control_outcomes = self.control_model.predict_risk(features, times) treated_outcomes = self.treated_model.predict_risk(features, times) return treated_outcomes, control_outcomes
Patient reports of the frequency and severity of adverse reactions associated with biological agents prescribed for psoriasis in Brazil Background: The safety of biological agents used to treat psoriasis remains uncertain. Objective: The authors determined the frequency and severity of adverse effects associated with use of biologic agents for psoriasis through patient-registered lawsuits to the government of Sao Paulo, Brazil. Methods: Sources of information included legal records, dispensing pharmacy data and interviews with patients. Research staff conducted telephone interviews with patients who used biologic drugs during 2004 – 2011, inquiring about medication-related adverse drug reactions (ADRs) and serious adverse events (SAEs). Results: Of the 218 patients identified, 15 proved ineligible or refused participation. 203 patients were interviewed, with 111 (54.7%) taking infliximab, 43 (21.2%) efalizumab, 35 (17.2%) etanercept and 14 (6.9%) adalimumab. Of 84 (41.4%) patients who experienced one or more ADR related to biological agents, 57 (67.9%) experienced one or more SAE. The only risk factor associated with ADRs was comorbidity odds ratio = 6.54 (95% confident interval 3.20 – 13.32), p < 0.0001. Conclusion: Biologic agents were associated with high rates of ADRs and SAEs. The data suggests that for patients taking a biologic agent to treat psoriasis and who have one or more comorbidities, warnings of possible adverse events and enhanced surveillance are warranted.
/** * Adds a new rule to the IDB database. * This is part of the fluent API. * @param newRule the rule to add. * @return {@code this} so that methods can be chained. * @throws DatalogException if the rule is invalid. */ public Jatalog rule(Rule newRule) throws DatalogException { newRule.validate(); idb.add(newRule); return this; }
package com.github.lindenb.knime5bio; import org.knime.core.node.NodeFactory; import org.knime.core.node.NodeModel; public abstract class AbstractNodeFactory<T extends NodeModel> extends NodeFactory<T> { }
An armed man gunned down a new village police chief on an Ohio street on Friday and then killed two employees in a nearby nursing home, where he later was found dead, a sheriff said. No nursing home residents were injured, nor were two hostages briefly held by the alleged gunman. The slain police chief, Steven Eric Disario, had headed the Kirkersville Police Department for only about three weeks, Licking County Sheriff Randy Thorp said. Disario was shot on a street near the Pine Kirk Care Center, and the two female employees and the gunman were found dead inside, Thorp said. Authorities identified the gunman as Thomas Hartless, 43, of the nearby village of Utica. The employees were Marlina Medrano, a nurse, and 48-year-old Cindy Krantz, a nurse's aide. Medrano's age was not available Disario, 36, was a father of six children, with a seventh on the way, the sheriff said. Flowers and flags appeared in an impromptu memorial outside the village police hall, located less than a block from the site of the shooting. Thorp called it a hard day for all. "We've lost a police officer. It's just a tragic event," he said. "I guess the only peace of mind is that the threat is over." Thorp gave the following timeline of events in the village of about 500 residents, roughly 25 miles (39 kilometers) east of Columbus: The gunman was in a wooded area behind the nursing home when he encountered two passers-by, whom he temporarily took hostage. Disario, responding to a report of a man with a gun, apparently encountered the gunman in that area. The chief's last radio communication said he had the man in sight. When a shot was fired at the chief, the hostages escaped unharmed. "We don't know the cause or the purpose or what drove this individual to do this," Thorp said, adding that was being investigated. Responding officers found Disario on the street and then investigated a report of a gunman at the nursing home, Thorp said. Some of the nursing home's 23 residents barricaded themselves during the shooting, but none of them was injured, he said. All were relocated to other facilities until investigators were out of the nursing home. Ohio Attorney General Mike DeWine, who came to the scene Friday afternoon, said search warrants had been executed on two vehicles owned by Hartless and at his home in Utica, about 30 miles (48 kilometers) away. He later said Medrano had a relationship with Hartless. Officials said they lived on the same street. Thorp said law enforcers were still working to determine what, if any, relationship the man had with the nursing home. The facility is secure, and it's unclear how the gunman got in, he said. The shooting closed down the main street in the village, which was flooded with police officers from several surrounding agencies and with ambulances. "We don't have this stuff go on around here," said Ron Rogers, 67, a local shopkeeper. "The only sirens we hear are when the Fire Department goes out." A woman who lives across the street said she and her 6-year-old son heard it happen. "We heard it all," said Tiffani Chester, 25. "We heard yelling, we heard the gunshots, then it was just sirens." Pine Kirk is licensed for 24 patients and had 23 as of May 3, according to Ohio Department of Health records. A message was left with the center, whose employees appeared wheeling medical carts out of the facility Friday evening to put them into storage while patients are away. Peter Van Runkle, the head of the state trade association representing nursing homes, told the Dispatch that Pine Kirk caters to "the forgotten members of society." "They provide them with a small environment that's less institutional than some facilities might be," he said. "They do a good job of taking care of a niche clientele." The state Bureau of Criminal Investigation is leading the probe into what happened. County Coroner Michael Campolo didn't expect to release autopsy results until Sunday, after all four victims had been examined. Gov. John Kasich ordered flags flown at half-staff in Licking County and the Statehouse and expressed his condolences in a tweet. "Join me in praying for his family, friends and colleagues, and for the others injured in this tragedy," the Republican governor said. ___ Welsh-Huggins reported from Columbus. Associated Press writer Mark Scolforo in Harrisburg, Pennsylvania, and AP researcher Rhonda Shafner in New York City contributed to this report.
/** * CosmosAsyncContainer with encryption capabilities. */ public class CosmosEncryptionAsyncContainer { private final Scheduler encryptionScheduler; private final CosmosResponseFactory responseFactory = new CosmosResponseFactory(); private final CosmosAsyncContainer container; private final EncryptionProcessor encryptionProcessor; private final CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; ImplementationBridgeHelpers.CosmosItemResponseHelper.CosmosItemResponseBuilderAccessor cosmosItemResponseBuilderAccessor; ImplementationBridgeHelpers.CosmosItemRequestOptionsHelper.CosmosItemRequestOptionsAccessor cosmosItemRequestOptionsAccessor; ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.CosmosQueryRequestOptionsAccessor cosmosQueryRequestOptionsAccessor; CosmosEncryptionAsyncContainer(CosmosAsyncContainer container, CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient) { this.container = container; this.cosmosEncryptionAsyncClient = cosmosEncryptionAsyncClient; this.encryptionProcessor = new EncryptionProcessor(this.container, cosmosEncryptionAsyncClient); this.encryptionScheduler = Schedulers.parallel(); this.cosmosItemResponseBuilderAccessor = ImplementationBridgeHelpers.CosmosItemResponseHelper.getCosmosItemResponseBuilderAccessor(); this.cosmosItemRequestOptionsAccessor = ImplementationBridgeHelpers.CosmosItemRequestOptionsHelper.getCosmosItemRequestOptionsAccessor(); this.cosmosQueryRequestOptionsAccessor = ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor(); } EncryptionProcessor getEncryptionProcessor() { return this.encryptionProcessor; } /** * create item and encrypts the requested fields * * @param item the Cosmos item represented as a POJO or Cosmos item object. * @param partitionKey the partition key. * @param requestOptions request option * @param <T> serialization class type * @return a {@link Mono} containing the Cosmos item resource response. */ @SuppressWarnings("unchecked") public <T> Mono<CosmosItemResponse<T>> createItem(T item, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions) { Preconditions.checkNotNull(item, "item"); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } Preconditions.checkArgument(partitionKey != null, "partitionKey cannot be null for operations using " + "EncryptionContainer."); byte[] streamPayload = cosmosSerializerToStream(item); return createItemHelper(streamPayload, partitionKey, requestOptions, (Class<T>) item.getClass(), false); } /** * Deletes the item. * <p> * After subscription the operation will be performed. The {@link Mono} upon successful completion will contain a * single Cosmos item response with the deleted item. * * @param itemId id of the item. * @param partitionKey partitionKey of the item. * @param options the request options. * @return a {@link Mono} containing the Cosmos item resource response. */ public Mono<CosmosItemResponse<Object>> deleteItem(String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options) { return container.deleteItem(itemId, partitionKey, options); } /** * upserts item and encrypts the requested fields * * @param item the Cosmos item represented as a POJO or Cosmos item object. * @param partitionKey the partition key. * @param requestOptions request option * @param <T> serialization class type * @return a {@link Mono} containing the Cosmos item resource response. */ @SuppressWarnings("unchecked") public <T> Mono<CosmosItemResponse<T>> upsertItem(T item, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions) { Preconditions.checkNotNull(item, "item"); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } Preconditions.checkArgument(partitionKey != null, "partitionKey cannot be null for operations using " + "EncryptionContainer."); byte[] streamPayload = cosmosSerializerToStream(item); return upsertItemHelper(streamPayload, partitionKey, requestOptions, (Class<T>) item.getClass(), false); } /** * replaces item and encrypts the requested fields * * @param item the Cosmos item represented as a POJO or Cosmos item object. * @param itemId the item id. * @param partitionKey the partition key. * @param requestOptions request option * @param <T> serialization class type * @return a {@link Mono} containing the Cosmos item resource response. */ @SuppressWarnings("unchecked") public <T> Mono<CosmosItemResponse<T>> replaceItem(T item, String itemId, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions) { Preconditions.checkNotNull(item, "item"); if (requestOptions == null) { requestOptions = new CosmosItemRequestOptions(); } Preconditions.checkArgument(partitionKey != null, "partitionKey cannot be null for operations using " + "EncryptionContainer."); byte[] streamPayload = cosmosSerializerToStream(item); return replaceItemHelper(streamPayload, itemId, partitionKey, requestOptions, (Class<T>) item.getClass(), false); } /** * Reads item and decrypt the encrypted fields * * @param id item id * @param partitionKey the partition key. * @param requestOptions request options * @param classType deserialization class type * @param <T> type * @return a {@link Mono} containing the Cosmos item resource response. */ public <T> Mono<CosmosItemResponse<T>> readItem(String id, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions, Class<T> classType) { Mono<CosmosItemResponse<byte[]>> responseMessageMono = this.readItemHelper(id, partitionKey, requestOptions, false); return responseMessageMono.publishOn(encryptionScheduler).flatMap(cosmosItemResponse -> setByteArrayContent(cosmosItemResponse, this.encryptionProcessor.decrypt(this.cosmosItemResponseBuilderAccessor.getByteArrayContent(cosmosItemResponse))) .map(bytes -> this.responseFactory.createItemResponse(cosmosItemResponse, classType))); } /** * Query for items in the current container using a string. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will contain one or several feed * response of the obtained items. In case of failure the {@link CosmosPagedFlux} will error. * * @param <T> the type parameter. * @param query the query text. * @param options the query request options. * @param classType the class type. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public <T> CosmosPagedFlux<T> queryItems(String query, CosmosQueryRequestOptions options, Class<T> classType) { return this.queryItems(new SqlQuerySpec(query), new CosmosQueryRequestOptions(), classType); } /** * Query for items in the current container using a {@link SqlQuerySpec}. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will contain one or several feed * response of the obtained items. In case of failure the {@link CosmosPagedFlux} will error. * * @param <T> the type parameter. * @param query the query. * @param options the query request options. * @param classType the class type. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public <T> CosmosPagedFlux<T> queryItems(SqlQuerySpec query, CosmosQueryRequestOptions options, Class<T> classType) { if (options == null) { options = new CosmosQueryRequestOptions(); } return queryItemsHelper(query, options, classType,false); } /** * Query for items in the current container using a {@link SqlQuerySpecWithEncryption}. * <p> * After subscription the operation will be performed. The {@link CosmosPagedFlux} will contain one or several feed * response of the obtained items. In case of failure the {@link CosmosPagedFlux} will error. * * @param <T> the type parameter. * @param sqlQuerySpecWithEncryption the sqlQuerySpecWithEncryption. * @param options the query request options. * @param classType the class type. * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public <T> CosmosPagedFlux<T> queryItemsOnEncryptedProperties(SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption, CosmosQueryRequestOptions options, Class<T> classType) { if (options == null) { options = new CosmosQueryRequestOptions(); } if (EncryptionModelBridgeInternal.getEncryptionParamMap(sqlQuerySpecWithEncryption).size() > 0) { List<Mono<Void>> encryptionSqlParameterMonoList = new ArrayList<>(); for (Map.Entry<String, SqlParameter> entry : EncryptionModelBridgeInternal.getEncryptionParamMap(sqlQuerySpecWithEncryption).entrySet()) { encryptionSqlParameterMonoList.add(EncryptionModelBridgeInternal.addEncryptionParameterAsync(sqlQuerySpecWithEncryption, entry.getKey(), entry.getValue(), this)); } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionSqlParameterMonoList).collectList(); Mono<SqlQuerySpec> sqlQuerySpecMono = listMono.flatMap(ignoreVoids -> Mono.just(EncryptionModelBridgeInternal.getSqlQuerySpec(sqlQuerySpecWithEncryption))); return queryItemsHelperWithMonoSqlQuerySpec(sqlQuerySpecMono, sqlQuerySpecWithEncryption, options, classType, false); } else { return queryItemsHelper(EncryptionModelBridgeInternal.getSqlQuerySpec(sqlQuerySpecWithEncryption), options, classType, false); } } /** * Get the CosmosEncryptionAsyncClient * * @return encrypted cosmosAsyncClient */ CosmosEncryptionAsyncClient getCosmosEncryptionAsyncClient() { return cosmosEncryptionAsyncClient; } /** * Gets the CosmosAsyncContainer * * @return cosmos container */ public CosmosAsyncContainer getCosmosAsyncContainer() { return container; } private <T> byte[] cosmosSerializerToStream(T item) { // TODO: return EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), item); } ItemDeserializer getItemDeserializer() { return CosmosBridgeInternal.getAsyncDocumentClient(container.getDatabase()).getItemDeserializer(); } private <T> Mono<byte[]> decryptResponse( byte[] input) { if (input == null) { return Mono.empty(); } return this.encryptionProcessor.decrypt( input); } private Mono<CosmosItemResponse<byte[]>> setByteArrayContent(CosmosItemResponse<byte[]> rsp, Mono<byte[]> bytesMono) { return bytesMono.flatMap( bytes -> { this.cosmosItemResponseBuilderAccessor.setByteArrayContent(rsp, bytes); return Mono.just(rsp); } ); } private <T> Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> queryDecryptionTransformer(Class<T> classType, Function<CosmosPagedFluxOptions, Flux<FeedResponse<JsonNode>>> func) { return func.andThen(flux -> flux.publishOn(encryptionScheduler) .flatMap( page -> { List<byte[]> byteArrayList = page.getResults().stream() .map(node -> cosmosSerializerToStream(node)) .collect(Collectors.toList()); List<Mono<byte[]>> byteArrayMonoList = byteArrayList.stream().map(bytes -> decryptResponse(bytes)).collect(Collectors.toList()); return Flux.concat(byteArrayMonoList).map( item -> getItemDeserializer().parseFrom(classType, item) ).collectList().map(itemList -> BridgeInternal.createFeedResponseWithQueryMetrics(itemList, page.getResponseHeaders(), BridgeInternal.queryMetricsFromFeedResponse(page), ModelBridgeInternal.getQueryPlanDiagnosticsContext(page), false, false, page.getCosmosDiagnostics()) ); } ) ); } private Mono<CosmosItemResponse<byte[]>> readItemHelper(String id, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions, boolean isRetry) { this.setRequestHeaders(requestOptions); Mono<CosmosItemResponse<byte[]>> responseMessageMono = this.container.readItem( id, partitionKey, requestOptions, byte[].class); return responseMessageMono.onErrorResume(exception -> { if (!isRetry && exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).then(Mono.defer(() -> readItemHelper(id, partitionKey, requestOptions, true) )); } } return Mono.error(exception); }); } private <T> Mono<CosmosItemResponse<T>> createItemHelper(byte[] streamPayload, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions, Class<T> itemClass, boolean isRetry) { this.setRequestHeaders(requestOptions); return this.encryptionProcessor.encrypt(streamPayload) .flatMap(encryptedPayload -> this.container.createItem( encryptedPayload, partitionKey, requestOptions) .publishOn(encryptionScheduler) .flatMap(cosmosItemResponse -> setByteArrayContent(cosmosItemResponse, this.encryptionProcessor.decrypt(this.cosmosItemResponseBuilderAccessor.getByteArrayContent(cosmosItemResponse))) .map(bytes -> this.responseFactory.createItemResponse(cosmosItemResponse, itemClass))).onErrorResume(exception -> { if (!isRetry && exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).then (Mono.defer(() -> createItemHelper(streamPayload, partitionKey, requestOptions, itemClass, true))); } } return Mono.error(exception); })); } private <T> Mono<CosmosItemResponse<T>> upsertItemHelper(byte[] streamPayload, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions, Class<T> itemClass, boolean isRetry) { this.setRequestHeaders(requestOptions); return this.encryptionProcessor.encrypt(streamPayload) .flatMap(encryptedPayload -> this.container.upsertItem( encryptedPayload, partitionKey, requestOptions) .publishOn(encryptionScheduler) .flatMap(cosmosItemResponse -> setByteArrayContent(cosmosItemResponse, this.encryptionProcessor.decrypt(this.cosmosItemResponseBuilderAccessor.getByteArrayContent(cosmosItemResponse))) .map(bytes -> this.responseFactory.createItemResponse(cosmosItemResponse, itemClass))) .onErrorResume(exception -> { if (!isRetry && exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).then (Mono.defer(() -> upsertItemHelper(streamPayload, partitionKey, requestOptions, itemClass, true))); } } return Mono.error(exception); })); } private <T> Mono<CosmosItemResponse<T>> replaceItemHelper(byte[] streamPayload, String itemId, PartitionKey partitionKey, CosmosItemRequestOptions requestOptions, Class<T> itemClass, boolean isRetry) { this.setRequestHeaders(requestOptions); return this.encryptionProcessor.encrypt(streamPayload) .flatMap(encryptedPayload -> this.container.replaceItem( encryptedPayload, itemId, partitionKey, requestOptions) .publishOn(encryptionScheduler) .flatMap(cosmosItemResponse -> setByteArrayContent(cosmosItemResponse, this.encryptionProcessor.decrypt(this.cosmosItemResponseBuilderAccessor.getByteArrayContent(cosmosItemResponse))) .map(bytes -> this.responseFactory.createItemResponse(cosmosItemResponse, itemClass))) .onErrorResume(exception -> { if (!isRetry && exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).then (Mono.defer(() -> replaceItemHelper(streamPayload, itemId, partitionKey, requestOptions, itemClass, true))); } } return Mono.error(exception); })); } private void setRequestHeaders(CosmosItemRequestOptions requestOptions) { this.cosmosItemRequestOptionsAccessor.setHeader(requestOptions, Constants.IS_CLIENT_ENCRYPTED_HEADER, "true"); this.cosmosItemRequestOptionsAccessor.setHeader(requestOptions, Constants.INTENDED_COLLECTION_RID_HEADER, this.encryptionProcessor.getContainerRid()); } private void setRequestHeaders(CosmosQueryRequestOptions requestOptions) { this.cosmosQueryRequestOptionsAccessor.setHeader(requestOptions, Constants.IS_CLIENT_ENCRYPTED_HEADER, "true"); this.cosmosQueryRequestOptionsAccessor.setHeader(requestOptions, Constants.INTENDED_COLLECTION_RID_HEADER, this.encryptionProcessor.getContainerRid()); } private <T> CosmosPagedFlux<T> queryItemsHelper(SqlQuerySpec sqlQuerySpec, CosmosQueryRequestOptions options, Class<T> classType, boolean isRetry) { setRequestHeaders(options); CosmosQueryRequestOptions finalOptions = options; Flux<FeedResponse<T>> tFlux = CosmosBridgeInternal.queryItemsInternal(container, sqlQuerySpec, options, new Transformer<T>() { @Override public Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> transform(Function<CosmosPagedFluxOptions, Flux<FeedResponse<JsonNode>>> func) { return queryDecryptionTransformer(classType, func); } }).byPage().onErrorResume(exception -> { if (exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (!isRetry && isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).thenMany( (CosmosPagedFlux.defer(() -> queryItemsHelper(sqlQuerySpec,finalOptions, classType, true).byPage()))); } } return Mono.error(exception); }); return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, finalOptions); return tFlux; }); } private <T> CosmosPagedFlux<T> queryItemsHelperWithMonoSqlQuerySpec(Mono<SqlQuerySpec> sqlQuerySpecMono, SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption, CosmosQueryRequestOptions options, Class<T> classType, boolean isRetry) { setRequestHeaders(options); CosmosQueryRequestOptions finalOptions = options; Flux<FeedResponse<T>> tFlux = CosmosBridgeInternal.queryItemsInternal(container, sqlQuerySpecMono, options, new Transformer<T>() { @Override public Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> transform(Function<CosmosPagedFluxOptions, Flux<FeedResponse<JsonNode>>> func) { return queryDecryptionTransformer(classType, func); } }).byPage().onErrorResume(exception -> { if (exception instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) exception; if (!isRetry && isIncorrectContainerRid(cosmosException)) { this.encryptionProcessor.getIsEncryptionSettingsInitDone().set(false); return this.encryptionProcessor.initializeEncryptionSettingsAsync(true).thenMany( (CosmosPagedFlux.defer(() -> queryItemsHelper(EncryptionModelBridgeInternal.getSqlQuerySpec(sqlQuerySpecWithEncryption), finalOptions, classType, true).byPage()))); } } return Mono.error(exception); }); return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { setContinuationTokenAndMaxItemCount(pagedFluxOptions, finalOptions); return tFlux; }); } boolean isIncorrectContainerRid(CosmosException cosmosException) { return cosmosException.getStatusCode() == HttpConstants.StatusCodes.BADREQUEST && cosmosException.getResponseHeaders().get(HttpConstants.HttpHeaders.SUB_STATUS) .equals(Constants.INCORRECT_CONTAINER_RID_SUB_STATUS); } }
/* Prints out the contents of the given OpInfo. Should only be called * inside a DEBUG macro (i.e. for debugging only). */ static void PrintOpInfo(const struct OpInfo* info) { DEBUG_OR_ERASE(printf("opinfo(%s, hasmrm=%u, immtype=%s, opinmrm=%d)\n", NaClInstTypeString(info->insttype), info->hasmrmbyte, NCDecodeImmediateTypeName(info->immtype), info->opinmrm)); }
<reponame>asoffer/icarus #include "base/untyped_buffer_view.h" #include "base/untyped_buffer.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace base { namespace { TEST(UntypedBufferView, Get) { untyped_buffer buf; buf.append(1); buf.append(2); untyped_buffer_view view(buf); EXPECT_EQ(view.get<int>(0), 1); EXPECT_EQ(view.get<int>(sizeof(int)), 2); } TEST(UntypedBufferView, RemovePrefixChangesSize) { untyped_buffer buf; buf.append(1); buf.append(2); buf.append(3); untyped_buffer_view view(buf); EXPECT_EQ(view.size(), sizeof(int) * 3); view.remove_prefix(sizeof(int)); EXPECT_EQ(view.size(), sizeof(int) * 2); view.remove_prefix(sizeof(int) * 2); EXPECT_TRUE(view.empty()); } TEST(UntypedBufferView, RemovePrefixWithGet) { untyped_buffer buf; buf.append(1); buf.append(2); buf.append(3); untyped_buffer_view view(buf); view.remove_prefix(sizeof(int)); EXPECT_EQ(view.get<int>(0), 2); EXPECT_EQ(view.get<int>(sizeof(int)), 3); view.remove_prefix(sizeof(int)); EXPECT_EQ(view.get<int>(0), 3); } TEST(UntypedBufferView, RemoveSuffixChangesSize) { untyped_buffer buf; buf.append(1); buf.append(2); buf.append(3); untyped_buffer_view view(buf); EXPECT_EQ(view.size(), sizeof(int) * 3); view.remove_suffix(sizeof(int)); EXPECT_EQ(view.size(), sizeof(int) * 2); view.remove_suffix(sizeof(int) * 2); EXPECT_TRUE(view.empty()); } TEST(UntypedBufferView, DataPointer) { untyped_buffer buf; buf.append(1); buf.append(2); untyped_buffer_view view(buf); EXPECT_EQ(buf.raw(0), view.data()); view.remove_prefix(4); EXPECT_EQ(buf.raw(4), view.data()); } } // namespace } // namespace base
#ifndef IMAGEWIDGET_HPP #define IMAGEWIDGET_HPP #include "Widget.hpp" #include "Events.hpp" #include "../Image/Image.hpp" #include <chrono> #include <functional> /** * \brief Gère une Image sélectionnable */ class ImageWidget : public Widget { public: ImageWidget(Image& image, const dim_t size, const std::function<bool(ClickEvent, ImageWidget*)>& callback = [](ClickEvent, ImageWidget*){ return false;}) : image_{image}, size_{size}, callback_{callback} {} Image& getImage() { return image_; } void setSelectable(bool selectable) { is_selectable_ = selectable; } protected: img actualRender() const override; void actualResize(const dim_t& size) override; dim_t actualSize() const override; bool actualPropagateEvent(const Event& event) override; private: Image& image_; dim_t size_; std::chrono::system_clock::time_point last_clicked_; std::function<bool(ClickEvent, ImageWidget*)> callback_ = [](ClickEvent, ImageWidget*){ return false;}; bool is_selectable_ = true; static constexpr std::chrono::system_clock::duration double_click_interval = std::chrono::milliseconds(250); }; #endif //IMAGEWIDGET_HPP
import { createMaskerPipe, ITransmittable, panMaskerPipe, } from '../../../main/ts' const noop = () => { /* noop */ } describe('maskerPipe', () => { it('factory returns IPipe', () => { const maskerPipe = createMaskerPipe((el) => el) expect(maskerPipe.type).toBe('masker') expect(maskerPipe.execute).toEqual(expect.any(Function)) }) it('return masked elements', async () => { const maskerPipe = createMaskerPipe((el) => el.toString() + 'masked') const transmittable: ITransmittable = { data: ['foo', 'bar', ['foo2', ['foo3']]], meta: { history: [] }, } expect(await maskerPipe.execute(transmittable, noop)).toStrictEqual([ null, ['foomasked', 'barmasked', ['foo2masked', ['foo3masked']]], ]) }) it('return masked elements', async () => { const transmittable: ITransmittable = { data: [ '4111111111111111', 'bar', ['4111111111111111', ['foo3', '0000000000000000']], ], meta: { history: [] }, } expect(await panMaskerPipe.execute(transmittable, noop)).toStrictEqual([ null, [ '4111 **** **** 1111', 'bar', ['4111 **** **** 1111', ['foo3', '0000 **** **** 0000']], ], ]) }) })
<reponame>mehrdad-shokri/element #!/usr/bin/env node import findRoot from 'find-root' const root = findRoot(__dirname) import { main } from './src/element' main(root)
def exists(self, *, parent: bool=None) -> AppCategoriesEndpoint: if parent == None: return self._set_exists('parent', 'true' if parent else 'false') return self
/** * Copyright (c) 2005,2010 <NAME> <<EMAIL>> * See the file COPYING for copying permission. * * $Id$ */ #ifndef YAPS_CALC_H #define YAPS_CALC_H /**********************************************************/ /* Equation of state to calculate pressures */ extern char EOSType[20]; /* Kernel to use in the calculations */ extern char KernelType[20]; /* Kernel smoothing length */ extern float SmoothR; /* Rest density */ extern float Density0; /* Speed of sound */ extern float SOS; /* Alpha factor to calculate viscosity */ extern float ViscAlpha; /* Beta factor to calculate viscosity */ extern float ViscBeta; /* Time step of integration */ extern float TimeStep; /**********************************************************/ /* Initialize calculation module */ extern void InitCalc( void); /* Do one calculation step */ extern void DoCalcStep( void); /**********************************************************/ #endif /* YAPS_CALC_H */
package com.blocklang.develop.dao; import java.util.List; import com.blocklang.develop.model.PageDataItem; public interface PageDataJdbcDao { void delete(Integer pageId); void batchSave(Integer pageId, List<PageDataItem> allData); }
from _Node import Node class File(Node): """ A file in a treebank """ def __init__(self, **kwargs): self._IDDict = {} Node.__init__(self, **kwargs) def attachChild(self, newChild): """ Append a sentence """ # Security isn't really an issue for Files, so just append the new # Sentence without complaint self._children.append(newChild) self._IDDict[newChild.globalID] = newChild def detachChild(self, node): """ Delete a sentence """ self._children.remove(node) self._IDDict.pop(node.globalID) def sentence(self, key): """ Retrieve a sentence by key """ return self._IDDict[key] def prettyPrint(self): return "(%d %s)" % (self.localID, '\n\n\n'.join([child.prettyPrint() for child in self.children()])) def performOperation(self, operation): """ Accept a Visitor and call it on each child Goofy name/design is legacy from when I didn't know how to code :( """ operation.newStructure() operation.actOn(self) for node in getattr(self, operation.listType)(): try: operation.actOn(node) # Give operations the opportunity to signal # when the work is complete except Break: break while operation.moreChanges: operation.actOn(self) for node in getattr(self, operation.listType)(): try: operation.actOn(node) # Give operations the opportunity to signal # when the work is complete except Break: break
import ICreateCoursesDTO from '@modules/courses/dtos/ICreateCoursesDTO'; import Courses from '@modules/courses/infra/typeorm/entities/Courses'; export default interface IUsersRepository { findById(id: string): Promise<Courses | undefined>; findOneByName(name: string): Promise<Courses | undefined>; findAll(page: number, limit: number): Promise<Courses[]>; create(courseData: ICreateCoursesDTO): Promise<Courses>; save(user: Courses): Promise<Courses>; remove(course: Courses): Promise<void>; }
{-# LANGUAGE TupleSections #-} module Day11.Day11 where import Lib import IntCode import Control.Concurrent.Async import Control.Concurrent.Chan import qualified Data.Map.Strict as M import Text.Printf import Data.Maybe import Data.List import Control.Monad data Direction = Lef | Down | Righ | Up deriving Show nextDirection :: Direction -> Integer -> Direction nextDirection d turn = case d of Lef -> if turn == 0 then Down else Up Down -> if turn == 0 then Righ else Lef Righ -> if turn == 0 then Up else Down Up -> if turn == 0 then Lef else Righ nextCoordinates :: (Integer, Integer) -> Direction -> (Integer, Integer) nextCoordinates (x, y) d = case d of Lef -> (x - 1, y) Down -> (x, y - 1) Righ -> (x + 1, y) Up -> (x, y + 1) readOutput :: Chan Integer -> IO (Integer, Integer) readOutput ch = do color <- readChan ch dir <- readChan ch return (color, dir) day11 :: IO () day11 = do contents <- fileContents "/src/Day11/input.txt" inChan <- newChan outChan <- newChan -- Change to 0 for part 1 writeChan inChan (1 :: Integer) let values = parseInput contents ram = M.fromList (zip [0 ..] values) positions = M.empty t1 <- async $ processOpCode ram 0 0 inChan outChan let loop pos dir grid = do t2 <- async $ readOutput outChan output <- waitEither t1 t2 case output of (Right (color, turn)) -> do let nextGrid = M.insert pos color grid nextDir = nextDirection dir turn nextPos = nextCoordinates pos nextDir writeChan inChan (fromMaybe 0 (M.lookup nextPos nextGrid)) loop nextPos nextDir nextGrid (Left _) -> do (color, _) <- wait t2 return $ M.insert pos color grid image <- loop (0, 0) Up positions -- print length image -- part 1 let coordinates = M.keys image getBounds = sequenceA [minimum, maximum] [minX, maxX] = getBounds $ map fst coordinates [minY, maxY] = getBounds $ map snd coordinates array = map (\y -> map (, y) [minX .. maxX]) [maxY, (maxY - 1) .. minY] forM_ [maxY, (maxY - 1) .. minY] (\y -> forM_ [minX .. maxX] (\x -> putStr (if fromMaybe 0 (M.lookup (x, y) image) == 0 then " " else "$") ) >> putStrLn "" ) test :: IO () test = do contents <- fileContents "/src/Day11/example2.txt" inChan <- newChan outChan <- newChan writeChan inChan (5 :: Integer) let values = parseInput contents ram = M.fromList (zip [0 ..] values) processOpCode ram 0 0 inChan outChan readChan outChan >>= print
package de.htwg_konstanz.ebus.wholesaler.main; import java.util.List; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.htwg_konstanz.ebus.framework.wholesaler.api.bo.BOSupplier; import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.SupplierBOA; public class XPathMethods { private static XPath xpath = XPathFactory.newInstance().newXPath(); private static SupplierBOA sboa = SupplierBOA.getInstance(); public static Integer getMaterialNumber(Node node) { String expression = "ARTICLE_DETAILS/EAN[1]"; Node materialNumber = null; try { materialNumber = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } if (materialNumber == null) { // TODO ########################## } int ean = Integer.parseInt(materialNumber.getFirstChild().getNodeValue()); return ean; } /** * * @return the BOSupplier if the supplier already exists, otherwise a new * created one ?! */ public static BOSupplier getSupplier(Node node) { String expression = "//SUPPLIER_NAME"; Node supplierNode = null; try { supplierNode = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } if (supplierNode == null) { // TODO ########################## } List<BOSupplier> suppliers = sboa.findAll(); // return suppliers.get(1); String suppliername = supplierNode.getFirstChild().getNodeValue(); boolean supplierExists = false; BOSupplier boSupplier = null; for (BOSupplier supplier : suppliers) { if (suppliername.equals(supplier.getCompanyname())) { supplierExists = true; boSupplier = supplier; break; } } if (supplierExists) return boSupplier; else { return null; } } /** * * @return a NodeList with all ARTICLEs found, or null */ public static NodeList getArticles(Node node) { String expression = "//ARTICLE"; NodeList nodes = null; try { nodes = (NodeList) xpath.evaluate(expression, node, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } return nodes; } /** * * @return a NodeList with all ARTICLEs found, or null */ public static String getShortdescription(Node node) { String expression = "ARTICLE_DETAILS/DESCRIPTION_SHORT[1]"; Node shortDescrNode = null; try { shortDescrNode = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return shortDescrNode.getFirstChild().getNodeValue(); } public static String getSupplierAid(Node node) { String expression = "SUPPLIER_AID[1]"; Node supplierAidNode = null; try { supplierAidNode = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return supplierAidNode.getFirstChild().getNodeValue(); } public static String getOrderNumber(Node node) { String supplier_aid = getSupplierAid(node); // To get the Header and the supplier name BOSupplier bosupplier = getSupplier(node.getParentNode().getParentNode()); if (bosupplier == null) return null; String supplier = bosupplier.getCompanyname(); String orderNumber = supplier_aid + supplier; return orderNumber; } public static NodeList getCountry(Node node) { String expression = "ARTICLE_PRICE_DETAILS/ARTICLE_PRICE"; NodeList articlePrices = null; try { articlePrices = (NodeList) xpath.evaluate(expression, node, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } return articlePrices; } public static NodeList getTerritories(Node node) { String expression = "TERRITORY"; NodeList territories = null; try { territories = (NodeList) xpath.evaluate(expression, node, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } return territories; } public static double getPriceAmount(Node node) { String expression = "PRICE_AMOUNT"; Node priceAmount = null; try { priceAmount = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return Double.parseDouble(priceAmount.getFirstChild().getNodeValue()); } public static double getTax(Node node) { String expression = "TAX"; Node tax = null; try { tax = (Node) xpath.evaluate(expression, node, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return Double.parseDouble(tax.getFirstChild().getNodeValue()); } public static String getOrderNumberSupplier(Node node) { String supplier_aid = getSupplierAid(node); if (supplier_aid == null) return "null"; return supplier_aid; } }
import { PlatformLocation } from '@angular/common'; import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/toPromise'; @Injectable() export class GeneralDataService { private onUserInfo: BehaviorSubject<any> = new BehaviorSubject<any>(null); private userInfo: any = null; // restrict to browser cache - not database private browserOnly: boolean = true; constructor( private http: Http, private platformLocation: PlatformLocation ) { } getBaseHref() : string { return this.platformLocation.getBaseHrefFromDOM() || '/'; } getApiUrl(action: string) : string { return this.getBaseHref() + 'api/' + action; } getBrowserUser() { let userKey = 'temp-user'; let sessionUser = sessionStorage.getItem(userKey); let user = null; try { user = sessionUser ? JSON.parse(sessionUser) : null; } catch(e) { } if(! user) { user = { accepted_terms_at: null, // "2018-09-14T05:46:24.165233Z", demo_user: true, surveys: [], user_id: userKey, }; sessionStorage.setItem(userKey, JSON.stringify(user)); } return user; } updateBrowserUser(params?: any) { let user = this.getBrowserUser(); if(params) Object.assign(user, params); sessionStorage.setItem('temp-user', JSON.stringify(user)); } clearSession() { sessionStorage.clear(); } quickExit() { let div = document.createElement('div'); div.style.background = '#fff'; div.style.position = 'absolute'; div.style.left = '0px'; div.style.top = '0px'; div.style.right = '0px'; div.style.bottom = '0px'; div.style.zIndex = '999999'; document.body.appendChild(div); this.clearSession(); document.title = ''; location.replace('https://www.google.com'); } loadJson(url: string, params?: any, headers?: any, relative?: boolean) : Promise<any> { if(! url) return Promise.reject('Cache name not defined'); if(relative) url = this.getBaseHref() + url; return this.http.get(url, { params, headers, withCredentials: true }) .map((x) => x.json()) .toPromise() .catch((error: any) => { return Promise.reject(error.message || error); }); } loadUserInfo(demo_login?: string) { if(this.browserOnly) { return new Promise(resolve => { try { let user = this.getBrowserUser(); this.returnUserInfo(user); resolve(user); } catch(e) { console.error(e); } }); } else { let headers = null; if(demo_login !== undefined) { headers = new Headers({'X-DEMO-LOGIN': demo_login}); } let url = this.getApiUrl('user-info'); return this.loadJson(url, { t: new Date().getTime() }, headers) .then((result) => { this.returnUserInfo(result); return result; }) .catch((error) => { console.log("Error loading user information:", error); this.returnUserInfo(null); return Promise.reject(error); }); } } logout() { if(this.browserOnly) { this.clearSession(); window.location.replace(this.getBaseHref()); } else if(this.userInfo && this.userInfo.demo_user) { // clear demo login cookie this.loadUserInfo('').then(() => { window.location.replace(this.getBaseHref()); }); } else { // redirect to siteminder logout URL // ... } } returnUserInfo(result) { console.log('user info:', result); this.userInfo = result; this.onUserInfo.next(result); } subscribeUserInfo(callb) { return this.onUserInfo.subscribe(callb); } requireLogin(no_terms?) { if(this.userInfo && this.userInfo.user_id && (no_terms || this.userInfo.accepted_terms_at)) { return Promise.resolve(this.userInfo); } return this.loadUserInfo().then((result) => { if(result && result.user_id) return result; return Promise.reject('Not logged in'); }); } acceptTerms() { if(this.browserOnly) { this.updateBrowserUser({accepted_terms_at: (new Date()).toString()}); return this.loadUserInfo(); } else { let url = this.getApiUrl('accept-terms'); return this.http.post(url, null, { withCredentials: true }) .map((x) => x.json()) .toPromise() .then((result) => this.loadUserInfo()); } } clearSurveyCache(name: string, key?: string, useLocal?: boolean) { if(! name) return Promise.reject('Cache name not defined'); let localKey = 'survey-' + name; if(this.browserOnly) { return new Promise(resolve => { if(key) sessionStorage.removeItem(localKey + '-key'); let index = this.getLocalSurveyCache(name, 'index', true); index = index ? index.result.filter(x => x.key !== key) : []; sessionStorage.setItem(localKey + '-index', JSON.stringify(index)); resolve(null); }); } if(useLocal) { localStorage.removeItem(localKey); } return this.saveSurveyCache(name, null, key); } loadSurveyCache(name: string, key?: string, useLocal?: boolean) { if(! name) return Promise.reject('Cache name not defined'); if(this.browserOnly) { return this.loadUserInfo().then(info => { if(! info.accepted_terms_at && key !== 'index') { return {accept_terms: true}; } return this.getLocalSurveyCache(name, key, true); }); } let url = this.getApiUrl('survey-cache/' + encodeURIComponent(name)); if(key) url += '/' + encodeURIComponent(key); return this.loadJson(url, { t: new Date().getTime() }) .then((result) => this.returnSurveyCache(name, key, result, null, useLocal)) .catch((err) => this.returnSurveyCache(name, key, null, err, useLocal)); } getLocalSurveyCache(name, key, session?) { let localKey = 'survey-' + name; let cached; if(session) { if(key === 'clear') { cached = sessionStorage.removeItem(localKey + '-latest'); return; } if(! key) key = sessionStorage.getItem(localKey + '-latest'); else if(key !== 'index') sessionStorage.setItem(localKey + '-latest', key); if(key) cached = sessionStorage.getItem(localKey + '-' + key); } else { cached = localStorage.getItem(localKey); } let result = null; if(cached) { cached = JSON.parse(cached); if(cached) { result = {'uid': null, 'local': true, 'key': key, 'result': cached}; } } return result; } saveLocalSurveyCache(name, data, key, session?) { let localKey = 'survey-' + name; if(session) { if(! key) key = '' + Math.random(); sessionStorage.setItem(localKey + '-' + key, JSON.stringify(data)); let index = this.getLocalSurveyCache(name, 'index', true); index = index ? index.result.filter(x => x.key !== key) : []; let idxCopy = Object.assign({}, data); delete idxCopy['data']; idxCopy['key'] = key; index.push(idxCopy); sessionStorage.setItem(localKey + '-index', JSON.stringify(index)); sessionStorage.setItem(localKey + '-latest', key); return key; } else { localStorage.setItem(localKey, JSON.stringify(data)); } } returnSurveyCache(name, key, result, err, useLocal?: boolean) { if((! result || ! result.key) && useLocal) { result = this.getLocalSurveyCache(name, key); } return result; } saveSurveyCache(name: string, data: object, key?: string, useLocal?: boolean) { if(! name) return Promise.reject('Cache name not defined'); if(this.browserOnly) { key = this.saveLocalSurveyCache(name, data, key, true); return Promise.resolve({'uid': null, 'local': true, 'key': key, 'status': 'ok', 'result': data}); } let url = this.getApiUrl('survey-cache/' + encodeURIComponent(name)); if(key) url += '/' + encodeURIComponent(key); let headers = new Headers({"Content-Type": "application/json"}); let postData = data === null ? '' : JSON.stringify(data); let savedLocal = false; if(useLocal && postData) { this.saveLocalSurveyCache(name, data, key); savedLocal = true; } return this.http.post(url, postData, { headers, withCredentials: true }) .map((result) => { let json = result.json(); if(json && json.key) json.result = data; return json; }) .toPromise() .catch((error: any) => { if(savedLocal) { return Promise.resolve({'uid': null, 'local': true, 'key': null, 'status': 'ok', 'result': data}); } return Promise.reject(error.message || error); }); } }
// CreateRedisClusterBackup creates a RedisClusterBackup in test namespace func (f *Framework) CreateRedisClusterBackup(instance *redisv1alpha1.RedisClusterBackup) error { f.Logf("Creating RedisClusterBackup %s", instance.Name) result := &redisv1alpha1.RedisClusterBackup{} err := f.Client.Get(context.TODO(), types.NamespacedName{ Namespace: f.Namespace(), Name: instance.Name, }, result) if errors.IsNotFound(err) { return f.Client.Create(context.TODO(), instance) } return err }
<reponame>rabelais88/fokus<filename>src/lib/useRouter.ts import { useHistory } from 'react-router-dom'; const useRouter = () => { const history = useHistory(); const redirect = (target: string) => history.push(target); return { redirect }; }; export default useRouter;
import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { ImportDialogComponent } from 'shared/dialogs/import/import-dialog.component'; import { TableImportUsersAction, TableImportUsersActionDef } from 'shared/table/actions/users/table-import-users-action'; import { AuthorizationService } from '../../../services/authorization.service'; import { CentralServerNotificationService } from '../../../services/central-server-notification.service'; import { CentralServerService } from '../../../services/central-server.service'; import { ComponentService } from '../../../services/component.service'; import { DialogService } from '../../../services/dialog.service'; import { MessageService } from '../../../services/message.service'; import { SpinnerService } from '../../../services/spinner.service'; import { WindowService } from '../../../services/window.service'; import { AppDatePipe } from '../../../shared/formatters/app-date.pipe'; import { TableAutoRefreshAction } from '../../../shared/table/actions/table-auto-refresh-action'; import { TableMoreAction } from '../../../shared/table/actions/table-more-action'; import { TableOpenURLActionDef } from '../../../shared/table/actions/table-open-url-action'; import { TableRefreshAction } from '../../../shared/table/actions/table-refresh-action'; import { TableNavigateToTransactionsAction } from '../../../shared/table/actions/transactions/table-navigate-to-transactions-action'; import { TableAssignSitesToUserAction, TableAssignSitesToUserActionDef } from '../../../shared/table/actions/users/table-assign-sites-to-user-action'; import { TableCreateUserAction, TableCreateUserActionDef } from '../../../shared/table/actions/users/table-create-user-action'; import { TableDeleteUserAction, TableDeleteUserActionDef } from '../../../shared/table/actions/users/table-delete-user-action'; import { TableEditUserAction, TableEditUserActionDef } from '../../../shared/table/actions/users/table-edit-user-action'; import { TableExportUsersAction, TableExportUsersActionDef } from '../../../shared/table/actions/users/table-export-users-action'; import { TableForceSyncBillingUserAction } from '../../../shared/table/actions/users/table-force-sync-billing-user-action'; import { TableNavigateToTagsAction } from '../../../shared/table/actions/users/table-navigate-to-tags-action'; import { TableSyncBillingUsersAction } from '../../../shared/table/actions/users/table-sync-billing-users-action'; import { IssuerFilter, organizations } from '../../../shared/table/filters/issuer-filter'; import { SiteTableFilter } from '../../../shared/table/filters/site-table-filter'; import { TagTableFilter } from '../../../shared/table/filters/tag-table-filter'; import { TableDataSource } from '../../../shared/table/table-data-source'; import { BillingButtonAction } from '../../../types/Billing'; import ChangeNotification from '../../../types/ChangeNotification'; import { DataResult } from '../../../types/DataResult'; import { TableActionDef, TableColumnDef, TableDef, TableFilterDef } from '../../../types/Table'; import { TenantComponents } from '../../../types/Tenant'; import { TransactionButtonAction } from '../../../types/Transaction'; import { User, UserButtonAction } from '../../../types/User'; import { Utils } from '../../../utils/Utils'; import { UserRoleFilter } from '../filters/user-role-filter'; import { UserStatusFilter } from '../filters/user-status-filter'; import { AppUserRolePipe } from '../formatters/user-role.pipe'; import { UserStatusFormatterComponent } from '../formatters/user-status-formatter.component'; import { UserSitesDialogComponent } from '../user-sites/user-sites-dialog.component'; import { UserDialogComponent } from '../user/user.dialog.component'; @Injectable() export class UsersListTableDataSource extends TableDataSource<User> { private editAction = new TableEditUserAction().getActionDef(); private assignSitesToUser = new TableAssignSitesToUserAction().getActionDef(); private deleteAction = new TableDeleteUserAction().getActionDef(); private syncBillingUsersAction = new TableSyncBillingUsersAction().getActionDef(); private forceSyncBillingUserAction = new TableForceSyncBillingUserAction().getActionDef(); private navigateToTagsAction = new TableNavigateToTagsAction().getActionDef(); private navigateToTransactionsAction = new TableNavigateToTransactionsAction().getActionDef(); public constructor( public spinnerService: SpinnerService, public translateService: TranslateService, private messageService: MessageService, private dialogService: DialogService, private router: Router, private dialog: MatDialog, private centralServerNotificationService: CentralServerNotificationService, private centralServerService: CentralServerService, private authorizationService: AuthorizationService, private componentService: ComponentService, private appUserRolePipe: AppUserRolePipe, private datePipe: AppDatePipe, private windowService: WindowService) { super(spinnerService, translateService); // Init if (this.authorizationService.hasSitesAdminRights()) { this.setStaticFilters([{ SiteID: this.authorizationService.getSitesAdmin().join('|') }]); } this.initDataSource(); this.initFilters(); } public initFilters() { // Tag const tagID = this.windowService.getSearch('TagID'); if (tagID) { const tagTableFilter = this.tableFiltersDef.find(filter => filter.id === 'tag'); if (tagTableFilter) { tagTableFilter.currentValue.push({ key: tagID, value: tagID, }); this.filterChanged(tagTableFilter); } } // Issuer const issuer = this.windowService.getSearch('Issuer'); if (issuer) { const issuerTableFilter = this.tableFiltersDef.find(filter => filter.id === 'issuer'); if (issuerTableFilter) { issuerTableFilter.currentValue = [organizations.find(organisation => organisation.key === issuer)]; this.filterChanged(issuerTableFilter); } } } public getDataChangeSubject(): Observable<ChangeNotification> { return this.centralServerNotificationService.getSubjectUsers(); } public loadDataImpl(): Observable<DataResult<User>> { return new Observable((observer) => { // Get the Tenants this.centralServerService.getUsers(this.buildFilterValues(), this.getPaging(), this.getSorting()).subscribe((users) => { // Ok observer.next(users); observer.complete(); }, (error) => { // Show error Utils.handleHttpError(error, this.router, this.messageService, this.centralServerService, 'general.error_backend'); // Error observer.error(error); }); }); } public buildTableDef(): TableDef { return { search: { enabled: true, }, hasDynamicRowAction: true, }; } public buildTableColumnDefs(): TableColumnDef[] { const loggedUserRole = this.centralServerService.getLoggedUser().role; const columns = []; columns.push( { id: 'status', name: 'users.status', isAngularComponent: true, angularComponent: UserStatusFormatterComponent, headerClass: 'col-10em text-center', class: 'col-10em table-cell-angular-big-component', sortable: true, }, { id: 'role', name: 'users.role', formatter: (role: string) => role ? this.translateService.instant(this.appUserRolePipe.transform(role, loggedUserRole)) : '-', headerClass: 'col-10em', class: 'text-left col-10em', sortable: true, }, { id: 'name', name: 'users.name', headerClass: 'col-15p', class: 'text-left col-15p', sorted: true, direction: 'asc', sortable: true, }, { id: 'firstName', name: 'users.first_name', headerClass: 'col-15p', class: 'text-left col-15p', sortable: true, }, { id: 'email', name: 'users.email', headerClass: 'col-20p', class: 'text-left col-20p', sortable: true, }, ); if (this.componentService.isActive(TenantComponents.BILLING)) { columns.push( { id: 'billingData.customerID', name: 'billing.id', headerClass: 'col-15p', class: 'col-15p', sortable: true, }, { id: 'billingData.lastChangedOn', name: 'billing.updated_on', headerClass: 'col-15p', formatter: (lastChangedOn: Date) => this.datePipe.transform(lastChangedOn), class: 'col-15p', sortable: true, }, ); } columns.push( { id: 'createdOn', name: 'users.created_on', formatter: (createdOn: Date) => this.datePipe.transform(createdOn), headerClass: 'col-15em', class: 'col-15em', sortable: true, }, { id: 'createdBy', name: 'users.created_by', formatter: (user: User) => Utils.buildUserFullName(user), headerClass: 'col-15em', class: 'col-15em', }, { id: 'lastChangedOn', name: 'users.changed_on', formatter: (lastChangedOn: Date) => this.datePipe.transform(lastChangedOn), headerClass: 'col-15em', class: 'col-15em', sortable: true, }, { id: 'lastChangedBy', name: 'users.changed_by', formatter: (user: User) => Utils.buildUserFullName(user), headerClass: 'col-15em', class: 'col-15em', }, { id: 'eulaAcceptedOn', name: 'users.eula_accepted_on', formatter: (eulaAcceptedOn: Date, row: User) => eulaAcceptedOn ? this.datePipe.transform(eulaAcceptedOn) + ` (${this.translateService.instant('general.version')} ${row.eulaAcceptedVersion})` : '-', headerClass: 'col-20em', class: 'col-20em', sortable: true, }, ); return columns as TableColumnDef[]; } public buildTableActionsDef(): TableActionDef[] { const tableActionsDef = super.buildTableActionsDef(); if (this.authorizationService.canExportUsers()) { tableActionsDef.unshift(new TableExportUsersAction().getActionDef()); } if (this.authorizationService.canImportUsers()) { tableActionsDef.unshift(new TableImportUsersAction().getActionDef()); } if (this.componentService.isActive(TenantComponents.BILLING) && this.authorizationService.canSynchronizeBillingUsers()) { tableActionsDef.unshift(this.syncBillingUsersAction); } if (this.authorizationService.canCreateUser()) { tableActionsDef.unshift(new TableCreateUserAction().getActionDef()); } return tableActionsDef; } public buildTableDynamicRowActions(user: User): TableActionDef[] { const rowActions: TableActionDef[] = []; const moreActions = new TableMoreAction([]); if (user.issuer) { if (user.canUpdate) { rowActions.push(this.editAction); } if (this.componentService.isActive(TenantComponents.ORGANIZATION)) { if (this.authorizationService.canListUsersSites()) { rowActions.push(this.assignSitesToUser); } } if (this.authorizationService.canListTokens()) { moreActions.addActionInMoreActions(this.navigateToTagsAction); } if (this.authorizationService.canListTransactions()) { moreActions.addActionInMoreActions(this.navigateToTransactionsAction); } if (this.componentService.isActive(TenantComponents.BILLING)) { if (this.authorizationService.canSynchronizeBillingUser()) { moreActions.addActionInMoreActions(this.forceSyncBillingUserAction); } } if (user.canDelete) { moreActions.addActionInMoreActions(this.deleteAction); } if (!Utils.isEmptyArray(moreActions.getActionsInMoreActions())) { rowActions.push(moreActions.getActionDef()); } } else { if (this.authorizationService.canListTokens()) { moreActions.addActionInMoreActions(this.navigateToTagsAction); } if (this.authorizationService.canListTransactions()) { moreActions.addActionInMoreActions(this.navigateToTransactionsAction); } if (user.canDelete) { moreActions.addActionInMoreActions(this.deleteAction); } if (!Utils.isEmptyArray(moreActions.getActionsInMoreActions())) { rowActions.push(moreActions.getActionDef()); } } return rowActions; } public actionTriggered(actionDef: TableActionDef) { // Action switch (actionDef.id) { case UserButtonAction.CREATE_USER: if (actionDef.action) { (actionDef as TableCreateUserActionDef).action(UserDialogComponent, this.dialog, this.refreshData.bind(this)); } break; case UserButtonAction.EXPORT_USERS: if (actionDef.action) { (actionDef as TableExportUsersActionDef).action(this.buildFilterValues(), this.dialogService, this.translateService, this.messageService, this.centralServerService, this.router, this.spinnerService); } break; case UserButtonAction.IMPORT_USERS: if (actionDef.action) { (actionDef as TableImportUsersActionDef).action(ImportDialogComponent, this.dialog); } break; case BillingButtonAction.SYNCHRONIZE_BILLING_USERS: if (this.syncBillingUsersAction.action) { this.syncBillingUsersAction.action( this.dialogService, this.translateService, this.messageService, this.centralServerService, this.router, ); } break; } } public rowActionTriggered(actionDef: TableActionDef, user: User) { switch (actionDef.id) { case UserButtonAction.EDIT_USER: if (actionDef.action) { (actionDef as TableEditUserActionDef).action(UserDialogComponent, this.dialog, { dialogData: user }, this.refreshData.bind(this)); } break; case UserButtonAction.ASSIGN_SITES_TO_USER: if (actionDef.action) { (actionDef as TableAssignSitesToUserActionDef).action( UserSitesDialogComponent, { dialogData: user }, this.dialog, this.refreshData.bind(this)); } break; case UserButtonAction.DELETE_USER: if (actionDef.action) { (actionDef as TableDeleteUserActionDef).action( user, this.dialogService, this.translateService, this.messageService, this.centralServerService, this.spinnerService, this.router, this.refreshData.bind(this)); } break; case UserButtonAction.BILLING_FORCE_SYNCHRONIZE_USER: if (this.forceSyncBillingUserAction.action) { this.forceSyncBillingUserAction.action( user, this.dialogService, this.translateService, this.spinnerService, this.messageService, this.centralServerService, this.router, this.refreshData.bind(this) ); } break; case UserButtonAction.NAVIGATE_TO_TAGS: if (actionDef.action) { (actionDef as TableOpenURLActionDef).action('users#tag?UserID=' + user.id + '&Issuer=' + user.issuer); } break; case TransactionButtonAction.NAVIGATE_TO_TRANSACTIONS: if (actionDef.action) { (actionDef as TableOpenURLActionDef).action('transactions#history?UserID=' + user.id + '&Issuer=' + user.issuer); } break; } } public buildTableActionsRightDef(): TableActionDef[] { return [ new TableAutoRefreshAction(false).getActionDef(), new TableRefreshAction().getActionDef(), ]; } public buildTableFiltersDef(): TableFilterDef[] { const issuerFilter = new IssuerFilter().getFilterDef(); return [ issuerFilter, new UserRoleFilter(this.centralServerService).getFilterDef(), new UserStatusFilter().getFilterDef(), new TagTableFilter([issuerFilter]).getFilterDef(), new SiteTableFilter([issuerFilter]).getFilterDef(), ]; } }
package com.linepro.modellbahn.util.exceptions; @FunctionalInterface public interface CheckedSupplier<V, E extends Throwable> { V get() throws E; }
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 main import ( "context" "encoding/base32" "fmt" "os" "path/filepath" "sync" "github.com/sirupsen/logrus" firecracker "github.com/firecracker-microvm/firecracker-go-sdk" "github.com/firecracker-microvm/firecracker-go-sdk/client/models" "github.com/firecracker-microvm/firecracker-containerd/internal" "github.com/firecracker-microvm/firecracker-containerd/proto" drivemount "github.com/firecracker-microvm/firecracker-containerd/proto/service/drivemount/ttrpc" ) const ( // fcSectorSize is the sector size of Firecracker drives fcSectorSize = 512 ) var ( // ErrDrivesExhausted occurs when there are no more drives left to use. This // can happen by calling PatchStubDrive greater than the number of drives. ErrDrivesExhausted = fmt.Errorf("There are no remaining drives to be used") ) // CreateContainerStubs will create a StubDriveHandler for managing the stub drives // of container rootfs drives. The Firecracker drives are hardcoded to be read-write // and have no rate limiter configuration. func CreateContainerStubs( machineCfg *firecracker.Config, jail jailer, containerCount int, logger *logrus.Entry, ) (*StubDriveHandler, error) { var containerStubs []*stubDrive for i := 0; i < containerCount; i++ { isWritable := true var rateLimiter *proto.FirecrackerRateLimiter stubFileName := fmt.Sprintf("ctrstub%d", i) stubDrive, err := newStubDrive( filepath.Join(jail.JailPath().RootPath(), stubFileName), jail, isWritable, rateLimiter, logger) if err != nil { return nil, fmt.Errorf("failed to create container stub drive: %w", err) } machineCfg.Drives = append(machineCfg.Drives, models.Drive{ DriveID: firecracker.String(stubDrive.driveID), PathOnHost: firecracker.String(stubDrive.stubPath), IsReadOnly: firecracker.Bool(!isWritable), RateLimiter: rateLimiterFromProto(rateLimiter), IsRootDevice: firecracker.Bool(false), }) containerStubs = append(containerStubs, stubDrive) } return &StubDriveHandler{ freeDrives: containerStubs, usedDrives: make(map[string]*stubDrive), }, nil } // StubDriveHandler manages a set of stub drives. It currently only supports reserving // one of the drives from its set. // In the future, it may be expanded to also support recycling a drive to be used again // for a different mount. type StubDriveHandler struct { freeDrives []*stubDrive // map of id -> stub drive being used by that task usedDrives map[string]*stubDrive mu sync.Mutex } // Reserve pops a unused stub drive and returns a MountableStubDrive that can be // mounted with the provided options as the patched drive information. func (h *StubDriveHandler) Reserve( requestCtx context.Context, id string, hostPath string, vmPath string, filesystemType string, options []string, driveMounter drivemount.DriveMounterService, machine firecracker.MachineIface, ) error { h.mu.Lock() defer h.mu.Unlock() if len(h.freeDrives) == 0 { return ErrDrivesExhausted } if _, ok := h.usedDrives[id]; ok { // This case means that drive wasn't released or removed properly return fmt.Errorf("drive with ID %s already in use, a previous attempt to remove it may have failed", id) } freeDrive := h.freeDrives[0] options, err := setReadWriteOptions(options, freeDrive.driveMount.IsWritable) if err != nil { return err } stubDrive := freeDrive.withMountConfig( hostPath, vmPath, filesystemType, options, ) freeDrive = &stubDrive err = stubDrive.PatchAndMount(requestCtx, machine, driveMounter) if err != nil { err = fmt.Errorf("failed to mount drive inside vm: %w", err) return err } h.freeDrives = h.freeDrives[1:] h.usedDrives[id] = freeDrive return nil } // Release unmounts stub drive of just deleted container // and pushes just released drive to freeDrives func (h *StubDriveHandler) Release( requestCtx context.Context, id string, driveMounter drivemount.DriveMounterService, machine firecracker.MachineIface, ) error { h.mu.Lock() defer h.mu.Unlock() drive, ok := h.usedDrives[id] if !ok { return fmt.Errorf("container %s drive was not found", id) } _, err := driveMounter.UnmountDrive(requestCtx, &drivemount.UnmountDriveRequest{ DriveID: drive.driveID, }) if err != nil { return fmt.Errorf("failed to unmount drive: %w", err) } err = machine.UpdateGuestDrive(requestCtx, drive.driveID, filepath.Base(drive.stubPath)) if err != nil { return fmt.Errorf("failed to patch drive: %w", err) } delete(h.usedDrives, id) h.freeDrives = append(h.freeDrives, drive) return nil } // CreateDriveMountStubs creates a set of MountableStubDrives from the provided DriveMount configs. // The RateLimiter and ReadOnly settings need to be provided up front here as they currently // cannot be patched after the Firecracker VM starts. func CreateDriveMountStubs( machineCfg *firecracker.Config, jail jailer, driveMounts []*proto.FirecrackerDriveMount, logger *logrus.Entry, ) ([]MountableStubDrive, error) { containerStubs := make([]MountableStubDrive, len(driveMounts)) for i, driveMount := range driveMounts { isWritable := driveMount.IsWritable rateLimiter := driveMount.RateLimiter cacheType := driveMount.CacheType stubFileName := fmt.Sprintf("drivemntstub%d", i) options, err := setReadWriteOptions(driveMount.Options, isWritable) if err != nil { return nil, err } stubDrive, err := newStubDrive( filepath.Join(jail.JailPath().RootPath(), stubFileName), jail, isWritable, rateLimiter, logger) if err != nil { return nil, fmt.Errorf("failed to create drive mount stub drive: %w", err) } stubDrive.setCacheType(cacheType) machineCfg.Drives = append(machineCfg.Drives, models.Drive{ DriveID: firecracker.String(stubDrive.driveID), PathOnHost: firecracker.String(stubDrive.stubPath), IsReadOnly: firecracker.Bool(!isWritable), RateLimiter: rateLimiterFromProto(rateLimiter), IsRootDevice: firecracker.Bool(false), CacheType: cacheTypeFromProto(cacheType), }) containerStubs[i] = stubDrive.withMountConfig( driveMount.HostPath, driveMount.VMPath, driveMount.FilesystemType, options) } return containerStubs, nil } func setReadWriteOptions(options []string, isWritable bool) ([]string, error) { var expectedOpt string if isWritable { expectedOpt = "rw" } else { expectedOpt = "ro" } for _, opt := range options { if opt == "ro" || opt == "rw" { if opt != expectedOpt { return nil, fmt.Errorf("mount option %s is incompatible with IsWritable=%t", opt, isWritable) } return options, nil } } // if here, the neither "ro" or "rw" was specified, so explicitly set the option for the user return append(options, expectedOpt), nil } // A MountableStubDrive represents a stub drive that is ready to be patched and mounted // once PatchAndMount is called. type MountableStubDrive interface { PatchAndMount( requestCtx context.Context, machine firecracker.MachineIface, driveMounter drivemount.DriveMounterService, ) error } func stubPathToDriveID(stubPath string) string { // Firecracker resource ids "can only contain alphanumeric characters and underscores", so // do a base32 encoding to remove any invalid characters (base32 avoids invalid "-" chars // from base64) return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString([]byte( filepath.Base(stubPath))) } func newStubDrive( stubPath string, jail jailer, isWritable bool, rateLimiter *proto.FirecrackerRateLimiter, logger *logrus.Entry, ) (*stubDrive, error) { // use the stubPath as the drive ID since it needs to be unique per-stubdrive anyways driveID := stubPathToDriveID(stubPath) f, err := os.OpenFile(stubPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) if err != nil { return nil, err } defer func() { if err := f.Close(); err != nil { logger.WithError(err).Errorf("unexpected error during %v close", f.Name()) } }() stubContent, err := internal.GenerateStubContent(driveID) if err != nil { return nil, err } if _, err := f.WriteString(stubContent); err != nil { return nil, err } info, err := f.Stat() if err != nil { return nil, err } fileSize := info.Size() sectorCount := fileSize / fcSectorSize driveSize := fcSectorSize * sectorCount remainingBytes := fileSize % fcSectorSize if remainingBytes != 0 { // If there are any residual bytes, this means we've need to fill the // appropriate sector size to ensure that the data is visible to // Firecracker. driveSize += fcSectorSize } // Firecracker will not show any drives smaller than 512 bytes. In // addition, the drive is read in chunks of 512 bytes; if the drive size is // not a multiple of 512 bytes, then the remainder will not be visible to // Firecracker. So we adjust to the appropriate size based on the residual // bytes remaining. if err := os.Truncate(stubPath, driveSize); err != nil { return nil, err } for _, opt := range jail.StubDrivesOptions() { err := opt(f) if err != nil { return nil, err } } return &stubDrive{ stubPath: stubPath, jail: jail, driveID: driveID, driveMount: &proto.FirecrackerDriveMount{ IsWritable: isWritable, RateLimiter: rateLimiter, }, }, nil } type stubDrive struct { stubPath string jail jailer driveID string driveMount *proto.FirecrackerDriveMount } func (sd stubDrive) withMountConfig( hostPath string, vmPath string, filesystemType string, options []string, ) stubDrive { sd.driveMount = &proto.FirecrackerDriveMount{ HostPath: hostPath, VMPath: vmPath, FilesystemType: filesystemType, Options: options, IsWritable: sd.driveMount.IsWritable, RateLimiter: sd.driveMount.RateLimiter, CacheType: sd.driveMount.CacheType, } return sd } func (sd stubDrive) PatchAndMount( requestCtx context.Context, machine firecracker.MachineIface, driveMounter drivemount.DriveMounterService, ) error { err := sd.jail.ExposeFileToJail(sd.driveMount.HostPath) if err != nil { return fmt.Errorf("failed to expose patched drive contents to jail: %w", err) } err = machine.UpdateGuestDrive(requestCtx, sd.driveID, sd.driveMount.HostPath) if err != nil { return fmt.Errorf("failed to patch drive: %w", err) } _, err = driveMounter.MountDrive(requestCtx, &drivemount.MountDriveRequest{ DriveID: sd.driveID, DestinationPath: sd.driveMount.VMPath, FilesytemType: sd.driveMount.FilesystemType, Options: sd.driveMount.Options, }) if err != nil { return fmt.Errorf("failed to mount newly patched drive: %w", err) } return nil } // CacheType sets the stub drive's cacheType value from the provided DriveMount configs. func (sd *stubDrive) setCacheType(cacheType string) { if cacheType != "" { sd.driveMount.CacheType = cacheType } }
package cn.lee.leetcode.weekly.w218; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; /** * @Title: Q5619 * @Description: https://leetcode-cn.com/contest/weekly-contest-218/problems/minimum-incompatibility/ * @author: libo * @date: 2020/12/6 11:04 * @Version: 1.0 */ @Slf4j public class Q5619 { @Test public void test() { Assert.assertEquals(4, minimumIncompatibility(new int[]{1, 2, 1, 4}, 2)); Assert.assertEquals(6, minimumIncompatibility(new int[]{6, 3, 8, 1, 3, 1, 2, 2}, 4)); Assert.assertEquals(-1, minimumIncompatibility(new int[]{5, 3, 3, 6, 3, 3}, 3)); } public int minimumIncompatibility(int[] nums, int k) { return 0; } }
package com.rudecrab.rbac.security; /** * 用户上下文对象,方便在系统中任何地方都能获取用户信息 * * @author RudeCrab */ public final class UserContext { private UserContext(){} private static final ThreadLocal<Long> USER = new ThreadLocal<>(); public static void add(Long id) { USER.set(id); } public static void remove() { USER.remove(); } /** * @return 当前登录用户的id */ public static Long getCurrentUserId() { return USER.get(); } }
mod serde; mod ty; use std::{path::Path, str::FromStr, sync::Arc}; use anyhow::Result; use druid::{ArcStr, Data}; use http::uri::PathAndQuery; use prost::bytes::Buf; use prost_types::{ FileDescriptorProto, FileDescriptorSet, MethodDescriptorProto, ServiceDescriptorProto, }; #[derive(Debug, Clone, Data)] pub struct FileSet { inner: Arc<FileSetInner>, } #[derive(Debug)] struct FileSetInner { raw: FileDescriptorSet, type_map: ty::TypeMap, services: Vec<ServiceInner>, } #[derive(Debug, Clone, Data)] pub struct Service { file_set: FileSet, index: usize, } #[derive(Debug)] struct ServiceInner { name: ArcStr, methods: Vec<MethodInner>, } #[derive(Debug, Clone, Data)] pub struct Method { service: Service, index: usize, } #[derive(Debug)] struct MethodInner { name: ArcStr, kind: MethodKind, path: PathAndQuery, request_ty: ty::TypeId, response_ty: ty::TypeId, } #[derive(Debug, Copy, Clone, Data, Eq, PartialEq)] pub enum MethodKind { Unary = 0b00, ClientStreaming = 0b01, ServerStreaming = 0b10, Streaming = 0b11, } #[derive(Debug, Clone, Data)] pub struct Message { file_set: FileSet, ty: ty::TypeId, } #[derive(Debug)] struct MessageInner { file_set: FileSet, index: usize, } impl FileSet { pub fn from_file<P>(path: P) -> Result<Self> where P: AsRef<Path>, { FileSet::from_bytes(fs_err::read(path)?.as_ref()) } pub fn from_bytes<B>(bytes: B) -> Result<Self> where B: Buf, { Ok(FileSet { inner: Arc::new(FileSet::from_raw(prost::Message::decode(bytes)?)?), }) } fn from_raw(raw: FileDescriptorSet) -> Result<FileSetInner> { let mut type_map = ty::TypeMap::new(); type_map.add_files(&raw)?; type_map.shrink_to_fit(); let type_map_ref = &type_map; let services = raw.file .iter() .flat_map(|raw_file| { raw_file.service.iter().map(move |raw_service| { Service::from_raw(raw_file, raw_service, type_map_ref) }) }) .collect::<Result<_>>()?; Ok(FileSetInner { raw, type_map, services, }) } pub fn to_bytes(&self) -> Vec<u8> { prost::Message::encode_to_vec(&self.inner.raw) } pub fn services(&self) -> impl ExactSizeIterator<Item = Service> + '_ { (0..self.inner.services.len()).map(move |index| Service { file_set: self.clone(), index, }) } pub fn get_service(&self, index: usize) -> Option<Service> { if index < self.inner.services.len() { Some(Service { file_set: self.clone(), index, }) } else { None } } pub fn get_message_by_name(&self, name: &str) -> Option<Message> { let ty = self.inner.type_map.get_by_name(name).ok()?; Some(Message { file_set: self.clone(), ty, }) } } impl Service { fn from_raw( raw_file: &FileDescriptorProto, raw_service: &ServiceDescriptorProto, type_map: &ty::TypeMap, ) -> Result<ServiceInner> { let methods = raw_service .method .iter() .map(|raw_method| Method::from_raw(raw_file, raw_service, raw_method, type_map)) .collect::<Result<_>>()?; Ok(ServiceInner { name: raw_service.name().into(), methods, }) } pub fn file_set(&self) -> &FileSet { &self.file_set } pub fn index(&self) -> usize { self.index } pub fn name(&self) -> ArcStr { self.inner().name.clone() } pub fn methods(&self) -> impl ExactSizeIterator<Item = Method> + '_ { (0..self.inner().methods.len()).map(move |index| Method { service: self.clone(), index, }) } pub fn get_method(&self, index: usize) -> Option<Method> { if index < self.inner().methods.len() { Some(Method { service: self.clone(), index, }) } else { None } } fn inner(&self) -> &ServiceInner { &self.file_set().inner.services[self.index] } } impl Method { fn from_raw( raw_file: &FileDescriptorProto, raw_service: &ServiceDescriptorProto, raw_method: &MethodDescriptorProto, type_map: &ty::TypeMap, ) -> Result<MethodInner> { let kind = match (raw_method.client_streaming(), raw_method.server_streaming()) { (false, false) => MethodKind::Unary, (true, false) => MethodKind::ClientStreaming, (false, true) => MethodKind::ServerStreaming, (true, true) => MethodKind::Streaming, }; let namespace = match raw_file.package() { "" => String::default(), package => format!(".{}", package), }; let path = PathAndQuery::from_str(&format!( "/{}{}/{}", namespace, raw_service.name(), raw_method.name() ))?; let request_ty = type_map.get_by_name(raw_method.input_type())?; let response_ty = type_map.get_by_name(raw_method.output_type())?; Ok(MethodInner { name: raw_method.name().into(), kind, path, request_ty, response_ty, }) } pub fn file_set(&self) -> &FileSet { self.service.file_set() } pub fn index(&self) -> usize { self.index } pub fn name(&self) -> ArcStr { self.inner().name.clone() } pub fn kind(&self) -> MethodKind { self.inner().kind } pub fn path(&self) -> PathAndQuery { self.inner().path.clone() } pub fn request(&self) -> Message { Message { file_set: self.file_set().clone(), ty: self.inner().request_ty, } } pub fn response(&self) -> Message { Message { file_set: self.file_set().clone(), ty: self.inner().response_ty, } } fn inner(&self) -> &MethodInner { &self.service.inner().methods[self.index] } } impl MethodKind { pub fn server_streaming(&self) -> bool { match *self { MethodKind::Unary | MethodKind::ClientStreaming => false, MethodKind::ServerStreaming | MethodKind::Streaming => true, } } pub fn client_streaming(&self) -> bool { match *self { MethodKind::Unary | MethodKind::ServerStreaming => false, MethodKind::ClientStreaming | MethodKind::Streaming => true, } } } impl Message { pub fn template_json(&self) -> String { self.file_set.inner.type_map.decode_template(self.ty) } pub fn decode(&self, protobuf: &[u8]) -> Result<String> { self.file_set.inner.type_map.decode(self.ty, protobuf) } pub fn encode(&self, json: &str) -> Result<Vec<u8>> { self.file_set.inner.type_map.encode(self.ty, json) } }
<gh_stars>0 package conf var ( LenStackBuf = 4096 LogLevel string LogPath string LogFlag int )
<reponame>farmerconnect/farmerconnect-ui import WizardSteps from './components/WizardSteps'; import Button from './components/Button'; import ActionInfotip from './components/ActionInfotip'; import IconCheck from './components/Icons/Check'; import IconClose from './components/Icons/Close'; import IconWarning from './components/Icons/Warning'; import NavigationBar from './components/NavigationBar'; import Loader from './components/Loader'; import * as Icon from './components/Icons'; import Row from './components/Row'; import Col from './components/Col'; import Container from './components/Container'; import Modal from './components/Modal'; import Radio from './components/Radio'; import CustomButton from './components/CustomButton'; import SingleSelect from './components/SingleSelect'; import DoubleSelect from './components/MultiSelect'; import Checkbox from './components/Checkbox'; import Tabs from './components/Tabs'; import SmallSelect from './components/SmallSelect'; import DropdownSelect from './components/DropdownSelect'; import Table from './components/Table'; import Tooltip from './components/Tooltip'; import Tag from './components/Tag'; import Dropdown from './components/Dropdown'; import FilterSelect from './components/FilterSelect'; import Input from './components/Input'; import Toggle from './components/Toggle'; import EditableLabel from './components/EditableLabel'; import TextArea from './components/TextArea'; import Card from './components/Card'; import Accordion from './components/Accordion'; import TagSelect from './components/TagSelect'; import InlineLoader from './components/InlineLoader'; import Breadcrumbs from './components/Breadcrumbs'; import Orderer from './components/Orderer'; import Infotip from './components/Infotip'; import DatePicker from './components/DatePicker'; import FileUpload from './components/FileUpload'; import ProgressBar from './components/ProgressBar'; import Select from './components/Select'; import LabelSwitch from './components/LabelSwitch'; import Colors from './components/Colors'; import Typography from './components/Typography'; import Alert from './components/Alert'; import Pagination from './components/Pagination'; import SearchInput from './components/SearchInput'; import Range from './components/Range'; import * as Mixins from './mixins'; import SmallInput from './components/SmallInput'; import * as Themes from './components/Theme'; export { WizardSteps, Button, ActionInfotip, IconCheck, IconClose, NavigationBar, IconWarning, Loader, Icon, Row, Col, Container, Modal, Radio, CustomButton, Checkbox, SingleSelect, DoubleSelect, Tabs, SmallSelect, DropdownSelect, Table, Tooltip, Tag, Dropdown, FilterSelect, Input, Toggle, EditableLabel, TextArea, Card, Accordion, TagSelect, InlineLoader, Breadcrumbs, Orderer, Infotip, DatePicker, FileUpload, ProgressBar, Select, LabelSwitch, Colors, Typography, Alert, Pagination, SearchInput, Mixins, Range, SmallInput, Themes, };
// // Copyright 2019 AT&T Intellectual Property // Copyright 2019 Nokia // // 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. // This source code is part of the near-RT RIC (RAN Intelligent Controller) // platform project (RICP). package services import ( "e2mgr/configuration" "e2mgr/logger" "e2mgr/mocks" "fmt" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common" "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities" "github.com/stretchr/testify/assert" "net" "strings" "testing" ) func setupRnibDataServiceTest(t *testing.T) (*rNibDataService, *mocks.RnibReaderMock, *mocks.RnibWriterMock) { return setupRnibDataServiceTestWithMaxAttempts(t, 3) } func setupRnibDataServiceTestWithMaxAttempts(t *testing.T, maxAttempts int) (*rNibDataService, *mocks.RnibReaderMock, *mocks.RnibWriterMock) { logger, err := logger.InitLogger(logger.DebugLevel) if err != nil { t.Errorf("#... - failed to initialize logger, error: %s", err) } config := &configuration.Configuration{RnibRetryIntervalMs: 10, MaxRnibConnectionAttempts: maxAttempts, RnibWriter: configuration.RnibWriterConfig{RanManipulationMessageChannel: "RAN_MANIPULATION", StateChangeMessageChannel: "RAN_CONNECTION_STATUS_CHANGE"}} readerMock := &mocks.RnibReaderMock{} writerMock := &mocks.RnibWriterMock{} rnibDataService := NewRnibDataService(logger, config, readerMock, writerMock) assert.NotNil(t, rnibDataService) return rnibDataService, readerMock, writerMock } func TestSuccessfulSaveNodeb(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("SaveNodeb", nodebInfo).Return(nil) rnibDataService.SaveNodeb(nodebInfo) writerMock.AssertNumberOfCalls(t, "SaveNodeb", 1) } func TestConnFailureSaveNodeb(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveNodeb", nodebInfo).Return(mockErr) rnibDataService.SaveNodeb(nodebInfo) writerMock.AssertNumberOfCalls(t, "SaveNodeb", 3) } func TestNonConnFailureSaveNodeb(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection failure")} writerMock.On("SaveNodeb", nodebInfo).Return(mockErr) rnibDataService.SaveNodeb(nodebInfo) writerMock.AssertNumberOfCalls(t, "SaveNodeb", 1) } func TestSuccessfulUpdateNodebInfo(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateNodebInfo", nodebInfo).Return(nil) rnibDataService.UpdateNodebInfo(nodebInfo) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfo", 1) } func TestConnFailureUpdateNodebInfo(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateNodebInfo", nodebInfo).Return(mockErr) rnibDataService.UpdateNodebInfo(nodebInfo) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfo", 3) } func TestSuccessfulUpdateNodebInfoAndPublish(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateNodebInfoAndPublish", nodebInfo).Return(nil) rnibDataService.UpdateNodebInfoAndPublish(nodebInfo) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfoAndPublish", 1) } func TestConnFailureUpdateNodebInfoAndPublish(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateNodebInfoAndPublish", nodebInfo).Return(mockErr) rnibDataService.UpdateNodebInfoAndPublish(nodebInfo) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfoAndPublish", 3) } func TestSuccessfulSaveRanLoadInformation(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) var ranName string = "abcd" ranLoadInformation := &entities.RanLoadInformation{} writerMock.On("SaveRanLoadInformation", ranName, ranLoadInformation).Return(nil) rnibDataService.SaveRanLoadInformation(ranName, ranLoadInformation) writerMock.AssertNumberOfCalls(t, "SaveRanLoadInformation", 1) } func TestConnFailureSaveRanLoadInformation(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) var ranName string = "abcd" ranLoadInformation := &entities.RanLoadInformation{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveRanLoadInformation", ranName, ranLoadInformation).Return(mockErr) rnibDataService.SaveRanLoadInformation(ranName, ranLoadInformation) writerMock.AssertNumberOfCalls(t, "SaveRanLoadInformation", 3) } func TestSuccessfulGetNodeb(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) invName := "abcd" nodebInfo := &entities.NodebInfo{} readerMock.On("GetNodeb", invName).Return(nodebInfo, nil) res, err := rnibDataService.GetNodeb(invName) readerMock.AssertNumberOfCalls(t, "GetNodeb", 1) assert.Equal(t, nodebInfo, res) assert.Nil(t, err) } func TestConnFailureGetNodeb(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) invName := "abcd" var nodeb *entities.NodebInfo = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetNodeb", invName).Return(nodeb, mockErr) res, err := rnibDataService.GetNodeb(invName) readerMock.AssertNumberOfCalls(t, "GetNodeb", 3) assert.True(t, strings.Contains(err.Error(), "connection error")) assert.Equal(t, nodeb, res) } func TestSuccessfulGetNodebIdList(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) nodeIds := []*entities.NbIdentity{} readerMock.On("GetListNodebIds").Return(nodeIds, nil) res, err := rnibDataService.GetListNodebIds() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 1) assert.Equal(t, nodeIds, res) assert.Nil(t, err) } func TestConnFailureGetNodebIdList(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var nodeIds []*entities.NbIdentity = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetListNodebIds").Return(nodeIds, mockErr) res, err := rnibDataService.GetListNodebIds() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 3) assert.True(t, strings.Contains(err.Error(), "connection error")) assert.Equal(t, nodeIds, res) } func TestConnFailureTwiceGetNodebIdList(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) invName := "abcd" var nodeb *entities.NodebInfo = nil var nodeIds []*entities.NbIdentity = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetNodeb", invName).Return(nodeb, mockErr) readerMock.On("GetListNodebIds").Return(nodeIds, mockErr) res, err := rnibDataService.GetListNodebIds() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 3) assert.True(t, strings.Contains(err.Error(), "connection error")) assert.Equal(t, nodeIds, res) res2, err := rnibDataService.GetNodeb(invName) readerMock.AssertNumberOfCalls(t, "GetNodeb", 3) assert.True(t, strings.Contains(err.Error(), "connection error")) assert.Equal(t, nodeb, res2) } func TestConnFailureWithAnotherConfig(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTestWithMaxAttempts(t, 5) var nodeIds []*entities.NbIdentity = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetListNodebIds").Return(nodeIds, mockErr) res, err := rnibDataService.GetListNodebIds() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 5) assert.True(t, strings.Contains(err.Error(), "connection error")) assert.Equal(t, nodeIds, res) } func TestGetGeneralConfigurationConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var config *entities.GeneralConfiguration = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetGeneralConfiguration").Return(config, mockErr) res, err := rnibDataService.GetGeneralConfiguration() readerMock.AssertNumberOfCalls(t, "GetGeneralConfiguration", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetGeneralConfigurationOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) config := &entities.GeneralConfiguration{} readerMock.On("GetGeneralConfiguration").Return(config, nil) res, err := rnibDataService.GetGeneralConfiguration() readerMock.AssertNumberOfCalls(t, "GetGeneralConfiguration", 1) assert.Equal(t, config, res) assert.Nil(t, err) } func TestGetGeneralConfigurationOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var config *entities.GeneralConfiguration = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetGeneralConfiguration").Return(config, mockErr) res, err := rnibDataService.GetGeneralConfiguration() readerMock.AssertNumberOfCalls(t, "GetGeneralConfiguration", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestSaveGeneralConfigurationConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) config := &entities.GeneralConfiguration{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveGeneralConfiguration", config).Return(mockErr) err := rnibDataService.SaveGeneralConfiguration(config) writerMock.AssertNumberOfCalls(t, "SaveGeneralConfiguration", 3) assert.NotNil(t, err) } func TestSaveGeneralConfigurationOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) config := &entities.GeneralConfiguration{} writerMock.On("SaveGeneralConfiguration", config).Return(nil) err := rnibDataService.SaveGeneralConfiguration(config) writerMock.AssertNumberOfCalls(t, "SaveGeneralConfiguration", 1) assert.Nil(t, err) } func TestSaveGeneralConfigurationOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) config := &entities.GeneralConfiguration{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("SaveGeneralConfiguration", config).Return(mockErr) err := rnibDataService.SaveGeneralConfiguration(config) writerMock.AssertNumberOfCalls(t, "SaveGeneralConfiguration", 1) assert.NotNil(t, err) } func TestRemoveServedCellsConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) var ranName string = "abcd" cellIds := []*entities.ServedCellInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("RemoveServedCells", ranName, cellIds).Return(mockErr) err := rnibDataService.RemoveServedCells(ranName, cellIds) writerMock.AssertNumberOfCalls(t, "RemoveServedCells", 3) assert.NotNil(t, err) } func TestRemoveServedCellsOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) var ranName string = "abcd" cellIds := []*entities.ServedCellInfo{} writerMock.On("RemoveServedCells", ranName, cellIds).Return(nil) err := rnibDataService.RemoveServedCells(ranName, cellIds) writerMock.AssertNumberOfCalls(t, "RemoveServedCells", 1) assert.Nil(t, err) } func TestRemoveServedCellsOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) var ranName string = "abcd" cellIds := []*entities.ServedCellInfo{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("RemoveServedCells", ranName, cellIds).Return(mockErr) err := rnibDataService.RemoveServedCells(ranName, cellIds) writerMock.AssertNumberOfCalls(t, "RemoveServedCells", 1) assert.NotNil(t, err) } func TestUpdateEnbConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} cellIds := []*entities.ServedCellInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateEnb", nodebInfo, cellIds).Return(mockErr) err := rnibDataService.UpdateEnb(nodebInfo, cellIds) writerMock.AssertNumberOfCalls(t, "UpdateEnb", 3) assert.NotNil(t, err) } func TestUpdateEnbOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} cellIds := []*entities.ServedCellInfo{} writerMock.On("UpdateEnb", nodebInfo, cellIds).Return(nil) err := rnibDataService.UpdateEnb(nodebInfo, cellIds) writerMock.AssertNumberOfCalls(t, "UpdateEnb", 1) assert.Nil(t, err) } func TestUpdateEnbOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} cellIds := []*entities.ServedCellInfo{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("UpdateEnb", nodebInfo, cellIds).Return(mockErr) err := rnibDataService.UpdateEnb(nodebInfo, cellIds) writerMock.AssertNumberOfCalls(t, "UpdateEnb", 1) assert.NotNil(t, err) } func TestAddEnbConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("AddEnb", nodebInfo).Return(mockErr) err := rnibDataService.AddEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "AddEnb", 3) assert.NotNil(t, err) } func TestAddEnbOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("AddEnb", nodebInfo).Return(nil) err := rnibDataService.AddEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "AddEnb", 1) assert.Nil(t, err) } func TestAddEnbOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("AddEnb", nodebInfo).Return(mockErr) err := rnibDataService.AddEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "AddEnb", 1) assert.NotNil(t, err) } func TestUpdateNbIdentityConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeId := &entities.NbIdentity{} newNodeId := &entities.NbIdentity{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateNbIdentities", gnbType, []*entities.NbIdentity{oldNodeId}, []*entities.NbIdentity{newNodeId}).Return(mockErr) err := rnibDataService.UpdateNbIdentity(gnbType, oldNodeId, newNodeId) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 3) assert.NotNil(t, err) } func TestUpdateNbIdentityOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeId := &entities.NbIdentity{} newNodeId := &entities.NbIdentity{} writerMock.On("UpdateNbIdentities", gnbType, []*entities.NbIdentity{oldNodeId}, []*entities.NbIdentity{newNodeId}).Return(nil) err := rnibDataService.UpdateNbIdentity(gnbType, oldNodeId, newNodeId) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 1) assert.Nil(t, err) } func TestUpdateNbIdentityOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeId := &entities.NbIdentity{} newNodeId := &entities.NbIdentity{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("UpdateNbIdentities", gnbType, []*entities.NbIdentity{oldNodeId}, []*entities.NbIdentity{newNodeId}).Return(mockErr) err := rnibDataService.UpdateNbIdentity(gnbType, oldNodeId, newNodeId) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 1) assert.NotNil(t, err) } func TestUpdateNbIdentitiesConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeIds := []*entities.NbIdentity{} newNodeIds := []*entities.NbIdentity{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateNbIdentities", gnbType, oldNodeIds, newNodeIds).Return(mockErr) err := rnibDataService.UpdateNbIdentities(gnbType, oldNodeIds, newNodeIds) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 3) assert.NotNil(t, err) } func TestUpdateNbIdentitiesOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeIds := []*entities.NbIdentity{} newNodeIds := []*entities.NbIdentity{} writerMock.On("UpdateNbIdentities", gnbType, oldNodeIds, newNodeIds).Return(nil) err := rnibDataService.UpdateNbIdentities(gnbType, oldNodeIds, newNodeIds) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 1) assert.Nil(t, err) } func TestUpdateNbIdentitiesOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) gnbType := entities.Node_GNB oldNodeIds := []*entities.NbIdentity{} newNodeIds := []*entities.NbIdentity{} mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("UpdateNbIdentities", gnbType, oldNodeIds, newNodeIds).Return(mockErr) err := rnibDataService.UpdateNbIdentities(gnbType, oldNodeIds, newNodeIds) writerMock.AssertNumberOfCalls(t, "UpdateNbIdentities", 1) assert.NotNil(t, err) } func TestPingRnibConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var nodeIds []*entities.NbIdentity = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetListNodebIds").Return(nodeIds, mockErr) res := rnibDataService.PingRnib() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 3) assert.False(t, res) } func TestPingRnibOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var nodeIds []*entities.NbIdentity = nil readerMock.On("GetListNodebIds").Return(nodeIds, nil) res := rnibDataService.PingRnib() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 1) assert.True(t, res) } func TestPingRnibOkOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var nodeIds []*entities.NbIdentity = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetListNodebIds").Return(nodeIds, mockErr) res := rnibDataService.PingRnib() readerMock.AssertNumberOfCalls(t, "GetListNodebIds", 1) assert.True(t, res) } func TestSuccessfulUpdateNodebInfoOnConnectionStatusInversion(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) event := "event" nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateNodebInfoOnConnectionStatusInversion", nodebInfo, event).Return(nil) rnibDataService.UpdateNodebInfoOnConnectionStatusInversion(nodebInfo, event) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfoOnConnectionStatusInversion", 1) } func TestConnFailureUpdateNodebInfoOnConnectionStatusInversion(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) event := "event" nodebInfo := &entities.NodebInfo{} mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("UpdateNodebInfoOnConnectionStatusInversion", nodebInfo, event).Return(mockErr) rnibDataService.UpdateNodebInfoOnConnectionStatusInversion(nodebInfo, event) writerMock.AssertNumberOfCalls(t, "UpdateNodebInfoOnConnectionStatusInversion", 3) } func TestGetE2TInstanceConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" var e2tInstance *entities.E2TInstance = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TInstance", address).Return(e2tInstance, mockErr) res, err := rnibDataService.GetE2TInstance(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstanceOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" e2tInstance := &entities.E2TInstance{} readerMock.On("GetE2TInstance", address).Return(e2tInstance, nil) res, err := rnibDataService.GetE2TInstance(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 1) assert.Nil(t, err) assert.Equal(t, e2tInstance, res) } func TestGetE2TInstanceOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" var e2tInstance *entities.E2TInstance = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TInstance", address).Return(e2tInstance, mockErr) res, err := rnibDataService.GetE2TInstance(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstanceNoLogsConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" var e2tInstance *entities.E2TInstance = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TInstance", address).Return(e2tInstance, mockErr) res, err := rnibDataService.GetE2TInstanceNoLogs(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstanceNoLogsOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" e2tInstance := &entities.E2TInstance{} readerMock.On("GetE2TInstance", address).Return(e2tInstance, nil) res, err := rnibDataService.GetE2TInstanceNoLogs(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 1) assert.Nil(t, err) assert.Equal(t, e2tInstance, res) } func TestGetE2TInstanceNoLogsOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) address := "10.10.5.20:3200" var e2tInstance *entities.E2TInstance = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TInstance", address).Return(e2tInstance, mockErr) res, err := rnibDataService.GetE2TInstanceNoLogs(address) readerMock.AssertNumberOfCalls(t, "GetE2TInstance", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstancesConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} var e2tInstances []*entities.E2TInstance = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TInstances", addresses).Return(e2tInstances, mockErr) res, err := rnibDataService.GetE2TInstances(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstancesOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} e2tInstance := []*entities.E2TInstance{} readerMock.On("GetE2TInstances", addresses).Return(e2tInstance, nil) res, err := rnibDataService.GetE2TInstances(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 1) assert.Nil(t, err) assert.Equal(t, e2tInstance, res) } func TestGetE2TInstancesOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} var e2tInstances []*entities.E2TInstance = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TInstances", addresses).Return(e2tInstances, mockErr) res, err := rnibDataService.GetE2TInstances(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstancesNoLogsConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} var e2tInstances []*entities.E2TInstance = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TInstances", addresses).Return(e2tInstances, mockErr) res, err := rnibDataService.GetE2TInstancesNoLogs(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TInstancesNoLogsOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} e2tInstance := []*entities.E2TInstance{} readerMock.On("GetE2TInstances", addresses).Return(e2tInstance, nil) res, err := rnibDataService.GetE2TInstancesNoLogs(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 1) assert.Nil(t, err) assert.Equal(t, e2tInstance, res) } func TestGetE2TInstancesNoLogsOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} var e2tInstances []*entities.E2TInstance = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TInstances", addresses).Return(e2tInstances, mockErr) res, err := rnibDataService.GetE2TInstancesNoLogs(addresses) readerMock.AssertNumberOfCalls(t, "GetE2TInstances", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TAddressesConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var addresses []string = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TAddresses").Return(addresses, mockErr) res, err := rnibDataService.GetE2TAddresses() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TAddressesOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} readerMock.On("GetE2TAddresses").Return(addresses, nil) res, err := rnibDataService.GetE2TAddresses() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 1) assert.Nil(t, err) assert.Equal(t, addresses, res) } func TestGetE2TAddressesOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var addresses []string = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TAddresses").Return(addresses, mockErr) res, err := rnibDataService.GetE2TAddresses() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TAddressesNoLogsConnFailure(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var addresses []string = nil mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} readerMock.On("GetE2TAddresses").Return(addresses, mockErr) res, err := rnibDataService.GetE2TAddressesNoLogs() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 3) assert.Nil(t, res) assert.NotNil(t, err) } func TestGetE2TAddressesNoLogsOkNoError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} readerMock.On("GetE2TAddresses").Return(addresses, nil) res, err := rnibDataService.GetE2TAddressesNoLogs() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 1) assert.Nil(t, err) assert.Equal(t, addresses, res) } func TestGetE2TAddressesNoLogsOtherError(t *testing.T) { rnibDataService, readerMock, _ := setupRnibDataServiceTest(t) var addresses []string = nil mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} readerMock.On("GetE2TAddresses").Return(addresses, mockErr) res, err := rnibDataService.GetE2TAddressesNoLogs() readerMock.AssertNumberOfCalls(t, "GetE2TAddresses", 1) assert.Nil(t, res) assert.NotNil(t, err) } func TestSaveE2TInstanceConnFailure(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveE2TInstance", e2tInstance).Return(mockErr) err := rnibDataService.SaveE2TInstance(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 3) assert.NotNil(t, err) } func TestSaveE2TInstanceOkNoError(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("SaveE2TInstance", e2tInstance).Return(nil) err := rnibDataService.SaveE2TInstance(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 1) assert.Nil(t, err) } func TestSaveE2TInstanceOtherError(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("SaveE2TInstance", e2tInstance).Return(mockErr) err := rnibDataService.SaveE2TInstance(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 1) assert.NotNil(t, err) } func TestSaveE2TInstanceNoLogsConnFailure(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveE2TInstance", e2tInstance).Return(mockErr) err := rnibDataService.SaveE2TInstanceNoLogs(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 3) assert.NotNil(t, err) } func TestSaveE2TInstanceNoLogsOkNoError(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("SaveE2TInstance", e2tInstance).Return(nil) err := rnibDataService.SaveE2TInstanceNoLogs(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 1) assert.Nil(t, err) } func TestSaveE2TInstanceNoLogsOtherError(t *testing.T) { e2tInstance := &entities.E2TInstance{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("SaveE2TInstance", e2tInstance).Return(mockErr) err := rnibDataService.SaveE2TInstanceNoLogs(e2tInstance) writerMock.AssertNumberOfCalls(t, "SaveE2TInstance", 1) assert.NotNil(t, err) } func TestSaveE2TAddressesConnFailure(t *testing.T) { addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("SaveE2TAddresses", addresses).Return(mockErr) err := rnibDataService.SaveE2TAddresses(addresses) writerMock.AssertNumberOfCalls(t, "SaveE2TAddresses", 3) assert.NotNil(t, err) } func TestSaveE2TAddressesOkNoError(t *testing.T) { addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("SaveE2TAddresses", addresses).Return(nil) err := rnibDataService.SaveE2TAddresses(addresses) writerMock.AssertNumberOfCalls(t, "SaveE2TAddresses", 1) assert.Nil(t, err) } func TestSaveE2TAddressesOtherError(t *testing.T) { addresses := []string{"10.10.5.20:3200", "10.10.5.21:3200"} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("SaveE2TAddresses", addresses).Return(mockErr) err := rnibDataService.SaveE2TAddresses(addresses) writerMock.AssertNumberOfCalls(t, "SaveE2TAddresses", 1) assert.NotNil(t, err) } func TestRemoveE2TInstanceConnFailure(t *testing.T) { address := "10.10.5.20:3200" rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("RemoveE2TInstance", address).Return(mockErr) err := rnibDataService.RemoveE2TInstance(address) writerMock.AssertNumberOfCalls(t, "RemoveE2TInstance", 3) assert.NotNil(t, err) } func TestRemoveE2TInstanceOkNoError(t *testing.T) { address := "10.10.5.20:3200" rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("RemoveE2TInstance", address).Return(nil) err := rnibDataService.RemoveE2TInstance(address) writerMock.AssertNumberOfCalls(t, "RemoveE2TInstance", 1) assert.Nil(t, err) } func TestRemoveE2TInstanceOtherError(t *testing.T) { address := "10.10.5.20:3200" rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("RemoveE2TInstance", address).Return(mockErr) err := rnibDataService.RemoveE2TInstance(address) writerMock.AssertNumberOfCalls(t, "RemoveE2TInstance", 1) assert.NotNil(t, err) } func TestAddNbIdentityConnFailure(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("AddNbIdentity", gnbType, nbIdentity).Return(mockErr) err := rnibDataService.AddNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "AddNbIdentity", 3) assert.NotNil(t, err) } func TestAddNbIdentityOkNoError(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("AddNbIdentity", gnbType, nbIdentity).Return(nil) err := rnibDataService.AddNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "AddNbIdentity", 1) assert.Nil(t, err) } func TestAddNbIdentityOtherError(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("AddNbIdentity", gnbType, nbIdentity).Return(mockErr) err := rnibDataService.AddNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "AddNbIdentity", 1) assert.NotNil(t, err) } func TestRemoveNbIdentityConnFailure(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("RemoveNbIdentity", gnbType, nbIdentity).Return(mockErr) err := rnibDataService.RemoveNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "RemoveNbIdentity", 3) assert.NotNil(t, err) } func TestRemoveNbIdentityOkNoError(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("RemoveNbIdentity", gnbType, nbIdentity).Return(nil) err := rnibDataService.RemoveNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "RemoveNbIdentity", 1) assert.Nil(t, err) } func TestRemoveNbIdentityOtherError(t *testing.T) { gnbType := entities.Node_GNB nbIdentity := &entities.NbIdentity{} rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("RemoveNbIdentity", gnbType, nbIdentity).Return(mockErr) err := rnibDataService.RemoveNbIdentity(gnbType, nbIdentity) writerMock.AssertNumberOfCalls(t, "RemoveNbIdentity", 1) assert.NotNil(t, err) } func TestRemoveServedNrCellsConnFailure(t *testing.T) { var ranName string = "abcd" var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} writerMock.On("RemoveServedNrCells", ranName, servedNrCells).Return(mockErr) err := rnibDataService.RemoveServedNrCells(ranName, servedNrCells) writerMock.AssertNumberOfCalls(t, "RemoveServedNrCells", 3) assert.NotNil(t, err) } func TestRemoveServedNrCellsOkNoError(t *testing.T) { var ranName string = "abcd" var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) writerMock.On("RemoveServedNrCells", ranName, servedNrCells).Return(nil) err := rnibDataService.RemoveServedNrCells(ranName, servedNrCells) writerMock.AssertNumberOfCalls(t, "RemoveServedNrCells", 1) assert.Nil(t, err) } func TestRemoveServedNrCellsOtherError(t *testing.T) { var ranName string = "abcd" var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} writerMock.On("RemoveServedNrCells", ranName, servedNrCells).Return(mockErr) err := rnibDataService.RemoveServedNrCells(ranName, servedNrCells) writerMock.AssertNumberOfCalls(t, "RemoveServedNrCells", 1) assert.NotNil(t, err) } func TestRemoveEnbConnFailure(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} nodebInfo := &entities.NodebInfo{} writerMock.On("RemoveEnb", nodebInfo).Return(mockErr) err := rnibDataService.RemoveEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "RemoveEnb", 3) assert.NotNil(t, err) } func TestRemoveEnbOkNoError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("RemoveEnb", nodebInfo).Return(nil) err := rnibDataService.RemoveEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "RemoveEnb", 1) assert.Nil(t, err) } func TestRemoveEnbOtherError(t *testing.T) { rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} nodebInfo := &entities.NodebInfo{} writerMock.On("RemoveEnb", nodebInfo).Return(mockErr) err := rnibDataService.RemoveEnb(nodebInfo) writerMock.AssertNumberOfCalls(t, "RemoveEnb", 1) assert.NotNil(t, err) } func TestUpdateGnbCellsConnFailure(t *testing.T) { var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: &net.OpError{Err: fmt.Errorf("connection error")}} nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateGnbCells", nodebInfo, servedNrCells).Return(mockErr) err := rnibDataService.UpdateGnbCells(nodebInfo, servedNrCells) writerMock.AssertNumberOfCalls(t, "UpdateGnbCells", 3) assert.NotNil(t, err) } func TestUpdateGnbCellsOkNoError(t *testing.T) { var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateGnbCells", nodebInfo, servedNrCells).Return(nil) err := rnibDataService.UpdateGnbCells(nodebInfo, servedNrCells) writerMock.AssertNumberOfCalls(t, "UpdateGnbCells", 1) assert.Nil(t, err) } func TestUpdateGnbCellsOtherError(t *testing.T) { var servedNrCells []*entities.ServedNRCell rnibDataService, _, writerMock := setupRnibDataServiceTest(t) mockErr := &common.InternalError{Err: fmt.Errorf("non connection error")} nodebInfo := &entities.NodebInfo{} writerMock.On("UpdateGnbCells", nodebInfo, servedNrCells).Return(mockErr) err := rnibDataService.UpdateGnbCells(nodebInfo, servedNrCells) writerMock.AssertNumberOfCalls(t, "UpdateGnbCells", 1) assert.NotNil(t, err) }
//Invoke call the registered function func (f *Fun) Invoke(que *val.ByteQue) *val.ByteQue { v, e := que.Pop("string") if e != nil { return except(e.Error()) } name := v.(string) fun, ok := f.funs[name] if !ok { return except(name + " function not found") } typ := strings.ReplaceAll(fun.Type().String(), " ", "") lix := strings.Index(typ, ")") pts := strings.Split(typ[strings.Index(typ, "(")+1:lix], ",") pas := make([]reflect.Value, len(pts)) for i := 0; i < len(pas); i++ { if que.Len() == 0 { return except("error when calling function " + name + " to restore parameters to the " + strconv.Itoa(i) + "th parameter " + pts[i]) } v, e := que.Pop(pts[i]) if e != nil { return except("error when calling function " + name + " to restore parameters to the " + strconv.Itoa(i) + "th parameter " + pts[i] + ": " + e.Error()) } pas[i] = reflect.ValueOf(v) } if que.Len() != 0 { return except("error when calling function " + name + " to restore parameters") } ret := val.NewByteQue() ret.Push(false) rts := strings.ReplaceAll(strings.ReplaceAll(typ[lix+1:], "(", ""), ")", "") if len(rts) > 0 { rts := strings.Split(rts, ",") rss := fun.Call(pas) for i := 0; i < len(rts); i++ { if rts[i] == "error" { if rss[i].Interface() != nil { return except(rss[i].Interface().(error).Error()) } } else { if rss[i].Interface() == nil { return except("the function return value cannot have nil except error") } if e := ret.Push(rss[i].Interface()); e != nil { return except(e.Error() + " when calling function " + name + " to store result " + strconv.Itoa(i)) } } } } else { fun.Call(pas) } return ret }
import heapq,math from collections import defaultdict,deque import sys, os.path #sys.setrecursionlimit(10000000) if(os.path.exists('C:/Users/Dhanush/Desktop/cp/input.txt')): sys.stdout = open('C:/Users/Dhanush/Desktop/cp/output.txt', 'w') sys.stdin = open('C:/Users/Dhanush/Desktop/cp/input.txt', 'r') input=sys.stdin.readline mod=10**9+7 s=input().strip() n=len(s) ns=[] for i in range(n): if(s[i]=='a' or s[i]=='b'): ns.append(s[i]) s="".join(ns) n=len(ns) i=0 l=[] while(i<n): while(i<n and s[i]=='b'): i+=1 cnt=0 while(i<n and s[i]=='a'): i+=1 cnt+=1 if(cnt>0): l.append(cnt) #print(l) if(len(l)==0): print(0) else: ans=l[0]+1 for i in range(1,len(l)): ans=(ans*(l[i]+1))%mod print(ans-1)
<gh_stars>1-10 import os from conans import ConanFile required_conan_version = ">=1.33.0" class RenderContextConan(ConanFile): python_requires = "base_conanfile/v0.2.0@jgsogo/stable" python_requires_extend = "base_conanfile.BaseCMakeConanfile" name = "render_context" homepage = "https://github.com/jgsogo/render_context" description = "Utilities to draw elements using Magnum with ImGUI integration" topics = ("cpp20", "magnum", "imgui") license = "MIT" def validate(self): self._validate_cppstd("20") def requirements(self): self.requires("imgui/cci.20211117+docking@jgsogo/stable") self.requires("magnum/2020.06@jgsogo/stable") self.requires("magnum-integration/2020.06") def package_info(self): self.cpp_info.defines.append("IMGUI_USER_CONFIG=\"{}\"".format(str(os.path.join(self.package_folder, "include", "render", "imgui", "imconfig.h")))) self.cpp_info.requires = ['magnum::magnum_main', 'imgui::imgui', 'magnum-integration::imgui'] self.cpp_info.libs = ['units', 'render_imgui']
From A Life Term To Life On The Outside: When Aging Felons Are Freed Enlarge this image toggle caption Brandon Chew/NPR Brandon Chew/NPR When Karriem Saleem El-Amin went to prison in 1971 for the murder of Baltimore grocer David Lermer during a robbery, he was an 18-year-old killer named William Collins. In 2013, El-Amin left prison after serving 42 years, 3 months and 3 days. Today, he is 60 years old, back in the city of his youth, converted to Islam, subdued by age and often baffled by the experience of freedom. Little things, like dining in a restaurant, can be disorienting. "I'm full, I'm enjoying the company of my family. And at some time, I guess maybe 30 or 40 minutes had passed, I'm feeling uneasy," El-Amin says. "Because I'm so used to having The Man telling me it's time to go." El-Amin is one of more than 130 prisoners serving life sentences for violent crimes in the state of Maryland who were freed on probation following a landmark ruling by the state's highest court. As a condition of their release, the prisoners received social services and other special preparations. And so far, none of them has re-offended. The affected prisoners were convicted at least 35 years ago; their average age now is 64. They aged behind bars. Their bodies, which used to brawl and run, now ache and strain. "One time I wouldn't even consider it, play basketball from the sun up to sun down, in the dark, in the snow," El-Amin says. "But you mature, you see that your knees ain't like that no more. ... Father Time steps in and you have to make the adjustments." The return of El-Amin and others to life on the outside has encouraged advocates of more liberal parole policies, infuriated the families of their victims, and raised questions about what a life sentence really means. toggle caption Brandon Chew/NPR Unusual Legal Twist In Maryland The released prisoners were all convicted of felonies in jury trials before 1981. They're out as the result of a strange instruction that Maryland judges were required to give to juries until that year. At the end of every criminal trial in the state, explains Tony Gioia, Baltimore's deputy state's attorney, the judge told the jury that "they are the judges of the facts and the law and that whatever the court said to the jury was advisory only." As contradictory as it may be to common understanding of what juries and judges do — it's what judges in Maryland instructed juries for decades. Here is a typical judge's instruction to the jurors in a trial from before 1981: "You, ladies and gentlemen, are the judges of not only the facts, as you are on every case, but on the law as well. It is your responsibility to determine for yourselves what the law is. Everything I say to you is advisory only. You are free to find the law to be other than what the court says it is. We have given you our best opinion about the matter but the final determination — that is solely in your hands." Law LISTEN: Part 1: More Than 130 Maryland Lifers Adjust To Freedom After Court Ruling More Than 130 Maryland Lifers Adjust To Freedom After Court Ruling Listen · 11:21 11:21 In other words, principles such as the presumption of innocence and the standard of proof beyond a reasonable doubt? Just "advice" from the bench — take it or leave it. By 1980, Maryland was the only state that was giving such an instruction, says Michael Millemann, a professor and expert in public interest law at the University of Maryland's Carey School of Law. In the early 1980s, Maryland's highest court finally put a stop to the practice. But for more than 30 years, in various cases, the state's Court of Appeals said that convictions from trials using the old jury instruction were still valid. Then, in 2012, in a case brought by a Maryland inmate, the court changed its position. In Unger v. State, the court ruled that people convicted on the basis of the old jury charge had been denied due process — and were entitled to a new trial. By that time, there were only about 250 people behind bars who were affected. They were serving long sentences for serious crimes committed more than 30 years earlier. Preparing For Life On The Outside El-Amin was one of them. Like him, 90 percent of the affected prisoners are African-American. Millemann, who has a long background in legal aid and advocacy for prisoners, notes that 40 years ago, blacks were often charged with more serious offenses than whites for the same crime. Of the 250 Unger prisoners, all but one are men; they typically entered prison at age 24 and served 40 years. Some of them will be retried. But for most, Millemann and prosecutor Gioia negotiate the terms of their release. The prisoners have to concede their guilt, abandon further appeals and be resentenced to time served. They are released on probation only after there is a plan for where they will live. A single probation violation sends them back to prison, with no chance to get out. The assistance they receive from social workers is key to their success outside prison, Gioia says. The social workers help those released secure everything from housing and clothing to bus passes, telephones and information on where to get food. toggle caption Brandon Chew/NPR Rebecca Bowman-Rivas, who runs the social work clinic at the University of Maryland's law school and oversees some of the Unger cases, says some of the prisoners even need help establishing who they are. "We've had one gentleman who found out that he had a completely different father and a different name on his birth certificate," she says. "We've seen a few where there was no name; it just said 'Baby.' " People incarcerated for decades also grapple with the "Rip Van Winkle effect." They can be thrown by pedestrians speaking on Bluetooth while walking alone and by buses that bend at the middle. Some of the released prisoners have outlived their family, including their children. And for many, Bowman-Rivas says, there is also a delayed grief. "When you're in prison, it's not really a safe place to deal with emotional issues," she says. "We have a lot of folks who lost their parents while they were incarcerated, or siblings, and when they get out, it's when it really starts to come back to them or when they go see the gravesite for the first time." Despite these hurdles, the lifers released in Maryland have a perfect record so far. But that perfect record has not impressed families of the murder victims. For Victims, A Painful Injustice Shirley Rubin says she can remember "every single detail" of the day in 1972 when she and her husband, Benjamin, were shot during a robbery at their Baltimore grocery store. He was killed; she was left with a bullet lodged in her hip. When the gunman was sentenced to life in prison plus 36 years, Rubin was confident he would be locked up until he died. Four decades later, she learned he was getting out of prison. "They released him; shame on them," Rubin, now 92, says. "And that's an injustice to me." Photos of her children and grandchildren fill the living room of her Baltimore home. Talking about the shooting, which happened more than 40 years ago, Rubin's anger is still palpable. "My husband missed everything. He missed all his grandchildren; he missed his great-grandchildren," Rubin says. "And I don't care what the case of Unger was, it had nothing to do with this. The man committed a terrible crime and he should have been punished for the rest of his life." Karen Wilson also remembers getting the "Unger call" from a woman in the state's attorney's office. The man convicted of killing her father in 1969, restaurant owner Joseph Wilson, was getting out. Enlarge this image toggle caption Emily Bogle/NPR Emily Bogle/NPR "She spoke about 10 minutes and I finally said, 'Are you trying to tell me that he's getting out of prison?' " Wilson recalls. "And she said, 'Yes.' " Wilson is Karen's maiden name — for privacy reasons, NPR is not using her married name. It was as Karen Wilson that she attended a hearing prior to the release of her father's killer. She told him of the devastation he caused her family: her mother's subsequent poverty, her sister's descent into depression and suicide. Enlarge this image toggle caption Emily Bogle/NPR Emily Bogle/NPR As a Christian whose faith has deepened in recent years, Wilson says she has forgiven her father's killer. His release from prison is something else. "I think that every last one of these people should still be in prison. They're still guilty; I don't care about the jury instruction. I don't believe that was an issue at all," she says. "I've served on juries and none of the jury instructions made any sense to me so I think the average person doesn't understand their jury instructions." What Unger Says About Aging Lifers During the time since the crimes covered by Unger decision, conventional thinking about sentencing has changed dramatically. Back then, a life sentence in Maryland typically meant a convict went to prison, stayed out of trouble, took part in prison programs and would be out on parole in 20 years. William Gardner went to prison in 1968 at age 16 for killing Baltimore cab driver Henry Kravetz. He was among those who experienced the old state policy on incarceration. "Especially when we first got in there, there was a lot of emphasis on rehabilitation, so we had an opportunity to go to school, college, obtain trades," Gardner says. "But at the end, the money that they invested in the rehabilitation, it kind of got lost." By the mid-1990s, all that changed. The governor canceled those programs and blocked parole for all prisoners serving life. The slogan of the day was: Life means life. Their life sentences turned literal, until the reprieve afforded by Unger. So why have so many lifers left prison without re-offending? One answer is that the Maryland prisoners who have been released were always good candidates for parole. This group also has benefited from the social workers on the prisoners' cases. And then there's the simple fact that they're old. The freedom of the Unger prisoners may never be accepted by the people whose lives they shattered. But so far, the would-be lifers have demonstrated they can walk the straight and narrow — provided they have some help.
package ru.job4j.servlet; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import java.sql.*; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import ru.job4j.crudservlet.User; /** * @author <NAME> * @version $Id$ * @since 0.1 */ public class PoolSQL { private final static Logger LOG = Logger.getLogger(PoolSQL.class); private Connection connection; private PreparedStatement preparedStatement; private static final PoolingDataSource POOL = new PoolingDataSource(); public PoolSQL() { try { Class.forName("org.postgresql.Driver"); DriverManagerConnectionFactory dmcf = new DriverManagerConnectionFactory( "jdbc:postgresql://localhost:5432/crud", "postgres", "Qwerty<PASSWORD>"); new PoolableConnectionFactory(dmcf, new GenericObjectPool() { { POOL.setPool(this); } }, null, null, false, true); createTable(); if (isEmpty()) { addUser(new User("root", "root", "root@root", "admin")); } } catch (ClassNotFoundException e) { LOG.error(String.format("Proble start connect: %s", e)); } } private void connect() { try { connection = POOL.getConnection(); } catch (SQLException e) { LOG.error(String.format("Problem get connect: %s", e)); } } private void disconnect() { if (connection != null) { try { connection.close(); connection = null; } catch (SQLException e) { LOG.error(String.format("Problem disconect connect: %s", e)); } } if (preparedStatement != null) { try { preparedStatement.close(); preparedStatement = null; } catch (SQLException e) { LOG.error(String.format("Problem disconect Prepared Statement: %s", e)); } } } public void createTable() { connect(); try { preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS crud ".concat( "(id serial PRIMARY KEY, ").concat( "name CHARACTER VARYING(100) NOT NULL, ").concat( "login CHARACTER VARYING(100) NOT NULL, ").concat( "email CHARACTER VARYING(100) NOT NULL, ").concat( "role CHARACTER VARYING(100) NOT NULL, ").concat( "createdate TIMESTAMP NOT NULL);")); preparedStatement.executeUpdate(); } catch (SQLException e) { LOG.error(String.format("Problem create table: %s", e)); } finally { disconnect(); } } private boolean isEmpty() { connect(); boolean rezult = false; try { preparedStatement = connection.prepareStatement("SELECT * FROM crud;"); ResultSet rs = preparedStatement.executeQuery(); if (!rs.next()) { rezult = true; } } catch (SQLException e) { LOG.error(String.format("Problem test empty: %s", e)); } finally { disconnect(); } return rezult; } public void addUser(User user) { connect(); try { preparedStatement = connection.prepareStatement("INSERT INTO crud (name, login, email, role, createdate) VALUES (?, ?, ?, ?, ?);"); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getLogin()); preparedStatement.setString(3, user.getEmail()); preparedStatement.setString(4, user.getRole()); preparedStatement.setTimestamp(5, new Timestamp(user.getCreatedate().getTime())); preparedStatement.executeUpdate(); } catch (SQLException e) { LOG.error(String.format("Problem add user: %s", e)); } finally { disconnect(); } } public void updateUser(String id, User user) { connect(); try { preparedStatement = connection.prepareStatement("UPDATE crud SET name = ?, email = ?, role = ?, createdate = ? WHERE id = ?;"); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getEmail()); preparedStatement.setString(3, user.getRole()); preparedStatement.setTimestamp(4, new Timestamp(user.getCreatedate().getTime())); preparedStatement.setInt(5, Integer.valueOf(id)); preparedStatement.executeUpdate(); } catch (SQLException e) { LOG.error(String.format("Problem update user: %s", e)); } finally { disconnect(); } } public void delUser(String id) { connect(); try { preparedStatement = connection.prepareStatement("DELETE FROM crud WHERE id = ?;"); preparedStatement.setInt(1, Integer.valueOf(id)); preparedStatement.executeUpdate(); } catch (SQLException e) { LOG.error(String.format("Problem del(id): %s", e)); } finally { disconnect(); } } public List<User> getUsers() { List<User> list = new LinkedList<>(); connect(); try { preparedStatement = connection.prepareStatement("SELECT * FROM crud ORDER BY id;"); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getString(1)); user.setName(rs.getString(2)); user.setLogin(rs.getString(3)); user.setEmail(rs.getString(4)); user.setRole(rs.getString(5)); user.setCreatedate(new Date(rs.getTimestamp(6).getTime())); list.add(user); } } catch (SQLException e) { LOG.error(String.format("Problem get list users: %s", e)); } finally { disconnect(); } return list; } public List<String> getRoles() { List<String> list = new LinkedList<>(); connect(); try { preparedStatement = connection.prepareStatement("SELECT role FROM crud GROUP BY role;"); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { list.add(rs.getString(1)); } } catch (SQLException e) { LOG.error(String.format("Problem get list roles: %s", e)); } finally { disconnect(); } return list; } }
// UpdAppServ - update app service func (db *AppServDB) UpdAppServ(ctx context.Context, cfg *chatbotbase.AppServConfig) ( *chatbotpb.AppServInfo, error) { casi, err := db.GetAppServ(ctx, cfg.Token) if err != nil { return nil, err } t, err := chatbotbase.GetAppServType(cfg.Type) if err != nil { return nil, err } asi := &chatbotpb.AppServInfo{ Token: cfg.Token, AppType: t, Username: cfg.UserName, } if casi != nil && t == casi.AppType && casi.Username == cfg.UserName { asi.Sessionid = casi.Sessionid } buf, err := proto.Marshal(asi) if err != nil { return nil, err } err = db.ankaDB.Set(ctx, AppServDBName, makeAppServKey(cfg.Token), buf) if err != nil { return nil, err } return asi, nil }
<reponame>longjiazuo/j2se-project package org.light4j.net.tcp.bio.basic; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; public class Client { // 端口 static final int PORT = 30000; public static void main(String[] args) throws Exception { Socket socket = new Socket("127.0.0.1", PORT); // 将Socket对应的输入流包装成BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); // 进行普通的IO操作 String line = br.readLine(); System.out.println("来自服务器的数据:" + line); // 关闭输入流,关闭Socket br.close(); socket.close(); } }
// BodyParam gets a variable that has been stored in the bodyparams object. func (self *Parameters) BodyParam(k string) interface{} { self.RLock() defer self.RUnlock() return self.bodyParams[k] }
<filename>chapter/_02two/IntQuest7.java /* MIT License Copyright (c) 2019 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Intersection: Given _02two (singly) linked lists, determine if the _02two lists intersect. Return the intersecting node. * Note that the intersection is defined based on reference, not value. That is, if the kth * node of the first linked list is the exact same node (by reference) as the jth node of the second * linked list, then they are intersecting. * Hints: #20, #45, #55, #65, #76, #93, #111, #120, #129 * - You can do this in 0 (A+B) time and 0 (1) additional space. That is, you do not need a * hash table (although you could do it with _01one). * - Examples will help you. Draw a picture of intersecting linked lists and _02two equivalent * linked lists (by value) that do not intersect. * - Focus first on just identifying if there's an intersection * - Observe that _02two intersecting linked lists will always have the same last node. Once they * intersect, all the nodes after that will be equal. * - You can determine if _02two linked lists intersect by traversing to the end of each and * comparing their tails. * - Now, you need to find where the linked lists intersect. Suppose the linked lists were the * same length. How could you do this? */ package chapter._02two; import static chapter._02two.MyLinkedList.overlapping; public class IntQuest7 { public static void main(String[] args) { MyLinkedList<Integer> list1 = new MyLinkedList<>(); MyLinkedList<Integer> list2 = new MyLinkedList<>(); list1.addNode(4); list2.addNode(7); list2.addNode(19); Node<Integer> node = new Node<>(352); list1.addNodeByReference(node); list2.addNodeByReference(node); Node<Integer> node1 = new Node<>(354); list1.addNodeByReference(node1); list2.addNodeByReference(node1); list1.printList(); list2.printList(); System.out.println(overlapping(list1, list2)); // those lists are overlapping; MyLinkedList<Integer> list3 = new MyLinkedList<>(); list3.addNode(3); list3.addNode(4); System.out.println(overlapping(list1, list3)); // those lists are not overlapping; } }
Couriers of asthma: antigenic proteins in natural rubber latex. Natural rubber latex (NRL) is a milky, white liquid containing the polymer cis-1,4-polyisoprene, derived from the laticifer cells of the rubber tree, Hevea brasiliensis. Reports of allergic reactions to NRL, ranging in severity from skin rashes to anaphylaxis and death, have been increasing. High rates of latex allergy are seen in children with spina bifida. Healthcare workers, especially those who frequently use powdered latex medical gloves, can develop NRL allergy and asthma, often resulting in considerable disability. Atopy and, possibly, pre-existing dermatitis predispose to sensitization and allergic symptoms. NRL protein antigens are found in many NRL products and also have been shown to bind to cornstarch glove-donning powders. Of the approximately 240 polypeptides in NRL, nearly 60 are antigenic, and nine have been identified and registered (Hev b 1&ndash9). Many natural latex antigens share epitopes with structural proteins and enzymes from other plant species. Current knowledge indicates that proposed reductions in total glove protein and limitations on the use of powder on NRL gloves are likely to result in a decline in the prevalence and severity of NRL allergies among healthcare workers.
<filename>src/main/java/io/github/oliviercailloux/j_voting/profiles/gui/MainGUI.java package io.github.oliviercailloux.j_voting.profiles.gui; import java.io.IOException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Objects; /** * Home GUI allowing to load a profile and then select how to display it */ public class MainGUI { private static final Logger LOGGER = LoggerFactory.getLogger(MainGUI.class.getName()); protected final static Display display = Display.getDefault(); protected final static Shell mainShell = new Shell(display, SWT.CLOSE | SWT.RESIZE); protected GridData gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); protected final static Label label = new Label(mainShell, SWT.CENTER); protected final static Button selectFileToReadButton = new Button(mainShell, SWT.PUSH); protected static Button socColumnsGUIButton = new Button(mainShell, SWT.PUSH); protected static Button soicolumnsGUIButton = new Button(mainShell, SWT.PUSH); protected static Button socRowsGUIButton = new Button(mainShell, SWT.PUSH); protected static Button soiRowsGUIButton = new Button(mainShell, SWT.PUSH); protected static Button socWrappedColumnsGUIButton = new Button(mainShell, SWT.PUSH); protected static Button soiWrappedColumnsGUIButton = new Button(mainShell, SWT.PUSH); protected static String fileToRead = ""; protected static String fileExtension = ""; protected static String[] profileToRead = new String[1]; public void displayGUI() { LOGGER.debug("displayGUI :"); GridLayout gridLayout = new GridLayout(); gridLayout.marginTop = 10; gridLayout.verticalSpacing = 10; gridLayout.numColumns = 3; mainShell.setLayout(gridLayout); // file chooser FileDialog fileChooser = new FileDialog(mainShell, SWT.OPEN); fileChooser.setFilterExtensions(new String[] { "*.soc", "*.soi" }); Font boldFont = new Font(label.getDisplay(), new FontData("Arial", 20, SWT.BOLD)); label.setFont(boldFont); label.setText("Profile Editing"); selectFileToReadButton.setText("Select a profile"); gridData.horizontalSpan = 3; gridData.horizontalAlignment = SWT.FILL; label.setLayoutData(gridData); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 3; selectFileToReadButton.setLayoutData(gridData); createSOCButtons(); createSOIButtons(); if (Objects.equal(fileToRead, "")) { mainShell.setText("Profile editing - No profile loaded"); // remove SOI buttons soicolumnsGUIButton.setVisible(false); soiRowsGUIButton.setVisible(false); soiWrappedColumnsGUIButton.setVisible(false); GridData data = (GridData) soicolumnsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) soiRowsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) soiWrappedColumnsGUIButton.getLayoutData(); data.exclude = true; // remove SOC buttons socColumnsGUIButton.setVisible(false); socRowsGUIButton.setVisible(false); socWrappedColumnsGUIButton.setVisible(false); data = (GridData) socColumnsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) socRowsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) socWrappedColumnsGUIButton.getLayoutData(); data.exclude = true; } else { mainShell.setText("Profile editing - " + fileToRead); } // pack elements to reduce size to the smallest mainShell.pack(); // center shell in your primary monitor Rectangle screenSize = display.getPrimaryMonitor().getBounds(); mainShell.setLocation((screenSize.width - mainShell.getBounds().width) / 2, (screenSize.height - mainShell.getBounds().height) / 2); // open the shell mainShell.open(); selectFileToReadButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileToRead = fileChooser.open(); // shell text if (fileToRead == null || fileToRead.isEmpty()) { mainShell.setText("Profile editing - No profile loaded"); label.setText("Profile editing"); } else { fileExtension = fileToRead.substring(fileToRead.length() - 3); if (fileExtension.equals("soc")) { label.setText("SOC Profile editing"); displaySOCButtons(); mainShell.pack(); mainShell.layout(); } else {// if extension is soi label.setText("SOI Profile editing"); displaySOIButtons(); mainShell.pack(); mainShell.layout(); } mainShell.setText("Profile editing - " + fileToRead); profileToRead[0] = fileToRead; } } }); while (!mainShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } /** * Instantiates and set characteristics of SOC buttons with their specific * behaviors. */ public void createSOCButtons() { socColumnsGUIButton.setText("Columns : Voters"); socRowsGUIButton.setText("Rows : Voters"); socWrappedColumnsGUIButton.setText("Columns : Voters wrapped"); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; socColumnsGUIButton.setLayoutData(gridData); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; socRowsGUIButton.setLayoutData(gridData); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; socWrappedColumnsGUIButton.setLayoutData(gridData); // listeners socColumnsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOCColumnsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening Columns GUI : {}", ioe); } } } }); socRowsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOCRowsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening Rows GUI : {}", ioe); } } } }); socWrappedColumnsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOCWrappedColumnsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening wrapped GUI : {}", ioe); } } } }); } /** * Instantiates and set characteristics of SOI buttons with their specific * behaviors. */ public void createSOIButtons() { soicolumnsGUIButton.setText("Columns : Voters"); soiRowsGUIButton.setText("Rows : Voters"); soiWrappedColumnsGUIButton.setText("Columns : Voters wrapped"); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; soicolumnsGUIButton.setLayoutData(gridData); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; soiRowsGUIButton.setLayoutData(gridData); gridData = new GridData(GridData.CENTER, GridData.CENTER, true, false); gridData.horizontalSpan = 1; soiWrappedColumnsGUIButton.setLayoutData(gridData); // listeners soicolumnsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOIColumnsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening Columns SOI GUI : {}", ioe); } } } }); soiRowsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOIRowsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening Rows SOI GUI : {}", ioe); } } } }); soiWrappedColumnsGUIButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (fileToRead == null || fileToRead.isEmpty()) { displayMessageNoFileLoaded(); } else { try { new SOIWrappedColumnsGUI().displayProfileWindow(profileToRead); } catch (IOException ioe) { LOGGER.debug("IOException when opening Wrapped Columns SOI GUI : {}", ioe); } } } }); } /** * Displays SOC buttons and hides SOI ones */ public void displaySOCButtons() { LOGGER.debug("displaySOCButtons : "); // remove SOI buttons soicolumnsGUIButton.setVisible(false); soiRowsGUIButton.setVisible(false); soiWrappedColumnsGUIButton.setVisible(false); GridData data = (GridData) soicolumnsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) soiRowsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) soiWrappedColumnsGUIButton.getLayoutData(); data.exclude = true; // add SOC buttons socColumnsGUIButton.setVisible(true); socRowsGUIButton.setVisible(true); socWrappedColumnsGUIButton.setVisible(true); data = (GridData) socColumnsGUIButton.getLayoutData(); data.exclude = false; data = (GridData) socRowsGUIButton.getLayoutData(); data.exclude = false; data = (GridData) socWrappedColumnsGUIButton.getLayoutData(); data.exclude = false; } /** * Displays SOI buttons and hides SOC ones */ public void displaySOIButtons() { LOGGER.debug("displaySOIButtons : "); // remove SOC buttons socColumnsGUIButton.setVisible(false); socRowsGUIButton.setVisible(false); socWrappedColumnsGUIButton.setVisible(false); GridData data = (GridData) socColumnsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) socRowsGUIButton.getLayoutData(); data.exclude = true; data = (GridData) socWrappedColumnsGUIButton.getLayoutData(); data.exclude = true; // add SOI buttons soicolumnsGUIButton.setVisible(true); soiRowsGUIButton.setVisible(true); soiWrappedColumnsGUIButton.setVisible(true); data = (GridData) soicolumnsGUIButton.getLayoutData(); data.exclude = false; data = (GridData) soiRowsGUIButton.getLayoutData(); data.exclude = false; data = (GridData) soiWrappedColumnsGUIButton.getLayoutData(); data.exclude = false; } public void displayMessageNoFileLoaded() { LOGGER.debug("displayMessageNoFileLoaded : "); MessageBox messageBox = new MessageBox(mainShell, SWT.OK); messageBox.setText("Warning"); messageBox.setMessage("No profile loaded !"); messageBox.open(); } public static void main(String[] args) { new MainGUI().displayGUI(); } }
Thursday, 19 July 2018 [link to this day] • Alterbeast, Inferi, Reaping Asmodela, Condemn the Infected, and Emerge a Tyrant - Sidebar Tavern (Baltimore) • Buddy Guy and Quinn Sullivan - State Theatre • Chuck Prophet & the Mission Express - the Hamilton • the Faceless, Lorna Shore, Dyscarnate, Dead Eyes Always Dreaming, and Artifacts - Baltimore SoundStage • Gounod: Roméo et Juliette - Wolf Trap (the Barns) • the James Hunter Six - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Japandroids - Rock & Roll Hotel - sold out • Kid Claws, Dentist, and Pagan Reagan - Black Cat (Backstage) • Mourn, Chastity, and Venn - DC9 • Nitty Gritty Dirt Band - Birchmere • Poncho Sanchez - Blues Alley (Two shows) • Sasquatch, Asthma Castle, Thought Eater, and Haze Mage - Ottobar (Baltimore) • Virginia Man and SondorBlue - Jammin' Java • Vocal Colors: Wolf Trap Opera at the Phillips Collection - the Phillips Collection, Music Room [1600 21st St NW] • Wait Wait . . . Don't Tell Me! - Wolf Trap (Filene Center) • When Particles Collide, Elizabeth II, and the Meer - Slash Run [201 Upshur St NW, WDC] • the World Peace Ensemble, Kyle Guffey, and American Darling Valve - Velvet Lounge Friday, 20 July 2018 [link to this day] • Ahi - DC9 • Al Stewart - AMP • Arcade Fire and Hamilton Leithauser - Jiffy Lube Live (Everything Now Continued) • the Bacon Brothes and Janie Barnett - Birchmere • the Brencore Allstar Band: A Tribute to the Music of Motown - Union Stage [740 Water Street SW, Washington, DC 20024] • Dave Chappell - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Drugs of Faith, Foehammer (record release), Malevich, and the Way - the Pinch [3548 14th St NW, WDC] • Erasure - Warner Theatre (World Be Gone Tour) - sold out • Greta Van Fleet - 9:30 Club - sold out • Janelle Monáe and St. Beauty - The Anthem [901 Wharf Street SW, Washington, DC] - sold out • Japandroids - Rock & Roll Hotel - sold out • Nicki Bluhm - the Hamilton • the Nighthawks and Mark Wenner's Blues Warriors - Jammin' Java • Paula Cole - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Poncho Sanchez - Blues Alley (Two shows) • the Prince Experience (tribute) - Baltimore SoundStage • Queen Latifah and Common - Wolf Trap (Filene Center) • Sathanas, Percussor, Descendency, Bound By The Grave, Uncut, MoonFire, and Murder Method - El Laberinto Bar & Grill [2423 Hickerson Drive, Wheaton, MD] • Tory Lanez - Fillmore Silver Spring (Memories Don't Die Tour) • Two Inch Astronaut (Farewell Show), Den-Mate, and Julian - Black Cat (Backstage) Saturday, 21 July 2018 [link to this day] • Animal Collective (performing Sung Tongs) - Lincoln Theatre • the Bacon Brothes and Janie Barnett - Birchmere • Chris Webby, Da Kid Emm, and Billy Lyve - Baltimore SoundStage • Crowded Streets (Dave Matthews tribute) - Jammin' Java (Late show - 10 PM) • Deafheaven, Drab Majesty, and Uniform - 9:30 Club • Demolition Hammer, Noisem, Genocide Pact, and Neolithic - Ottobar (Baltimore) • Dispatch, Nahko & Medicine for the People, and Raye Zaragoza - Merriweather Post Pavilion • Erasure - Warner Theatre (World Be Gone Tour) • Ezra Mae & the Gypsy Moon - Rock & Roll Hotel • Gounod: Roméo et Juliette - Wolf Trap (the Barns) • Greta Van Fleet and Cloves - The Anthem [901 Wharf Street SW, Washington, DC] - sold out • the Hot Lanes Big Band presents the Great American Songbook - Jammin' Java (1 PM Afternoon Show) • James Wolf, Raven Bauer Durham, and Stephen Carroll Palke - RhizomeDC [6950 Maple St NW, WDC] • Jaws in Concert: National Symphony Orchestra (Emil de Cou, conductor) - Wolf Trap (Filene Center) • Masque Off: Cosplay Night - Fillmore Silver Spring • the Newly Dead Game: A Murder Mystery - Jammin' Java (7 PM Early Show Presented by Dye Laughing Productions) • On the Border (Eagles tribute) - State Theatre • the Out of Water Experience (album release party), Goodbye July, Normandy Wood, the Revived, and Jimmy Warner - Rams Head Live! (Baltimore) • Panic! at the Disco - Baltimore Arena (Royal Farms Arena) (Pray for the Wicked Tour) • Poncho Sanchez - Blues Alley (Two shows) • Poster Children and Teen Mortgage - DC9 • Ray Wylie Hubbard - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Rob Zombie, Marilyn Manson, and Deadly Apples - Jiffy Lube Live (Twins of Evil Tour) Sunday, 22 July 2018 [link to this day] • Aria Jukebox - Wolf Trap (the Barns - 3 PM) • the Bacon Brothes and Janie Barnett - Birchmere • Blackberry Smoke and Magpie Salute - Fillmore Silver Spring • Casino Royale in Concert - National Symphony Orchestra (Emil de Cou, conductor) - Wolf Trap (Filene Center) • DC101 Kerfuffle: Fall Out Boy, Rise Against, Awolnation, AJR, Robert DeLong, Mt. Joy, L.I.F.T. - Merriweather Post Pavilion • Louie Anderson and Danny Rouhier - State Theatre • Poncho Sanchez - Blues Alley (Two shows) • Romane & Lettuce - Black Cat (Backstage) • Sleep and Dylan Carlson - 9:30 Club - sold out • Sweet Yonder - Jammin' Java (1:30 PM Afternoon Show - Shepherd's Center of Oakton Vienna Benefit Concert) • Weeer, Pixies, and Sleigh Bells - Jiffy Lube Live • Zac Clark (of Andrew McMahon & the Wilderness), Bob Oxblood, and Mykey - Jammin' Java (7:30 PM Evening Show) Monday, 23 July 2018 [link to this day] • #YES50: Celebrating 50 Years of Yes - Warner Theatre • Bongripper, Pyrolatrous, and Caustic Casanova - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] • D.O.A., the Turbo AC's, and Dot Dash - Black Cat (Backstage) • Del Florida, Static Atlas, the Touch, and Bottled Up - Velvet Lounge • Sb the Moor, Melanin Free, Giddeon Gallows, and Infinity Knives + Randi - Wind-Up Space (Baltimore) • Signor Benedick the Moor, Melanin Free, Giddeon Gallows, and Infinity Knives + Randi - Wind-Up Space (Baltimore) • Sleep (performing Holy Mountain) and Dylan Carlson - 9:30 Club • Small Dad, Cave Baby, and the NRIs - Fort Reno Tuesday, 24 July 2018 [link to this day] • Charlie Parr - Black Cat (Backstage) • Courtney Barnett, Julien Baker, and Vagabon - The Anthem [901 Wharf Street SW, Washington, DC] • Evanescence and Lindsey Stirling - Jiffy Lube Live • Heresiarch, Antichrist Siege Machine, and Erlkonig - Metro Gallery (Baltimore) MOVED TO ATLAS BREW WORKS • Heresiarch, Antichrist Siege Machine, and Erlkonig - the Pinch [3548 14th St NW, WDC] • Jason Isbell & the 400 Unit and Hiss Golden Messsenger - Wolf Trap (Filene Center) • Jeff Antoniuk & John D'Earth Quintet: MD Summer Jazz Opening Night - Blues Alley (Two shows) • Sb the Moor, Ardamus, and Airospace - Electric Maid [268 Carroll St NW, WDC] • Summer Salt, Hot Flash Heat Wave, and the Symposium - DC9 Wednesday, 25 July 2018 [link to this day] • Blackmore's Night and the Wizard's Consort - Lincoln Theatre • Charlie Puth and Hailee Steinfeld - Wolf Trap (Filene Center - the Voicenotes Tour) • Chicago and REO Speedwagon - Jiffy Lube Live • CKY, Palm Trees in Moscow, and Matt Talley - Baltimore SoundStage • the Dave Matthews Tribute Band - Howard Theatre • Echo & the Bunnymen and Violent Femmes - The Anthem [901 Wharf Street SW, Washington, DC] • Fantastic Negrito - 6th & I • Karen Linette - Blues Alley (Two shows) • Nikki Lane and Blank Range - Rock & Roll Hotel • the Quebe Sisters - City Winery DC [1350 Okie St NE, Washington, DC 20002] • the Rad Trads - Strathmore (Live from the Lawn) • Virginia Music Adventures Summer Institute Ensemble - Jammin' Java • Wilder Maker and Odetta Hartman - Black Cat (Backstage) • the xx - 9:30 Club - sold out Thursday, 26 July 2018 [link to this day] • Bazzi - Fillmore Silver Spring (Moved from Union Stage - the Cosmic Tour) - sold out • Bazzi - Union Stage [740 Water Street SW, Washington, DC 20024] - sold out Moved to the Fillmore Silver Spring • Cowboy Junkies - Birchmere • Eagles and James Taylor & His All-Star Band - Nationals Park [1500 South Capitol St SE, WDC] • Eric Roberson - Baltimore SoundStage • Jazz Funk Soul: Jeff Lorber, Everette Harp, Paul Jackson Jr. - Blues Alley (Two shows) • Larry Keel Experience - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Little Bird - Metro Gallery (Baltimore) • Liz Russo & Andre Kim - AMP (AMP Comedy Night) • Olivia Chaney - Jammin' Java • the Quebe Sisters Band - Rams Head On Stage (Annapolis) • Shannon & the Clams - U St Music Hall (Early show - 7 PM) • Slightly Stoopid, Stick Figure, and Pepper - Pier Six Pavilion (Baltimore) (Schools Out for Summer 2018 Tour) • Sylvan Esso and Moses Sumney - The Anthem [901 Wharf Street SW, Washington, DC] • Taciturn, Birds For Eyes, Alive/Alone, Slow Fix, and dc charges - Velvet Lounge • the xx - 9:30 Club - sold out Friday, 27 July 2018 [link to this day] • Back to the 90s: Brains of J (Pearl Jam tribute), Getchoo (Weezer tribute), First Gentleman (Preseidents of the USA tribute), and Selling the Drama (Live tribute) - Jammin' Java • Bal Boheme, Caravela, Wet Leather, and Jon Harmon - Velvet Lounge • Bernstein at 100: A Celebration: National Symphony Orchestra (Michael Barrett, conductor) - Wolf Trap (Filene Center) • the Dirty Grass Players perform Pickin' on the Dark Side of the Peach and Two Ton Twig - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Eric Roberson - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Erin Rae - DC9 • Frass Green - Rock & Roll Hotel • Glue Factory, Positive No, and Warm Sun - Comet Ping Pong • Incendio - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Jay-Z and Beyoncé - FedEx Field [1600 FedEx Way, Landover, MD 20785] (OTR II Tour) • Jazz Funk Soul: Jeff Lorber, Everette Harp, Paul Jackson Jr. - Blues Alley (Two shows) • Johnny Gill - Birchmere • Kim Walker-Smith - Fillmore Silver Spring (On My Side Tour) • Mark Thomas - Baltimore SoundStage • Roger Clyne & the Peacemakers and Andrew Leahey & the Homestead - State Theatre • Silvestre Dangond - The Anthem [901 Wharf Street SW, Washington, DC] • Smashing Pumpkins - Baltimore Arena (Royal Farms Arena) (Shiny And Oh So Bright Tour) • Sun Dogs (Rush tribute) - AMP • Temple of Void - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] • Witch Mountain, Brimstone Coven, Queen Wolf, and Cavern - Metro Gallery (Baltimore) • the xx - 9:30 Club - sold out Saturday, 28 July 2018 [link to this day] • American Television, Virginia Creep, the Osyx, and the Combs - DC9 • Arctic Monkeys and Mini Mansions - The Anthem [901 Wharf Street SW, Washington, DC] - sold out • the Best of Wagner's Ring: National Symphony Orchestra (Patrick Summers, conductor) - Wolf Trap (Filene Center) • Bit Gen Gamer Fest XII: Super Madness, Cheap Dinosaurs, Lame Genie, Rare Candy (video game tribute), the X-Hunters, Master Sword, Cowabunga Pizza Time, Steel Samurai, Random Battles, Flabbercasters, Nelward, Wreck the System, Animal Style, Pocky Bros, Garbage Masher, DJ Super Sonic, Kenzie Black - Ottobar (Baltimore) (3 PM Show) • Claire Lynch Band & Steppin' At the Junction - AMP • David Byrne and Benjamin Clementine - Merriweather Post Pavilion (American Utiopia Tour) • Dr. Badlove & the Remedies, Cosmic Romp, and Dope Francis - Rock & Roll Hotel • Eric Roberson - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Jay-Z and Beyoncé - FedEx Field [1600 FedEx Way, Landover, MD 20785] (OTR II Tour) • Jazz Funk Soul: Jeff Lorber, Everette Harp, Paul Jackson Jr. - Blues Alley (Two shows) • Johnny Gill - Birchmere • Kesha and Macklemore - Jiffy Lube Live • the Legwarmers (80s tribute) - State Theatre • Made in Cameroon Music Festival - Fillmore Silver Spring • Pissed Jeans - Metro Gallery (Baltimore) • That 70s Party with Champion Sound (live) and vinyl DJs Gudi and John Eamon - 9:30 Club • Vicious Circle, Percussor, Descendency, and Visceral Violation - TheDepot Baltimore [1728 N Charles St, Baltimore, MD] • A Watkins Glen Reunion featuring the Allman Others & On the Bus - Jammin' Java (Summer Jam XLV) • Woven In, Matt Pless, Valore, and Slow Groan - Joe Squared [33 West North Ave, Baltimore, MD] Sunday, 29 July 2018 [link to this day] • Arctic Monkeys and Mini Mansions - The Anthem [901 Wharf Street SW, Washington, DC] • Glassjaw & Quicksand with Primitive Weapons - Rams Head Live! (Baltimore) • Jazz Funk Soul: Jeff Lorber, Everette Harp, Paul Jackson Jr. - Blues Alley (Two shows) • Lightmare, the Prabir Trio, and Wooden/Apple/Heart - DC9 • Medicine Man, Magic Item, and Adjective Animal - Joe Squared [33 West North Ave, Baltimore, MD] • Mother's Finest - Birchmere • No Small Children and Caz Gardiner - Jammin' Java • Pastel, Tortuga, Le'Asha Julius, and Jenna Camille - Velvet Lounge • Rico Nasty and Maliibu Mitch - Baltimore SoundStage (the Nasty Tour) • Spirit Adrift - Metro Gallery (Baltimore) • Tinariwen - Warner Theatre • Vans Warped Tour: 3OH!3, The Amity Affliction, As It Is, Assuming We Survive, August Burns Red, Broadside, Capstan, Chase Atlantic, Chelsea Grin, Crown The Empire, Dayseeker, Deez Nuts, Doll Skin, Don Broco, Every Time I Die, Farewell Winters, Four Year Strong, Grayscale, Ice Nine Kills, In Hearts Wake, The Interrupters, Issues, Knuckle Puck, Kublai Khan, Less Than Jake, Lighterburns, The Maine, Makeout, Mayday Parade, Motionless in White, Movements, Mychildren Mybride, Nekrogoblikon, Palaye Royale, Real Friends, Reel Big Fish, Sharptooth, Simple Plan, Sleep On It, State Champs, Story Untold, This Wild Life, Tonight Alive, Trash Boat, Twiztid, Unearth, Wage War, Waterparks, We the Kings, With Confidence - Merriweather Post Pavilion • Yanni: Live at the Acropolis 25th Anniversary Tour - Wolf Trap (Filene Center) Monday, 30 July 2018 [link to this day] • Alex Cameron - Metro Gallery (Baltimore) • Andy Timmons and Travis Larson Band - Jammin' Java • Beres Hammond - Rams Head Live! (Baltimore) • Lamb of God, Anthrax, Testament, and Napalm Death - Fillmore Silver Spring • the Ominous Circle, Scorched, and Neolithic - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] • Rex Orange County - U St Music Hall (Early show - 7 PM) - sold out • Wolves of the Dry Ravine, the Effects, and Koshari - Fort Reno Tuesday, 31 July 2018 [link to this day] • Bob Boguslaw: CD Release Party - Blues Alley (Two shows) • Boy Pablo - Union Stage [740 Water Street SW, Washington, DC 20024] • Chris Robinson Brotherhood - Rams Head Live! (Baltimore) • Peter & Jeremy: Peter Asher (of Peter & Gordon) and Jeremy Clyde (of Chad & Jeremy) - Jammin' Java • the Spill Canvas, Punchline, Selfish Things, and Too Soon Jokes - Baltimore SoundStage • Us the Duo and Justin Nozuka - 6th & I (The Together Tour - Summer 2018) • the Vaccines - Rock & Roll Hotel - sold out • Zeke, Foghound, the Phantom Killers, and Salt Traderr - Metro Gallery (Baltimore) Wednesday, 1 August 2018 [link to this day] • Avenged Sevenfold, Prophets of Rage, and Three Days Grace - Jiffy Lube Live (End of the World Tour) • the Chuck Brown Band - Strathmore (Live from the Lawn) • Former Best Friends Songwriter Circle: Chris Cassaday, Justin Trawick, Louisa Hall, Eli Lev - Jammin' Java • Leron Young - Blues Alley (Two shows) • Rico Nasty - Fillmore Silver Spring • the Sheepdogs and Brent Cowles - Rock & Roll Hotel • Telekinetic Yeti, Hyborian, and Faith in Jane - Metro Gallery (Baltimore) • Zach and Kristin Will Make You Slumber Party - DC9 Thursday, 2 August 2018 [link to this day] • Amanda Shires and Sean Rowe - Birchmere • Black milk - Rock & Roll Hotel • Castlecomer - DC9 • Father John Misty and Bully - The Anthem [901 Wharf Street SW, Washington, DC] • Freddy Cole Quartet - Blues Alley (Two shows) • George Clinton & Parliament Funkadelic - 9:30 Club • Lady Antebellum, Darius Rucker, and Russell Dickerson - Merriweather Post Pavilion • Lil Ugly Mane, Nickelus F, Backslider, End It, Butch Dawson & Black Zheep DZ, and DJ Pancakes - Baltimore SoundStage • Preston Reed - Jammin' Java • Sound Proof Genie and Branch Manager - Fort Reno • Wino (Scott Weinrich), Xasthur, and Dee Calhoun - Metro Gallery (Baltimore) Friday, 3 August 2018 [link to this day] • Analepsy, Korpse, Cognitive, Slamentation, Wormhole, and Cancer Priest - Sidebar Tavern (Baltimore) CANCELLED due to visa issues • Andrea Gibson and Mary Lambert - 9:30 Club • Attila, Suicide Silence, Volumes, Rings of Saturn, Spite, and Cross Your Fingers - Baltimore SoundStage (Rage Fest) • Colors Presents: R&B Only with Dauché, DJ Printz, and Jabari - Rams Head Live! (Baltimore) • DCLA Silent Headphone Party: East Vs West Vs Dirty South - Fillmore Silver Spring • the Family Crest and Wylder - DC9 • Freddy Cole Quartet - Blues Alley (Two shows) • Hey Frase! A Live Podcast Taping with Sarah Fraser - AMP • Parthenon Huxley & Friends - Jammin' Java • Party Like It's, the Osyx, the Creachies, and the Let Go - Rock & Roll Hotel • Son Del Caribe - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Tiny Cat - Dark Music Festival: Hante, Kontravoid, Technophobia, Remote/Control, Radiator Greys - Black Cat (Backstage - a benefit for the Greater DC Diaper Bank) • Trombone Shorty & Orleans Avenue with Galactic, Preservation Hall Jazz Band, and New Breed Brass Band, plus special guests - Pier Six Pavilion (Baltimore) (Voodoo Threauxdown) • Verdi's Rigoletto: Wolf Trap Opera and National Symphony Orchestra (Grant Gershon, conductor) - Wolf Trap (Filene Center) Saturday, 4 August 2018 [link to this day] • 1964: the Tribute - Birchmere • Brain Stew (Green Day tribute) and Getchoo (Weezer tribute) - Metro Gallery (Baltimore) (Back to the 90s Night) • Dreadnought, Byrgan, and LORD - TheDepot Baltimore [1728 N Charles St, Baltimore, MD] • Flashand 70s Showcase - Union Stage [740 Water Street SW, Washington, DC 20024] • Freddy Cole Quartet - Blues Alley (Two shows) • Hanson: String Theory with National Symphony Orchestra (Emil de Cou, conductor) - Wolf Trap (Filene Center) • Hayes Carll (solo) - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Jimmy Buffett and the Coral Reefer Band - Jiffy Lube Live • Oneida, Quattracenta, Scroll Downers, and Nerftoss - Ottobar (Baltimore) • School of Rock All-Stars - DC9 (Early show - 5 pM) • A Sound of Thunder, Offensive, Dark Entity, Vilified, Screaming in Silence, Ace Holiday, and OnceDrowned - Rams Head Live! (Baltimore) • Strangelove (Depeche Mode tribute) - Fillmore Silver Spring • Stu Larsen & Natsuki Kurai II with Tim Hart - Jammin' Java • Summer Spirit Festival - Part One: Erykah Badu, Nas, Method Man & Redman, Rapsody - Merriweather Post Pavilion • Tiny Cat - Dark Music Festival: Crash Course in Science, Sally Dige, Void Vision, Twins, Funeral Lace - Black Cat (Backstage - a benefit for the Greater DC Diaper Bank) • TT the Artist, Kotic Couture, Bond St. District, Jay Royale, and Rovo Monty - Baltimore SoundStage (the Shopping Mall Ball) Sunday, 5 August 2018 [link to this day] • Bitch Sesh Live - 9:30 Club (Two shows - 3 PM & 7 PM) - sold out • Bryan Adams - Wolf Trap (Filene Center) • Bush, Stone Temple Pilots, and the Cult - Jiffy Lube Live (Revolution 3 Tour) • Freddy Cole Quartet - Blues Alley (Two shows) • Jake Shimabukuro - Birchmere • Rob Stokes, Kyle Duke & the Brown Bag Boys, and Nick Cianci - DC9 • Steve Everett (album release show) and the Currys - Jammin' Java • Summer Spirit Festival - Part Two: the Roots, Anderson .Paak & the Free Nationals, Lizzo, Raheem DeVaughn, Masego, and more - Merriweather Post Pavilion (1 PM Doors) Monday, 6 August 2018 [link to this day] • the Bachelor Boys - Jammin' Java • De Lux - Union Stage [740 Water Street SW, Washington, DC 20024] (More Disco Songs About Love Tour) • Many Rooms and Angelo De Augustine - DC9 • the Mauls and Numbers Station - Galaxy Hut Tuesday, 7 August 2018 [link to this day] • Angélique Kidjo's Remain In Light and Femi Kuti & the Positive Force - Wolf Trap (Filene Center) • the Essex Green - Black Cat (Backstage) • Joan of Arc - DC9 • Kenny Wesley - Blues Alley (Two shows) • Sequel - Jammin' Java Wednesday, 8 August 2018 [link to this day] • Alex Lahey - Rock & Roll Hotel • Counting Crows and Live - Jiffy Lube Live (25 Years and Counting) • Disney: Beauty & the Beast in concert film with live orchestra and sinters - Wolf Trap (Filene Center) • Erin & the Wildfire - Strathmore (Live from the Lawn) • exits, Shiffley, and Zach Benson - Jammin' Java • Kraus, Nolife, Pinkwench, and Mess - Metro Gallery (Baltimore) • Matt Schofield - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Victor Provost - Blues Alley (Two shows) • Wimps and Bacchae - Black Cat (Backstage) Thursday, 9 August 2018 [link to this day] • Andrew Combs - DC9 • the Breeders and Post Pink - Rams Head Live! (Baltimore) • Disney: Beauty & the Beast in concert film with live orchestra and sinters - Wolf Trap (Filene Center) • Jason Weems & Melissa Douty - AMP (AMP Comedy Night) • Marcus Johnson: Urban Jam Band - Blues Alley (Two shows) • Ruse de Guerre, the Firnats, Desperry, and Lilnorinori - Rock & Roll Hotel • the Shondes, Governess, and Hemlines - Black Cat (Backstage) • Toad the Wet Sprocket and Megan Slankard - Birchmere • Tony Lucca and Jesse Ruben - Jammin' Java • Within the Ruins, Phinehas, Great American Ghost, Dead Atlantic, and Fire in Elysium - Baltimore SoundStage • Wiz Khalifa, Rae Sremmurd, Lil Skies, and O.T. Genasis - Jiffy Lube Live Friday, 10 August 2018 [link to this day] • Andrea Brachfeld - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Campdogzz - DC9 • Daddy Issues - Wind-Up Space (Baltimore) • Fuzzqueen, Fiona Silver, Loi Loi, and Higher Numbers - Rock & Roll Hotel • Jason Mraz and Brett Dennen - Merriweather Post Pavilion • Kidz Bop Live 2018 - Pier Six Pavilion (Baltimore) • Kill Lincoln (Good Riddance to Good Advice vinyl release show), Joystick, and Boardroom Heroes - Black Cat (Backstage) • Lyle Lovett & His Large Band - Wolf Trap (Filene Center) • Marcus Johnson: Urban Jam Band - Blues Alley (Two shows) • the Reagan Years (80s tribute) - Union Stage [740 Water Street SW, Washington, DC 20024] • Toad the Wet Sprocket and Megan Slankard - Birchmere Saturday, 11 August 2018 [link to this day] • Alice Bag, Homosuperior, and Faunas - Comet Ping Pong • Apple Core (Fab Four tribute) - AMP • the Bayside Tigers (90s Tribute) - State Theatre • Big 100 Throwback Bash featuring the Great Rock N Roll Time Machine. - Fillmore Silver Spring • Dan Navarro - Jammin' Java • Godspeed You Black Emperor and KGD - Baltimore SoundStage • Granger Smith - Power Plant Live [34 Market Place, Baltimore, MD] • Intern John: Look What You've Done - Warner Theatre • Jeremih, Teyana Taylor, and DaniLeigh - 9:30 Club • Keith Urban and Kelsea Ballerini - Jiffy Lube Live (the 2018 Country Megaticket) • Marcus Johnson: Urban Jam Band - Blues Alley (Two shows) • Mary Chapin Carpenter, Rhiannon Giddens, and Francesco Turrisi - Wolf Trap (Filene Center) • Phish - Merriweather Post Pavilion - sold out • Poseurs with DJ Mohawk Adam, DJ Michael Scruggs, Mike "Vanilla Moody" Olsen - DC9 • Shakira - Capital One Arena (formerly Verizon Center) (El Dorado World Tour - rescheduled from 1/16/18) • Thomas Anders & Modern Talking Band - DAR Constitution Hall • UkeFest Evening Concerts - Strathmore (Education Center) Sunday, 12 August 2018 [link to this day] • ABBA The Concert - Wolf Trap (Filene Center) • Horseburner, Seasick Gladiator, Mangog, and Dumb Waiter - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] • Incubus - Fillmore Silver Spring - sold out • Kevin Nealon - Rams Head On Stage (Annapolis) (Two shows - 6 PM & 9 PM) • Marcus Johnson: Urban Jam Band - Blues Alley (Two shows) • Morris Day & the Time - Birchmere • Pedro the Lion and H.C. McEntire - Black Cat (Mainstage) • Pentatonix, Echosmith, and Calum Scott - Jiffy Lube Live • Phish - Merriweather Post Pavilion • Tempest - Jammin' Java • UkeFest Evening Concerts - Strathmore (Education Center) Monday, 13 August 2018 [link to this day] • Mindi Abair & the Boneshakers - Birchmere Tuesday, 14 August 2018 [link to this day] • Alkaline Trio and Together Pangea - Rams Head Live! (Baltimore) • DK the Drummer and Sucré - DC9 • Earth, Wind, & Fire Tribute Band: Celebrating the Elements - Blues Alley (Two shows) Wednesday, 15 August 2018 [link to this day] • the Fixx - Birchmere • Gladys Knight & the O'Jays - Wolf Trap (Filene Center) • Nothing Nowhere, Wicca Phase Springs Eternal, Bogues, Lil West, and Jay Vee - Rock & Roll Hotel (Rock & Roll Hotel 12 Year Anniversary) • Pusha T, Sheck Wes, and Valee - Baltimore SoundStage (the Daytona Tour 2018) • Tim Whalen Quintet - Blues Alley (Two shows) • Trace Bundy - Jammin' Java • UkeFest Finale - Strathmore (Live from the Lawn) • Warren G - Fillmore Silver Spring Thursday, 16 August 2018 [link to this day] • Alan Jackson and Lee Ann Womack - Wolf Trap (Filene Center) • Bad Bunny - Patriot Center / EagleBank Arena (La Nueva Religion Tour) • Bat Fangs, the Love Language, and Moon Racer - Rock & Roll Hotel (Rock & Roll Hotel 12 Year Anniversary) • Casual War, Impuritan, and Joshua Palace - Velvet Lounge • Cup, Bottled Up, and Bike Thiefs - Black Cat (Backstage) • Dark Thoughts and Glue Traps - Metro Gallery (Baltimore) • Loston Harris - Blues Alley (Two shows) • Scott Kirby with guitarist Dave Edmisten - Jammin' Java Friday, 17 August 2018 [link to this day] • 3Divas - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Black Violin - Baltimore SoundStage (Classical Boom Tour) • Casual War, Stump Devils, and Phantom Scimitar - the Pinch [3548 14th St NW, WDC] • Cryfemal, Vesterian, Muert, Rites of Sedition, Infidel, Metanium, Part Death, Worthles,s and Mithlond - H Restaurant & Night Club [11300 Georgia Ave, Silver Spring, MD] • the Influence (reunion show), FuzzQueen, Dr Robinson's Fiasco, and the NRIs - Jammin' Java • the Little Mermen (Disney rock tribute) - Rams Head Live! (Baltimore) • Melba Moore - Blues Alley (Two shows) • the Messthetics, Mellow Diamond, and Puff Pieces - Rock & Roll Hotel (Rock & Roll Hotel 12 Year Anniversary) • Mura Masa - 9:30 Club • Needtobreathe, Johnnyswim, and Billy Raffoul - The Anthem [901 Wharf Street SW, Washington, DC] • Spyro Gyra - the Hamilton • Tacocat - DC9 • Trombone Shorty, Galactic, and Preservation Hall - Wolf Trap (Filene Center) Saturday, 18 August 2018 [link to this day] • the Avett Brothers and Nicole Atkins - Wolf Trap (Filene Center) • BandHouse Gigs - Fillmore Silver Spring • Billy Currington and Locash - Power Plant Live [34 Market Place, Baltimore, MD] • Cake, Ben Folds, and Tall Heights - Merriweather Post Pavilion • The Chasm, Infernal Conjuration, Acerus, and The Day Of The Beast - El Laberinto Bar & Grill [2423 Hickerson Drive, Wheaton, MD] • Crushnpain, Xoxok, and La Roche - Velvet Lounge • DC Music Rocks Festival: Black Dog Prowl, Allthebestkids, Fellowcraft, Pebble to Pearl, Kid Brother - 9:30 Club • Donavon Frankenreiter - the Hamilton • Film screening of Slave to the Grind: A Film about Grindcore featuring a Q&A with director Doug Brown, plus performances by Brainpan (DC record release show), Funeral Leech, Carcosa, Total F*cking Destruction, Tossed Aside - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] (Film at 5 PM, bands at 8 PM) • Howie Day - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Jeff Daniels with Ben Daniels Band - Birchmere • Luke Bryan, Jon Pardi, and Morgan Wallen - Jiffy Lube Live (the 2018 Country Megaticket) • Maryland Folk Metal Fest IV: Helsott, Winter Nights, Sekengard, Goblin Hovel, Urn, Wandering Oak, Ferus Din, and Ashen - Ottobar (Baltimore) • Melba Moore - Blues Alley (Two shows) • Risk! - Live Show & Podcast - Black Cat (Mainstage) • Sparta - Rock & Roll Hotel • Sparta and Sound & Shape - Rock & Roll Hotel (Rock & Roll Hotel 12 Year Anniversary) • Trial By Fire (Journey tribute) - State Theatre Sunday, 19 August 2018 [link to this day] • Country Boots Cancer featuring Jamey Johnson and Chris Hennessee - Rams Head Live! (Baltimore) • Godsmack, Shinedown, Like a Storm, and Red Sun Rising - Jiffy Lube Live • the Hunts and Fox & the Bear - Jammin' Java • Jean-Luc Ponty: The Atlantic Years - Birchmere • Melba Moore - Blues Alley (Two shows) • the Revivalists and ZZ Ward - Wolf Trap (Filene Center) Monday, 20 August 2018 [link to this day] • Jeff Beck and Ann Wilson (of Heart) - Wolf Trap (Filene Center) • John Hiatt & the Goners featuring Sonny Landreth - Birchmere Tuesday, 21 August 2018 [link to this day] • 3 Doors Down and Collective Soul - Pier Six Pavilion (Baltimore) (the Rock & Roll Express Tour) • Dopethrone, Gateway to Hell, Tombtokerr, and Total Maniac - Metro Gallery (Baltimore) • John Hiatt & the Goners featuring Sonny Landreth - Birchmere • Slocan Ramblers and Fireside Collective - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] Wednesday, 22 August 2018 [link to this day] • Chris Urquiaga: I'm Here CD release party - Blues Alley (Two shows) • High Valley - Birchmere • Kenny Chesney and Old Dominion - Merriweather Post Pavilion • Mark G. Meadows Sextet - Strathmore (Live from the Lawn) • Michael McDonald and Peter Cetera - Wolf Trap (Filene Center) • Shooter Jennings - City Winery DC [1350 Okie St NE, Washington, DC 20002] • the Voice of the Moody Blues Justin Hayward: "All the Way" in concert, featuring Mike Dawes - Birchmere Thursday, 23 August 2018 [link to this day] • the Cordovas - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Cyrus Chestnut - Blues Alley (Two shows) • Dawes, Shovels & Rope, and Joseph - Wolf Trap (Filene Center) • Fishbone - Fillmore Silver Spring • Impalers, Red Death, Asesinato - Comet Ping Pong • In the Whale - Black Cat (Backstage) • Kyle Kinane - 9:30 Club • M.O.P. + AZ with Icon Tha God, Tislam the Great, and DJ Doo Wop - Baltimore SoundStage • Tanya Tucker - Birchmere Friday, 24 August 2018 [link to this day] • Back to Black (Amy Winehouse tribute) - Fillmore Silver Spring • Bill Burr - the Theater at MGM National Harbor [7100 Oxon Hill Rd, Oxon Hill, MD] (Two shows - 7 PM & 10 PM) • Breaking Benjamin, Five Finger Death Punch, Nothing More, and Bad Wolves - Jiffy Lube Live • the Chad Dukes Rodkast presents: "CollaorHAYtion", a Theatrical Production - Jammin' Java • Cyrus Chestnut - Blues Alley (Two shows) • Frankie Valli & the Four Seasons - Wolf Trap (Filene Center) • Gringo Star, Boat Burning, and Heavy Breathing - Black Cat (Mainstage) • High Command, Left Cross, Enforced, and Execution Hour - the Pinch [3548 14th St NW, WDC] • Little River Band - Birchmere • Peter Bradley Adams - Union Stage [740 Water Street SW, Washington, DC 20024] • Speakers of the House - National Gallery of Art Sculpture Garden [DC] (Jazz in the Garden at 5 PM) • Wasted Theory, Foghound, and the Druids - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] Saturday, 25 August 2018 [link to this day] • 4th Annual Veterans Benefit Concert - Pier Six Pavilion (Baltimore) • Beach House and Papercuts - The Anthem [901 Wharf Street SW, Washington, DC] • Brad Paisley, Kane Brown, and Dan Tyminski - Jiffy Lube Live (the 2018 Country Megaticket) • Cyrus Chestnut - Blues Alley (Two shows) • Dave Mason & Steve Cropper: Rock & Soul Revue with Gretchen Rhodes - Baltimore SoundStage • Grunge-a-palooza - Rams Head Live! (Baltimore) • Kidz Bop Live 2018 - Wolf Trap (Filene Center) • Leo & Cygnus (single release), Del Florida, and Kavoossi - Metro Gallery (Baltimore) • Rodney Crowell - the Hamilton Sunday, 26 August 2018 [link to this day] • 311, the Offspring, and Gym Class Heroes - Jiffy Lube Live (Never-Ending Summer Tour) • Bollywood Boulevard: A Journey Through Hindi Cinema - Wolf Trap (Filene Center) • Cyrus Chestnut - Blues Alley (Two shows) • FLOODSTOCK featuring the Vi-Kings & the Rockits - Jammin' Java • Jacob Sartorius - Baltimore SoundStage • This Is Not a Show Live featuring Ed Schrader's Music Beat, Opin, Trading the Inside - Black Cat (Backstage) • Yngwie Malmsteen - State Theatre Tuesday, 28 August 2018 [link to this day] • New Order - The Anthem [901 Wharf Street SW, Washington, DC] • Slaughter Beach, Dog, and Thin Lips - DC9 Wednesday, 29 August 2018 [link to this day] • Bob James Trio - Birchmere • Long Neck, Fern Mayo, and Tosser - Comet Ping Pong • the Sweetback Sisters - Strathmore (Live from the Lawn) • Wolf Parade - Ottobar (Baltimore) Thursday, 30 August 2018 [link to this day] • Chris Thomas King - Blues Alley (Two shows) • G-Eazy, Lil Uzi Vert, Ty Dolla $ign, YBN Nahmir, P-Lo, and Murda Beatz - Jiffy Lube Live (the Endless Summer Tour) • Guitar Legend Dick Dale - Birchmere • Kenny G and the Tenors - Wolf Trap (Filene Center) • Lightmare, Park Snakes, North by North, and Honey - DC9 • Paty Cantu - Fillmore Silver Spring Friday, 31 August 2018 [link to this day] • Chris Thomas King - Blues Alley (Two shows) • Gavin DeGraw and Phillip Phillips - Wolf Trap (Filene Center) • Jammin Java's Mid-Atlantic Band Battle #19 - FINALS - Jammin' Java • Kim Waters - Birchmere • Niall Horan and Maren Morris - Jiffy Lube Live (Flicker World Tour) Saturday, 1 September 2018 [link to this day] • Cargo & the Heavy Lifters and the Band Changed - Jammin' Java (We Have a Dream Concert) • Chris Thomas King - Blues Alley (Two shows) • Eldritch Horror, Rotten, Bound By The Grave, Deathcrown, and Percussor - Sparta Inn [6400 N Point Rd, Sparrows Point, MD] • Garbagefest 3: Abby Huston, Cherry Ames, Baberage, the Osyx, the Greek Police, Crash Course in Science, a MARC Train Home, XK Scenario, I Against Eye - Black Cat (Backstage - a benefit for Food Not Bombs) • the Hot Lanes Big Band - Jammin' Java (1 PM Afternoon Show) • Jeffrey Osborne - Birchmere • Obeisance, Sivad, Satanik Goat Ritual, and Domnitor - El Laberinto Bar & Grill [2423 Hickerson Drive, Wheaton, MD] • Tone Rangers and the Chromatics - Union Stage [740 Water Street SW, Washington, DC 20024] (Warbling at the Wharf) • Ziggy Marley, Steel Pulse, and Tribal Seeds - Wolf Trap (Filene Center) Sunday, 2 September 2018 [link to this day] • Chris Thomas King - Blues Alley (Two shows) • Ohmme - Black Cat (Backstage) Monday, 3 September 2018 [link to this day] • Carolyn Wonderland and Shinyribs - City Winery DC [1350 Okie St NE, Washington, DC 20002] • Wax Idols and Shadow Age - Metro Gallery (Baltimore) Tuesday, 4 September 2018 [link to this day] • the Bachelor Boys - Jammin' Java • Miguel, DVSN, and Nonchalant Savant - The Anthem [901 Wharf Street SW, Washington, DC] Wednesday, 5 September 2018 [link to this day] • 5 Seconds of Summer - Wolf Trap (Filene Center - Meet You There Tour) • Mac Demarco - The Anthem [901 Wharf Street SW, Washington, DC] • Ought and Swearin' - Ottobar (Baltimore) • Steve Wilson Quartet with Raymond Angry, Willie Jones III, & Ben Williams - Blues Alley (Two shows) Thursday, 6 September 2018 [link to this day] • Alanis Morissette - Wolf Trap (Filene Center) • Dead Boys, the Ghost Wolves, and Ravagers - Metro Gallery (Baltimore) • Ex Hex - Ottobar (Baltimore) • the Jesus Lizard and All Souls - Black Cat (Mainstage) - sold out • John Craigie and Daniel Rodriguez (of Elephant Revival) - Jammin' Java • Punch Brothers and Madison Cunningham - The Anthem [901 Wharf Street SW, Washington, DC] • Yellowjackets - Blues Alley (Two shows) Friday, 7 September 2018 [link to this day] • Deafwish and Gotobeds - Joe Squared [33 West North Ave, Baltimore, MD] • Dierks Bentley, Brothers Osborne, and LANCO - Jiffy Lube Live (the 2018 Country Megaticket) • Gang Gang Dance - Metro Gallery (Baltimore) • Hatchie - DC9 • Ian Anderson Presents Jethro Tull: 50th Anniversary Tour - Wolf Trap (Filene Center) • the Manhattans featuring Gerald Alston - Birchmere • Nick Cannon Presents: Wild 'n Out Live - Baltimore Arena (Royal Farms Arena) • Nothing, Culture Abuse, and Smut - Rock & Roll Hotel • Nothing But Thieves and Demob Happy - 9:30 Club • Rorie, Hayley Fahey, and Throwing Plates - Jammin' Java • the Stranger (Billy Joel tribute) - State Theatre • Yellowjackets - Blues Alley (Two shows) Saturday, 8 September 2018 [link to this day] • 4U - A Symphonic Celebration of Prince with the Wolf Trap Orchestra - Wolf Trap (Filene Center) • All Pigs Must Die - Metro Gallery (Baltimore) • Chayanne - Patriot Center / EagleBank Arena (Desde El Alma Tour 2018) • Deray Mckesson - Baltimore SoundStage • Gabriel Kahane - Jammin' Java • Kathy Griffin - DAR Constitution Hall • the Seldom Scene & Jonathan Edwards - Birchmere • Shopping and No Age - Rock & Roll Hotel • Waxahatchee, Night Shop, and Anna St. Louis - Miracle Theatre [535 8th St SE, WDC] • Yellowjackets - Blues Alley (Two shows) Sunday, 9 September 2018 [link to this day] • Elan Trotman & Bernie Williams: Caribbean Connection - Blues Alley (Two shows) • In Real Life - Fillmore Silver Spring (Tonight Belongs To You Tour) • Jon B - Birchmere • Lucy Spraggan and Owen Danoff - Jammin' Java • OhGr, Lead Into Gold, Omniflux, and DJ Hemlock - Baltimore SoundStage • Red Fang - Rock & Roll Hotel • Saintseneca - Black Cat (Backstage) • Still Corners - DC9 Monday, 10 September 2018 [link to this day] • First Aid Kit and Julia Jacklin - The Anthem [901 Wharf Street SW, Washington, DC] • Grace & Pierce Pettis and Rebekah Todd - Jammin' Java • Killing Joke - Baltimore SoundStage (Fortieth Anniversary World Tour 2018) • Marshall Keys & the Soulful Path - Blues Alley (Two shows) Tuesday, 11 September 2018 [link to this day] • Angra, Scarlet Aura, and Offensive Offensive - Baltimore SoundStage • The Choir "Bloodshot" - Jammin' Java • Dodie - Fillmore Silver Spring - sold out • MC50 - Kick Out the Jams 50th Anniversary Tour featuring MC5s Brother Wayne Kramer, Soundgarden's Kim Thayil, Fugazi's Brendan Canty, Kings X's Dug Pinnick, and Zen Guerrilla's Marcus Durant - 9:30 Club • Preoccupations - Metro Gallery (Baltimore) • Sumac, Dalek, and Infernal Coil - Rock & Roll Hotel • Teitur - Union Stage [740 Water Street SW, Washington, DC 20024] Wednesday, 12 September 2018 [link to this day] • Film Screening: Records Collecting Dust II with Q&A - Black Cat (Backstage) • Matt Holubowski & Vera Sola - Jammin' Java • Paul McCandless with Charged Particles - Blues Alley (Two shows) • Remo Drive, Field Medic, and Prince Daddy & the Hyena - DC9 • Sarah Shook & the Disarmers - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Yuno - Rock & Roll Hotel Thursday, 13 September 2018 [link to this day] • Blessthefall, the Word Alive, Ded, Thousand Below, and A War Within - Baltimore SoundStage • Christian McBride's New Jawn - Blues Alley (Two shows - Rescheduled from 5/18-5/20) • Eleanor Friedberger - Pearl Street Warehouse [33 Pearl Street SW, Washington, DC 20024] • Mt. Joy - 8x10 [10 East Cross St, Baltimore, MD 21230] • Ski Mask the Slump God, Bandhunta Izzy, Danny Towers, and DJ Scheme - Rams Head Live! (Baltimore) • Van William - DC9 Friday, 14 September 2018 [link to this day] • Charlie Sepulveda & the Turnaround - AMP • Christian McBride's New Jawn - Blues Alley (Two shows - Rescheduled from 5/18-5/20) • John Mayall - the Hamilton • Jukebox the Ghost - Rams Head Live! (Baltimore) (Off to the Races 2018 Tour . . . Continued!) • Life of Agony and Silvertomb - Baltimore SoundStage • Los Amigos Invisibles - 9:30 Club (Late show - 10 PM) • Nils Lofgren & Friends (an acoustic evening) - Birchmere • Ozzy Osbourne and Stone Sour - Jiffy Lube Live (No More Tours 2) • Paul Simon - Capital One Arena (formerly Verizon Center) (Homeward Bound - Farewell Tour) Saturday, 15 September 2018 [link to this day] • Alina Baraz - 9:30 Club (Late show - 10 PM) • Celtic Thunder - Warner Theatre • Chamberlain - DC9 • Chemlab with C-Tec and Hellbent - State Theatre • Christian McBride's New Jawn - Blues Alley (Two shows - Rescheduled from 5/18-5/20) • Funny. Shlegl. Rouhier. Dukes - Jammin' Java • Kevin Hart - Capital One Arena (formerly Verizon Center) (Irresponsible Tour) • Kix and Ever Rise - Rams Head Live! (Baltimore) • Nils Lofgren & Friends (an acoustic evening) - Birchmere • Propagandhi and Iron Chic - Baltimore SoundStage • Rainbow Rock - Jammin' Java (10:30 AM Morning Show) • Smokey Robinson - the Theater at MGM National Harbor [7100 Oxon Hill Rd, Oxon Hill, MD] Sunday, 16 September 2018 [link to this day] • Coco Montoya - State Theatre • Laruin Talese - Blues Alley (Two shows) • Nils Lofgren & Friends (an acoustic evening) - Birchmere • Van Morrison - Jiffy Lube Live Monday, 17 September 2018 [link to this day] • In the Vane of . . . Bob Dylan: Annapolis artists playing tributes & Dylan-inspired originals - Rams Head On Stage (Annapolis) • Kneebody - Blues Alley (Two shows) • Revocation, Exhumed, Rivers of Nihil, and Yautja - Metro Gallery (Baltimore) • Rolling Blackouts Coastal Fever - Black Cat (Backstage) Tuesday, 18 September 2018 [link to this day] • Alison Krauss - The Anthem [901 Wharf Street SW, Washington, DC] • Amos Lee and Caitlyn Smith - Lincoln Theatre (My New Moon Tour) • Butch Walker and Greg Holden - Baltimore SoundStage (the Last Days of Summer Tour) • D.R.I., A Wilhelm Scream, Kaustik, and Babies with Rabies - Ottobar (Baltimore) • Dead Sara and Welles - Black Cat (Backstage) • Fidlar, Dilly Dally, and Nobro - 9:30 Club • Pohgoh, Thrushes, and J.Robbins - Metro Gallery (Baltimore) • Robbie Fulks and Linda Gail Lewis - Jammin' Java • Seether and Tremonti - Rams Head Live! (Baltimore) Wednesday, 19 September 2018 [link to this day] • Car Seat Headrest, Naked Giants, and Don Babylon - 9:30 Club - sold out • Childish Gambino and Rae Sremmurd - Capital One Arena (formerly Verizon Center) • Residente - Fillmore Silver Spring Thursday, 20 September 2018 [link to this day] • André Rieu and his Johann Strauss Orchestra - Patriot Center / EagleBank Arena • Ava Luna - Metro Gallery (Baltimore) • Car Seat Headrest, Naked Giants, and Don Babylon - 9:30 Club • Courtney Marie Andrews - Rock & Roll Hotel • James Bay - The Anthem [901 Wharf Street SW, Washington, DC] • LVL UP (Final Tour) - DC9 • Mike Stern - Dennis Chambers with Bob Franceschini & Tom Kennedy - Blues Alley (Two shows) Friday, 21 September 2018 [link to this day] • Arthur Buck - Rock & Roll Hotel • the Bayside Tigers (90s tribute) - Rams Head Live! (Baltimore) • Elton John - Capital One Arena (formerly Verizon Center) (Farewell Yellow Brick Road Tour) • Euge Groove - Birchmere • Gary Numan and Nightmare Air - 9:30 Club (Early show - 6 PM) • Joshua Hedley (Mr. Jukebox record release show) - Union Stage [740 Water Street SW, Washington, DC 20024] • Karla Bonoff - AMP • Lost 80s Live - Warner Theatre • Mastodon, Dinosaur Jr., and Netherlands - Fillmore Silver Spring • Mike Stern - Dennis Chambers with Bob Franceschini & Tom Kennedy - Blues Alley (Two shows) • Mortified: Live Podcast - Black Cat (Mainstage) • Nicki Minaj and Future - Baltimore Arena (Royal Farms Arena) (NICKIHNDRXX Tour) • Portugal The Man and Lucious - Merriweather Post Pavilion • Saint Sister - DC9 • Tribute to Los Fabulosos Cadillacs & Los Autenticos Decadentes - State Theatre • Usnea - Atlas Brew Works [2052 West Virginia Ave NE #102, WDC] • Whethan, Sweater Beats, and Andrew Luce - 9:30 Club (Late show - 10 PM) Saturday, 22 September 2018 [link to this day] • BSO: Beethoven Eroica Symphony - Strathmore (Music Center) • Cherub and Maddy O'Neal - Baltimore SoundStage • Elton John - Capital One Arena (formerly Verizon Center) (Farewell Yellow Brick Road Tour) • Family & Friends: Felix Culpa Tour - Jammin' Java (Late show - 10 PM) • Inna - Howard Theatre • Mike Stern - Dennis Chambers with Bob Franceschini & Tom Kennedy - Blues Alley (Two shows) • Mystic Braves, the Creation Factory, and the Beginners Mynd - DC9 • Owl City and Matthew Thiessen & the Earthquakes - 9:30 Club • Rooney and Mating Ritual - Rock & Roll Hotel • Russell Peters - DAR Constitution Hall • Shenandoah Run - Jammin' Java (Early show - 6:30 PM) • Trillectro 2018: SZA, 2 Chainz, RL Grime, Young Thug, Playboi Carti, The Internet, Smokepurpp, Rico Nasty, Maxo Kream, Sheck Wes, Snoh Aalegra, Rayana Jay, Everyday People, Jungle Fever, Beau Young Prince, Good Intent, Rezt, Innanet James, Soduh, That Feel Good, Joy Club, Skin Valley, Closed Sessions, First Family, Girlaaa, Chicken & Mumbo Sauce, True Laurels, Special Guest: Carnage - Merriweather Post Pavilion • the Young Dubliners - the Hamilton Sunday, 23 September 2018 [link to this day] • Carlos Vives - The Anthem [901 Wharf Street SW, Washington, DC] • Emma Ruth Rundle and Jaye Jayle - Metro Gallery (Baltimore) • the Growlers - 9:30 Club • Mike Stern - Dennis Chambers with Bob Franceschini & Tom Kennedy - Blues Alley (Two shows) • No Raza, Rat Infested, Sangre Inedita, and EvilTerror - the Pinch [3548 14th St NW, WDC] • Noah Gundersen (acoustic) and Harrison Whitford - Miracle Theatre [535 8th St SE, WDC] • the Score, the Orphan the Poet, and Birthday - DC9 • Steel Panther and the Wild! - Rams Head Live! (Baltimore) • Zao, the Atlas Moth, and Yashira - Ottobar (Baltimore) Tuesday, 25 September 2018 [link to this day] • Beth Hart: Special Solo Performance - 6th & I • Chromeo and Steven A. Clark - Rams Head Live! (Baltimore) • Fickle Friends - DC9 (You Are Someone Else Tour) • Game of Thrones Live Concert Experience featuring Ramin Djawadi - Capital One Arena (formerly Verizon Center) • Idles and Bambaa - Rock & Roll Hotel • Jay Rock and Reason - Baltimore SoundStage (the Big Redemption Tour) • Jump Little Children (album release party) and Michael Flynn - City Winery DC [1350 Okie St NE, Washington, DC 20002] • On Cinema Live! with Tim Heidecker and Gregg Turkington - Fillmore Silver Spring • SG Lewis - Union Stage [740 Water Street SW, Washington, DC 20024] Wednesday, 26 September 2018 [link to this day] • Alestorm and Gloryhammer - Baltimore SoundStage • Sales - Rock & Roll Hotel Thursday, 27 September 2018 [link to this day] • Andaiye - Blues Alley (Two shows) • Dream Wife - DC9 • Eric Benet & Faith Evans - Birchmere • Israel Nash & Band - Jammin' Java (Lifted Tour 2018) • Miniature Tigers - Rock & Roll Hotel (Tell It To the Volcano 10th Anniversary Tour) • Mt. Joy - U St Music Hall (Early show - 7 PM) • Nicole Atkins and Indianola - Baltimore SoundStage Friday, 28 September 2018 [link to this day] • Archie Fisher & Garnet Rogers: The Best Times After All - Jammin' Java • Blood Orange - Lincoln Theatre • the Deep Dark Woods and Native Harrow - DC9 • Eric Benet & Faith Evans - Birchmere • Future Islands - The Anthem [901 Wharf Street SW, Washington, DC] • Hiroshima - Rams Head On Stage (Annapolis) • Jade Bird and Field Report (solo) - Rock & Roll Hotel • Joan Baez - Warner Theatre (Fare Thee Well Tour) - sold out • Leftover Salmon - State Theatre • Let It Flow - AMP • the National, Cat Power, and Phoebe Bridgers - Merriweather Post Pavilion • Rene Marie: Experiment in Truth - Blues Alley (Two shows) Saturday, 29 September 2018 [link to this day] • Active Bird Community - DC9 • Belly - 9:30 Club • Disney Junior Dance Party on Tour - DAR Constitution Hall • Gazebo: Concert & New Wave Dance Party with DJ BPM - Jammin' Java • Ginuwine - Howard Theatre • Hiroshima - Birchmere • Jo Koy - The Anthem [901 Wharf Street SW, Washington, DC] (Break the Mold Tour) • National Philharmonic: On the Waterfront - Strathmore (Music Center) • Rainbow Kitten Surprise and Caroline Rose - Rams Head Live! (Baltimore) • Rene Marie: Experiment in Truth - Blues Alley (Two shows) • Social Distortion, Justin Townes Earle, and Valley Queen - Fillmore Silver Spring Sunday, 30 September 2018 [link to this day] • the Australian Pink Floyd Show - Strathmore (Music Center) • Cowboy Mouth - AMP • Nathan Angelo - Jammin' Java • Rene Marie: Experiment in Truth - Blues Alley (Two shows) • WPOC Sunday in the Country: Brett Eldredge, Dan + Shay, Dustin Lynch, Devin Dawson, Morgan Evans, Jimmie Allen, Jillian Jacqueline - Merriweather Post Pavilion (1 PM Doors) Monday, 1 October 2018 [link to this day] • the Chick Corea Trio: Vigilette with Carlitos Del Puerto and Marcus Gilmore - Birchmere • Ohmme - Metro Gallery (Baltimore) • Trad Gras Och Stenar and Endless Boogie - DC9 Tuesday, 2 October 2018 [link to this day] • Donovan Woods & the Opposition - Jammin' Java • Maroon 5 - Capital One Arena (formerly Verizon Center) (Red Pill Blues Tour) • Slash featuring Myles Kennedy and the Conspirators - Fillmore Silver Spring (Living the Dream Tour) Wednesday, 3 October 2018 [link to this day] • the Frights - Rock & Roll Hotel (Hypochondriac Tour) • Leon Bridges and Khruangbin - The Anthem [901 Wharf Street SW, Washington, DC] • Liz Phair and Speedy Ortiz - 9:30 Club Thursday, 4 October 2018 [link to this day] • Brian Fallon (the Gaslight Anthem) & Craig Finn: Songs from the Hymnal - 6th & I • Darden Smith: Songs and Stories from The Habit of Noticing: Using Creativity to Make a Life (and a Living) - Jammin' Java • the Steeldrivers with Kieran Kane & Rayna Gellert - Birchmere • Thrice - Fillmore Silver Spring • Troye Sivan, Kim Petras, and Leland - The Anthem [901 Wharf Street SW, Washington, DC] Friday, 5 October 2018 [link to this day] • Blitzen Trapper - Rock & Roll Hotel (Furr 10th Anniversary Tour) • Florence + the Machine and Beth Ditto - The Anthem [901 Wharf Street SW, Washington, DC] - sold out • Julia Nixon: the Songs of Burt Bacharach & Hal David - AMP • Not Even and JC & Teddy D - Jammin' Java • the Steeldrivers with Kieran Kane & Rayna Gellert - Birchmere Saturday, 6 October 2018 [link to this day] • Chelsea Cutler and Christian French - DC9 • Florence + the Machine and Beth Ditto - The Anthem [901 Wharf Street SW, Washington, DC] • the Frights and Hunny - Metro Gallery (Baltimore) • Great Lake Swimmers - Rock & Roll Hotel • the Hot Lanes Big Band Presents the Original Music of Bobby Jasinski - Jammin' Java (1 PM Afternoon Show) • King Khan & the Shrines and Gabriella Cohen - Black Cat (Mainstage) • Lady Antebellum & Darius Rucker with Russell Dickerson - Jiffy Lube Live (the 2018 Country Megaticket) • Martin Barre (of Jethro Tull) - Rams Head On Stage (Annapolis) • Nora Jane Struthers - Jammin' Java • Pat Metheny - Strathmore (Music Center) • Rata Blanca - State Theatre • Simple Minds - 9:30 Club (Walk Between Worlds Tour) Sunday, 7 October 2018 [link to this day] • BSO: Sibelius Sypmonies - Strathmore (Music Center - 3 PM) • Herman's Hermits starring Peter Noone - Birchmere • HONNE - 9:30 Club • Papa Roach and Of Mice & Men - Fillmore Silver Spring Monday, 8 October 2018 [link to this day] • Noah Kahan - Jammin' Java Tuesday, 9 October 2018 [link to this day] • Nine Inch Nails, the Jesus and Mary Chain, and Kite Base - The Anthem [901 Wharf Street SW, Washington, DC] • Ninja Sex Party - Fillmore Silver Spring • Swing Shift - Blues Alley (Two shows) Wednesday, 10 October 2018 [link to this day] • Lydia Lunch Retrovirus (Weasel Walter + Bob Bert + Tim Dahl) - Metro Gallery (Baltimore) • Nine Inch Nails, the Jesus and Mary Chain, and Kite Base - The Anthem [901 Wharf Street SW, Washington, DC] Thursday, 11 October 2018 [link to this day] • Amorphis, Dark Tranquillity, Moonspell, and Omnium Gatherum - Baltimore SoundStage • Ben Howard and Wye Oak - The Anthem [901 Wharf Street SW, Washington, DC] • Bob Moses and Mansionair - 9:30 Club • BSO SuperPops: Tony DeSare - Strathmore (Music Center) • Gruff Rhys - DC9 • the Jayhawks - Birchmere • Megative and Jonny Gofigure - Black Cat (Backstage) • Rachelle Ferrell - Blues Alley (Two shows) • Three Dog Night - Rams Head On Stage (Annapolis) • Trivium, Avatar, and Light the Torch - Rams Head Live! (Baltimore) (the Sin and the Sentence World Tour) • Vinicius Cantuária - Strathmore (Mansion) Friday, 12 October 2018 [link to this day] • Jane Monheit - Rams Head On Stage (Annapolis) • Lovelytheband - Rock & Roll Hotel • Maria Bamford Live - Warner Theatre • Murder By Death - 9:30 Club • Rachelle Ferrell - Blues Alley (Two shows) • Raul Midón - AMP • Satan's Unholy Abomination Fest 6: Inferno and more TBA - Mi Mariachi de Wheaton [2715 University Blvd W, Wheaton, MD] • Satan's Unholy Abomination Festival Vol. 6H Restaurant & Night Club [11300 Georgia Ave, Silver Spring, MD] (NOTE: ShowlistDC does not support racism, but we do try to list every concert in the area, regardless of the bands' points of view or political beliefs. Please read up on the bands playing and consider if these are bands you want to support.) • Wintersun, Ne Obliviscaris, and Sarah Longfield - Baltimore SoundStage (North American Forest Tour 2018) • ZOSO (Led Zeppelin tribute) - State Theatre Saturday, 13 October 2018 [link to this day] • Chris Stapleton, Marty Stuart, and Brent Cobb - Jiffy Lube Live • Goo Goo Dolls - The Anthem [901 Wharf Street SW, Washington, DC] • the Milk Carton Kids and the Barr Brothers - Lincoln Theatre • National Philharmonic: Lenny's Playlist - Strathmore (Music Center) • the Nields - Jammin' Java • Rachelle Ferrell - Blues Alley (Two shows) • the Record Company - 9:30 Club • Streetlight Manifesto (performing Everything Goes Numb in its entirety) and Mephiskapheles - Rams Head Live! (Baltimore) • Whose Live Anyway? - Warner Theatre Sunday, 14 October 2018 [link to this day] • the Caribbean and Marriage Blanc - Galaxy Hut • National Philharmonic: Lenny's Playlist - Strathmore (Music Center - 3 PM) • NF - The Anthem [901 Wharf Street SW, Washington, DC] (Perception Tour) • Rachelle Ferrell - Blues Alley (Two shows) • the Record Company and Madisen Ward & the Mama Bear - Rams Head Live! (Baltimore) Monday, 15 October 2018 [link to this day] • Mikaela Davis - DC9 (Delivery Tour) • Tyler Childers - 9:30 Club Tuesday, 16 October 2018 [link to this day] • Matthew Perryman Jones and Molly Parden - Jammin' Java • Passenger - 9:30 Club Wednesday, 17 October 2018 [link to this day] • Death Cab for Cutie and Charly Bliss - The Anthem [901 Wharf Street SW, Washington, DC] • Johnny Marr - Fillmore Silver Spring • Juanito Pascual's New Flamenco Trio - Blues Alley (Two shows) • Little Dragon - Rock & Roll Hotel • Wynonna & the Big Noise - Birchmere Thursday, 18 October 2018 [link to this day] • Candy Dulfer - Birchmere • Chvrches and Lo Moon - The Anthem [901 Wharf Street SW, Washington, DC] • Dee Dee Bridgewater - Blues Alley (Two shows) • Lavinia Meijer - Strathmore (Mansion) • Tank & the Bangas, Big Freedia, and Naughty Professor - 9:30 Club - sold out • Tank and the Bangas &ajmp; Big Freedia with Naughty Professor - 9:30 Club - sold out • YolanDa Brown - the Hamilton Friday, 19 October 2018 [link to this day] • Andy Grammer - Baltimore SoundStage (the Good Parts Tour) • Dee Dee Bridgewater - Blues Alley (Two shows) • Glorietta - Rock & Roll Hotel • Lil Xan - Total Xanarchy - Fillmore Silver Spring (Monster Energy Outbreak Tour) • Stephanie Mills - Birchmere • Trevor Noah - DAR Constitution Hall Saturday, 20 October 2018 [link to this day] • Anderson East and Savannah Conley - Baltimore SoundStage • BSO: Vivaldi Four Seasons - Strathmore (Music Center) • Dee Dee Bridgewater - Blues Alley (Two shows) • Joe Russo's Almost Dead with Oteil Burbridge on bass - The Anthem [901 Wharf Street SW, Washington, DC] • Stephanie Mills - Birchmere • Trevor Noah - DAR Constitution Hall • the Wombats and Barns Courtney - Rams Head Live! (Baltimore) Sunday, 21 October 2018 [link to this day] • Big Thief and the Range of Light Wilderness - 9:30 Club • Dee Dee Bridgewater - Blues Alley (Two shows) • Dying Fetus, Incantation, Gatecreeper, and Genocide Pact - Baltimore SoundStage (Revolver Presents: Contanimation Tour) • Eve Ensler & Anne Lamott - Strathmore (Music Center) • Garbage - Lincoln Theatre (Version 2.0 20th Anniversary Tour) - sold out • the Glitch Mob - Rams Head Live! (Baltimore) • Lily Allen - Fillmore Silver Spring • Ottmar Liebert & Luna Legra - Birchmere • the Relapse Symphony (reunion show) and Divine By Night - Jammin' Java Monday, 22 October 2018 [link to this day] • Antigama, Violent Opposition, and Drugs of Faith - Metro Gallery (Baltimore) • Gallant and Jamila Woods - 9:30 Club Tuesday, 23 October 2018 [link to this day] • Jessie J - Fillmore Silver Spring (the R.O.S.E. Tour) • RuPaul's Drag Race: Werq the World - Lincoln Theatre Wednesday, 24 October 2018 [link to this day] • Hippo Campus and the Districts - 9:30 Club • Jacqui Naylor - Blues Alley (Two shows) Thursday, 25 October 2018 [link to this day] • Descendents, Teenage Bottlerock, and Ruth Ruth - Fillmore Silver Spring • Hey Ocean! - DC9 • the Music of Cream: 50th Anniversary - Rams Head Live! (Baltimore) • Najee - Blues Alley (Two shows) • Nick Cave & the Bad Seeds and Cigarettes After Sex - The Anthem [901 Wharf Street SW, Washington, DC] Friday, 26 October 2018 [link to this day] • Dermot Kennedy - Black Cat (Mainstage) • Monster Magnet, Electric Citizen, Dark Sky Funeral, and Mountainwolf - Baltimore SoundStage • Najee - Blues Alley (Two shows) • the Revolution - Fillmore Silver Spring • They Might Be Giants - Rams Head Live! (Baltimore) • Trevor Noah - DAR Constitution Hall • Yungblud and Arrested Youth - DC9 (21st Century Liability Tour) Saturday, 27 October 2018 [link to this day] • BSO: Grieg Piano Concerto - Strathmore (Music Center) • Days of Darkness II: Alcest, Earth, Front Line Assembly, Die Krupps, Controlled Bleeding, Earth Electric, Rougemarine, Black Pyramid - Rams Head Live! (Baltimore) • Days of Darkness II: Bell Witch, Statiqbloom, Heavy Temple, Crowhurst, Crazy Bull, Electropathic, Pale Spring - Baltimore SoundStage • MASH featuring John Abraham, Alka Yagnik, Malaika Arora Khan, LV Revanth, Kubbra Sait, Bhoomi Trivedi, Sudesh, and Krushna - Patriot Center / EagleBank Arena (Rescheduled from 5/27/18) • Najee - Blues Alley (Two shows) • Ruston Kelly and Katie Pruitt - Jammin' Java (Dying Star Fall Tour) Sunday, 28 October 2018 [link to this day] • Days of Darkness II: Blue Öyster Cult, Claudio Simonetti's Goblin (Suspiria live score), Anna Von Hausswolff, Acid Witch, Dan Terminus, Earthride, Lazerpunk, Alms - Rams Head Live! (Baltimore) • Days of Darkness II: Rome, Bang, Satan's Satyrs, Child Bite, Ecstatic Vision, Pale Divine, John Haughm, Crud - Baltimore SoundStage • Goran Bregovic - Strathmore (Music Center) • Najee - Blues Alley (Two shows) • Roky Erickson - Black Cat (Mainstage) Monday, 29 October 2018 [link to this day] • Jain and Drama - 9:30 Club Tuesday, 30 October 2018 [link to this day] • Tom Misch - Rams Head Live! (Baltimore) Wednesday, 31 October 2018 [link to this day] • Chief Keef - Fillmore Silver Spring (Back From the Dead Fest) Thursday, 1 November 2018 [link to this day] • Patty Larkin - Jammin' Java • Wu-Tang Clan - The Anthem [901 Wharf Street SW, Washington, DC] Friday, 2 November 2018 [link to this day] • Lucky Kaplansky - Jammin' Java • Max Frost and Upsahl - DC9 Saturday, 3 November 2018 [link to this day] • Eden and Sasha Sloan - Rams Head Live! (Baltimore) • Mike Epps - DAR Constitution Hall (Two shows - 7 PM & 10:30 PM) • Raven's Night: momento Mori 2018 - Birchmere • Wanda Sykes - Strathmore (Music Center) Sunday, 4 November 2018 [link to this day] • Chris Stapleton - Baltimore Arena (Royal Farms Arena) (All American Road Show) • Christine & the Queens - 9:30 Club • David Finckel (cello ) & Wu Han (piano) - Wolf Trap (the Barns - 3 PM) • Elvis Costello & the Imposters - DAR Constitution Hall • Tom Green - State Theatre Monday, 5 November 2018 [link to this day] • Postmodern Jukebox - Strathmore (Music Center) Tuesday, 6 November 2018 [link to this day] • Ghostland Observatory and Gibbz - 6th & I • Yaeji - Black Cat (Mainstage) Wednesday, 7 November 2018 [link to this day] • Tenacious D and Wynchester - The Anthem [901 Wharf Street SW, Washington, DC] Thursday, 8 November 2018 [link to this day] • Aida Cuevas - Strathmore (Music Center) • Darwin Deez - DC9 • Midland and Desure - 9:30 Club (Late show - 10 PM) Friday, 9 November 2018 [link to this day] • Lake Street Dive - The Anthem [901 Wharf Street SW, Washington, DC] • the New Chinese Acrobats - Strathmore (Music Center) • the Tallest Man on Earth - Lincoln Theatre (When The Bird Sees the Solid Ground Tour) Saturday, 10 November 2018 [link to this day] • Aparna Nancherla - 6th & I • BSO: Poulenc Concerto for Two Pianos - Strathmore (Music Center) • the Joy Formidable and Tancred - Black Cat (Mainstage) • Kamasi Washington - Lincoln Theatre Sunday, 11 November 2018 [link to this day] • Gino Vannelli - Rams Head On Stage (Annapolis) Monday, 12 November 2018 [link to this day] • Charlotte Lawrence - DC9 • Doyle (of the Misfits), Sonci Creeps, and Meteor King - Baltimore SoundStage (World Abomination Tour 2018) Tuesday, 13 November 2018 [link to this day] • Ty Segall (solo acoustic) - 9:30 Club Wednesday, 14 November 2018 [link to this day] • Frank Vignola: Hot Jazz Guitar Trio - Blues Alley (Two shows) Thursday, 15 November 2018 [link to this day] • Josh Groban and Idina Menzel - Capital One Arena (formerly Verizon Center) (Bridges Tour) • Renaissance - Baltimore SoundStage (Day of the Dreamer) Friday, 16 November 2018 [link to this day] • BSO Off the Cuff: Copland Symphony No. 3 - Strathmore (Music Center) • Lynyrd Skynyrd - Baltimore Arena (Royal Farms Arena) (Last of the Street Survivors Farewell Tour) • Mary Fahl of October Project(full band) - Miracle Theatre [535 8th St SE, WDC] • Mitski and Jessica Lea Mayfield - 9:30 Club (Late show - 10 PM) • Randy Rogers Band - 9:30 Club (Early show - 6 PM) • Young the Giant and Lights - The Anthem [901 Wharf Street SW, Washington, DC] Saturday, 17 November 2018 [link to this day] • MC Lars & I Fight Dragons, Wreck the System, and Rare Candy - Metro Gallery (Baltimore) • National Philharmonic: Bernstein Choral Celebration - Strathmore (Music Center) Sunday, 18 November 2018 [link to this day] • BSO: Copland Symphony No. 3 - Strathmore (Music Center - 3 PM) • MC Lars - Jammin' Java • Wild Nothing - 9:30 Club Tuesday, 20 November 2018 [link to this day] • the Dead South - 9:30 Club • Yellow Days - Rock & Roll Hotel Wednesday, 21 November 2018 [link to this day] • Allen Stone and Nick Waterhouse - 9:30 Club • Tash Sultana and Ocean Alley - The Anthem [901 Wharf Street SW, Washington, DC] (Flow State World Tour) Friday, 23 November 2018 [link to this day] • the Nighthawks and Billy Price - State Theatre • Tierra Santa - Mexico Lindo de Maryland MXL Night Club [5652 Annapolis Rd, Bladensburg, MD] Saturday, 24 November 2018 [link to this day] • Maze featuring Frankie Beverly and Joe - DAR Constitution Hall Tuesday, 27 November 2018 [link to this day] • Hot Tuna (acoustic) - City Winery DC [1350 Okie St NE, Washington, DC 20002] Wednesday, 28 November 2018 [link to this day] • the Julian Lage Trio - Union Stage [740 Water Street SW, Washington, DC 20024] Thursday, 29 November 2018 [link to this day] • Stacey Kent - Blues Alley (Two shows) Friday, 30 November 2018 [link to this day] • Kurt Vile & the Violators and Jessica Pratt - 9:30 Club • Stacey Kent - Blues Alley (Two shows) • Theresa Caputo (From TLC's Long Island Medium) - the Theater at MGM National Harbor [7100 Oxon Hill Rd, Oxon Hill, MD] Saturday, 1 December 2018 [link to this day] • Stacey Kent - Blues Alley (Two shows) • Storm Large (of Pink Martini) - AMP Sunday, 2 December 2018 [link to this day] • Sabrina Benaim and Clementine Von Radics - Jammin' Java • Stacey Kent - Blues Alley (Two shows) Wednesday, 5 December 2018 [link to this day] • Ministry, Carpenter Brut, and Igorrr - Fillmore Silver Spring Thursday, 6 December 2018 [link to this day] • 98 Degrees - Fillmore Silver Spring • the Ballroom Thieves - Rock & Roll Hotel • Chris Young - Baltimore Arena (Royal Farms Arena) (Losing Sleep Tour) Friday, 7 December 2018 [link to this day] • Amber Run - Rock & Roll Hotel Saturday, 8 December 2018 [link to this day] • Rufus Wainwright - Strathmore (Music Center) Thursday, 13 December 2018 [link to this day] • BSO: Cirque Nutcracker - Strathmore (Music Center) Saturday, 15 December 2018 [link to this day] • Rockapella - State Theatre • Turnpike Troubadours - Fillmore Silver Spring Sunday, 16 December 2018 [link to this day] • Moscow Ballet's great Russian Nutcracker - Strathmore (Music Center - 2 PM & 7 PM) Monday, 17 December 2018 [link to this day] • Moscow Ballet's great Russian Nutcracker - Strathmore (Music Center) Wednesday, 19 December 2018 [link to this day] • a John Waters Christmas - Baltimore SoundStage Saturday, 22 December 2018 [link to this day] • National Philharmonic: Handel's Messiah - Strathmore (Music Center) Sunday, 23 December 2018 [link to this day] • National Philharmonic: Handel's Messiah - Strathmore (Music Center - 2 PM & 7 PM) Saturday, 29 December 2018 [link to this day] • New Year's Comedy Jam - DAR Constitution Hall Friday, 4 January 2019 [link to this day] • Justin Timberlake - Capital One Arena (formerly Verizon Center) (the Man of the Woods Tour) Saturday, 5 January 2019 [link to this day] • BSO: Leon Fleischer's Birthday Celebration - Strathmore (Music Center) Friday, 11 January 2019 [link to this day] • BSO Off the Cuff: Turangalia-symphonie - Strathmore (Music Center) Sunday, 13 January 2019 [link to this day] • BSO: Turangalia-symphonie - Strathmore (Music Center - 3 PM) Saturday, 19 January 2019 [link to this day] • BSO: Sibelius Violin Concerto - Strathmore (Music Center) Thursday, 24 January 2019 [link to this day] • BSO SuperPops: Rodgers & Hammerstein - Strathmore (Music Center) Saturday, 26 January 2019 [link to this day] • National Philharmonic: Infamous Brahms - Strathmore (Music Center) Sunday, 27 January 2019 [link to this day] • National Philharmonic: Infamous Brahms - Strathmore (Music Center - 3 PM) Thursday, 31 January 2019 [link to this day] • BSO: Respighi Pines of Rome - Strathmore (Music Center) Saturday, 2 February 2019 [link to this day] • National Philharmonic: Chopin - Recollections of Home - Strathmore (Music Center) Thursday, 7 February 2019 [link to this day] • Tessa Lark - Strathmore (Mansion) Saturday, 9 February 2019 [link to this day] • BSO: Mozart Symphony No. 40 - Strathmore (Music Center) Thursday, 14 February 2019 [link to this day] • Ivan Amodei presents Secrets and Illusions - Lisner Auditorium Saturday, 16 February 2019 [link to this day] • BSO: Liszt Piano Concerto No. 1 - Strathmore (Music Center) Sunday, 17 February 2019 [link to this day] • National Symphony Orchestra of Cuba with Esperanza Spalding - Strathmore (Music Center - 4 PM) CANCELLED Thursday, 21 February 2019 [link to this day] • Farruquito - Strathmore (Music Center) Friday, 22 February 2019 [link to this day] • BSO Off the Cuff: Elgar Cello Concerto - Strathmore (Music Center) Saturday, 23 February 2019 [link to this day] • National Philharmonic: the Debut - Strathmore (Music Center) Sunday, 24 February 2019 [link to this day] • BSO: Elgar Cello Concerto - Strathmore (Music Center - 3 PM) Thursday, 28 February 2019 [link to this day] • BSO SuperPops: Christina Bianco - Strathmore (Music Center) Saturday, 9 March 2019 [link to this day] • BSO: Scheherazade - Strathmore (Music Center) Sunday, 10 March 2019 [link to this day] • National Philharmonic: Sunday Serenades - Strathmore (Music Center - 3 PM) Thursday, 14 March 2019 [link to this day] • BSO: Appalachian Spring - Strathmore (Music Center) Sunday, 24 March 2019 [link to this day] • Fleetwood Mac - Baltimore Arena (Royal Farms Arena) Thursday, 28 March 2019 [link to this day] • BSO: Brahms Piano Concert No. 1 - Strathmore (Music Center) Saturday, 30 March 2019 [link to this day] • National Philharmonic: Sounds of New Orleans - Strathmore (Music Center) Thursday, 4 April 2019 [link to this day] • BSO: Cirque Goes Hollywood - Strathmore (Music Center) Thursday, 11 April 2019 [link to this day] • BSO: Porgy & Bess - Strathmore (Music Center) Saturday, 13 April 2019 [link to this day] • National Philharmonic: Verdi Requiem - Strathmore (Music Center) Thursday, 2 May 2019 [link to this day] • BSO: An American in Paris - Strathmore (Music Center) Thursday, 9 May 2019 [link to this day] • BSO: Tchaikovsky Violin Concerto - Strathmore (Music Center) Friday, 10 May 2019 [link to this day] • Chick Corea & Béla Fleck - Strathmore (Music Center) Saturday, 11 May 2019 [link to this day] • National Philharmonic: Bernstein & Beethoven Part I - Strathmore (Music Center) Saturday, 18 May 2019 [link to this day] • BSO: Brahms Violin Concerto - Strathmore (Music Center) Friday, 31 May 2019 [link to this day] • BSO Off the Cuff: André Watts Performs Beethoven's Emperor - Strathmore (Music Center) Saturday, 1 June 2019 [link to this day] • National Philharmonic: Bernstein & Beethoven Part II - Strathmore (Music Center) Sunday, 2 June 2019 [link to this day] • BSO: André Watts Performs Beethoven's Emperor - Strathmore (Music Center - 3 PM) Saturday, 15 June 2019 [link to this day] • BSO: West Side Story - Strathmore (Music Center)
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.mysql; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import io.debezium.config.CommonConnectorConfig; import io.debezium.connector.AbstractSourceInfo; import io.debezium.connector.LegacyV1AbstractSourceInfoStructMaker; public class LegacyV1MySqlSourceInfoStructMaker extends LegacyV1AbstractSourceInfoStructMaker<SourceInfo> { private final Schema schema; public LegacyV1MySqlSourceInfoStructMaker(String connector, String version, CommonConnectorConfig connectorConfig) { super(connector, version, connectorConfig); schema = commonSchemaBuilder() .name("io.debezium.connector.mysql.Source") .field(AbstractSourceInfo.SERVER_NAME_KEY, Schema.STRING_SCHEMA) .field(SourceInfo.SERVER_ID_KEY, Schema.INT64_SCHEMA) .field(SourceInfo.TIMESTAMP_KEY, Schema.INT64_SCHEMA) .field(SourceInfo.GTID_KEY, Schema.OPTIONAL_STRING_SCHEMA) .field(SourceInfo.BINLOG_FILENAME_OFFSET_KEY, Schema.STRING_SCHEMA) .field(SourceInfo.BINLOG_POSITION_OFFSET_KEY, Schema.INT64_SCHEMA) .field(SourceInfo.BINLOG_ROW_IN_EVENT_OFFSET_KEY, Schema.INT32_SCHEMA) .field(SourceInfo.SNAPSHOT_KEY, SchemaBuilder.bool().optional().defaultValue(false).build()) .field(SourceInfo.THREAD_KEY, Schema.OPTIONAL_INT64_SCHEMA) .field(SourceInfo.DATABASE_NAME_KEY, Schema.OPTIONAL_STRING_SCHEMA) .field(SourceInfo.TABLE_NAME_KEY, Schema.OPTIONAL_STRING_SCHEMA) .field(SourceInfo.QUERY_KEY, Schema.OPTIONAL_STRING_SCHEMA) .build(); } @Override public Schema schema() { return schema; } @Override public Struct struct(SourceInfo sourceInfo) { Struct result = commonStruct(); result.put(SourceInfo.SERVER_NAME_KEY, serverName); result.put(SourceInfo.SERVER_ID_KEY, sourceInfo.getServerId()); if (sourceInfo.getCurrentGtid() != null) { // Don't put the GTID Set into the struct; only the current GTID is fine ... result.put(SourceInfo.GTID_KEY, sourceInfo.getCurrentGtid()); } result.put(SourceInfo.BINLOG_FILENAME_OFFSET_KEY, sourceInfo.getCurrentBinlogFilename()); result.put(SourceInfo.BINLOG_POSITION_OFFSET_KEY, sourceInfo.getCurrentBinlogPosition()); result.put(SourceInfo.BINLOG_ROW_IN_EVENT_OFFSET_KEY, sourceInfo.getCurrentRowNumber()); result.put(SourceInfo.TIMESTAMP_KEY, sourceInfo.getBinlogTimestampSeconds()); if (sourceInfo.isLastSnapshot()) { // if the snapshot is COMPLETED, then this will not happen. result.put(SourceInfo.SNAPSHOT_KEY, true); } if (sourceInfo.getThreadId() >= 0) { result.put(SourceInfo.THREAD_KEY, sourceInfo.getThreadId()); } if (sourceInfo.database() != null) { result.put(SourceInfo.DATABASE_NAME_KEY, sourceInfo.database()); } if (sourceInfo.table() != null) { result.put(SourceInfo.TABLE_NAME_KEY, sourceInfo.table()); } if (sourceInfo.getQuery() != null) { result.put(SourceInfo.QUERY_KEY, sourceInfo.getQuery()); } return result; } }
If it seems that your inbox has been overloaded with Evites of late, you're not imagining things. Houston has been declared party capital of the country by Evite in a data review that analyzed the habits of its users in 39 cities. Houston ranks No. 1 in both categories studied in the first annual list of the Top 10 U.S. Party Cities. We're head of the pack in the list of "Party Animals: Which Cities Have the Most 'Yes' RSVPs?" (815,290) and tops in "Weekend Warriors: Which Cities Party Hardest on the Weekends?" To date in 2015, more than 55,000 party hosts invited guests to events through the on-line invitation and party planning service. Austin came in third in both categories, right behind second-ranking Chicago. Austin recorded more 706,253 "yes" responses in the past year and scheduled 48,526 weekend bashes via Evite. Dallas ranked 10th in the most "yes" RSVP category. Rounding out the top 10 featured in the announcement of the first annual Top 10 U.S. Party Cities were San Diego, New York, Los Angeles, Atlanta, San Francisco, Washington D.C. and Dallas. Other top scorers in the weekend warrior category were San Diego, Atlanta, San Jose, New York, Los Angeles, Seattle and a close tie for 10th were Washington D.C. and San Francisco. “As many of us get ready for the busy holiday party season, these Top Party Cities have clearly been training for this moment all year long,” said Victor Cho, Evite CEO, in a statement.
/********************************************************************* * * Filename: toim3232-sir.c * Version: 1.0 * Description: Implementation of dongles based on the Vishay/Temic * TOIM3232 SIR Endec chipset. Currently only the * IRWave IR320ST-2 is tested, although it should work * with any TOIM3232 or TOIM4232 chipset based RS232 * dongle with minimal modification. * Based heavily on the Tekram driver (tekram.c), * with thanks to Dag Brattli and Martin Diehl. * Status: Experimental. * Author: David Basden <[email protected]> * Created at: Thu Feb 09 23:47:32 2006 * * Copyright (c) 2006 David Basden. * Copyright (c) 1998-1999 Dag Brattli, * Copyright (c) 2002 Martin Diehl, * All Rights Reserved. * * 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. * * Neither Dag Brattli nor University of Tromsø admit liability nor * provide warranty for any of this software. This material is * provided "AS-IS" and at no charge. * ********************************************************************/ /* * This driver has currently only been tested on the IRWave IR320ST-2 * * PROTOCOL: * * The protocol for talking to the TOIM3232 is quite easy, and is * designed to interface with RS232 with only level convertors. The * BR/~D line on the chip is brought high to signal 'command mode', * where a command byte is sent to select the baudrate of the RS232 * interface and the pulse length of the IRDA output. When BR/~D * is brought low, the dongle then changes to the selected baudrate, * and the RS232 interface is used for data until BR/~D is brought * high again. The initial speed for the TOIMx323 after RESET is * 9600 baud. The baudrate for command-mode is the last selected * baud-rate, or 9600 after a RESET. * * The dongle I have (below) adds some extra hardware on the front end, * but this is mostly directed towards pariasitic power from the RS232 * line rather than changing very much about how to communicate with * the TOIM3232. * * The protocol to talk to the TOIM4232 chipset seems to be almost * identical to the TOIM3232 (and the 4232 datasheet is more detailed) * so this code will probably work on that as well, although I haven't * tested it on that hardware. * * Target dongle variations that might be common: * * DTR and RTS function: * The data sheet for the 4232 has a sample implementation that hooks the * DTR and RTS lines to the RESET and BaudRate/~Data lines of the * chip (through line-converters). Given both DTR and RTS would have to * be held low in normal operation, and the TOIMx232 requires +5V to * signal ground, most dongle designers would almost certainly choose * an implementation that kept at least one of DTR or RTS high in * normal operation to provide power to the dongle, but will likely * vary between designs. * * User specified command bits: * There are two user-controllable output lines from the TOIMx232 that * can be set low or high by setting the appropriate bits in the * high-nibble of the command byte (when setting speed and pulse length). * These might be used to switch on and off added hardware or extra * dongle features. * * * Target hardware: IRWave IR320ST-2 * * The IRWave IR320ST-2 is a simple dongle based on the Vishay/Temic * TOIM3232 SIR Endec and the Vishay/Temic TFDS4500 SIR IRDA transciever. * It uses a hex inverter and some discrete components to buffer and * line convert the RS232 down to 5V. * * The dongle is powered through a voltage regulator, fed by a large * capacitor. To switch the dongle on, DTR is brought high to charge * the capacitor and drive the voltage regulator. DTR isn't associated * with any control lines on the TOIM3232. Parisitic power is also taken * from the RTS, TD and RD lines when brought high, but through resistors. * When DTR is low, the circuit might lose power even with RTS high. * * RTS is inverted and attached to the BR/~D input pin. When RTS * is high, BR/~D is low, and the TOIM3232 is in the normal 'data' mode. * RTS is brought low, BR/~D is high, and the TOIM3232 is in 'command * mode'. * * For some unknown reason, the RESET line isn't actually connected * to anything. This means to reset the dongle to get it to a known * state (9600 baud) you must drop DTR and RTS low, wait for the power * capacitor to discharge, and then bring DTR (and RTS for data mode) * high again, and wait for the capacitor to charge, the power supply * to stabilise, and the oscillator clock to stabilise. * * Fortunately, if the current baudrate is known, the chipset can * easily change speed by entering command mode without having to * reset the dongle first. * * Major Components: * * - Vishay/Temic TOIM3232 SIR Endec to change RS232 pulse timings * to IRDA pulse timings * - 3.6864MHz crystal to drive TOIM3232 clock oscillator * - DM74lS04M Inverting Hex line buffer for RS232 input buffering * and level conversion * - PJ2951AC 150mA voltage regulator * - Vishay/Temic TFDS4500 SIR IRDA front-end transceiver * */ #include <linux/module.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/sched.h> #include <net/irda/irda.h> #include "sir-dev.h" static int toim3232delay = 150; /* default is 150 ms */ module_param(toim3232delay, int, 0); MODULE_PARM_DESC(toim3232delay, "toim3232 dongle write complete delay"); #if 0 static int toim3232flipdtr = 0; /* default is DTR high to reset */ module_param(toim3232flipdtr, int, 0); MODULE_PARM_DESC(toim3232flipdtr, "toim3232 dongle invert DTR (Reset)"); static int toim3232fliprts = 0; /* default is RTS high for baud change */ module_param(toim3232fliptrs, int, 0); MODULE_PARM_DESC(toim3232fliprts, "toim3232 dongle invert RTS (BR/D)"); #endif static int toim3232_open(struct sir_dev *); static int toim3232_close(struct sir_dev *); static int toim3232_change_speed(struct sir_dev *, unsigned); static int toim3232_reset(struct sir_dev *); #define TOIM3232_115200 0x00 #define TOIM3232_57600 0x01 #define TOIM3232_38400 0x02 #define TOIM3232_19200 0x03 #define TOIM3232_9600 0x06 #define TOIM3232_2400 0x0A #define TOIM3232_PW 0x10 /* Pulse select bit */ static struct dongle_driver toim3232 = { .owner = THIS_MODULE, .driver_name = "Vishay TOIM3232", .type = IRDA_TOIM3232_DONGLE, .open = toim3232_open, .close = toim3232_close, .reset = toim3232_reset, .set_speed = toim3232_change_speed, }; static int __init toim3232_sir_init(void) { if (toim3232delay < 1 || toim3232delay > 500) toim3232delay = 200; IRDA_DEBUG(1, "%s - using %d ms delay\n", toim3232.driver_name, toim3232delay); return irda_register_dongle(&toim3232); } static void __exit toim3232_sir_cleanup(void) { irda_unregister_dongle(&toim3232); } static int toim3232_open(struct sir_dev *dev) { struct qos_info *qos = &dev->qos; IRDA_DEBUG(2, "%s()\n", __func__); /* Pull the lines high to start with. * * For the IR320ST-2, we need to charge the main supply capacitor to * switch the device on. We keep DTR high throughout to do this. * When RTS, TD and RD are high, they will also trickle-charge the * cap. RTS is high for data transmission, and low for baud rate select. * -- DGB */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* The TOI3232 supports many speeds between 1200bps and 115000bps. * We really only care about those supported by the IRDA spec, but * 38400 seems to be implemented in many places */ qos->baud_rate.bits &= IR_2400|IR_9600|IR_19200|IR_38400|IR_57600|IR_115200; /* From the tekram driver. Not sure what a reasonable value is -- DGB */ qos->min_turn_time.bits = 0x01; /* Needs at least 10 ms */ irda_qos_bits_to_value(qos); /* irda thread waits 50 msec for power settling */ return 0; } static int toim3232_close(struct sir_dev *dev) { IRDA_DEBUG(2, "%s()\n", __func__); /* Power off dongle */ sirdev_set_dtr_rts(dev, FALSE, FALSE); return 0; } /* * Function toim3232change_speed (dev, state, speed) * * Set the speed for the TOIM3232 based dongle. Warning, this * function must be called with a process context! * * Algorithm * 1. keep DTR high but clear RTS to bring into baud programming mode * 2. wait at least 7us to enter programming mode * 3. send control word to set baud rate and timing * 4. wait at least 1us * 5. bring RTS high to enter DATA mode (RS232 is passed through to transceiver) * 6. should take effect immediately (although probably worth waiting) */ #define TOIM3232_STATE_WAIT_SPEED (SIRDEV_STATE_DONGLE_SPEED + 1) static int toim3232_change_speed(struct sir_dev *dev, unsigned speed) { unsigned state = dev->fsm.substate; unsigned delay = 0; u8 byte; static int ret = 0; IRDA_DEBUG(2, "%s()\n", __func__); switch(state) { case SIRDEV_STATE_DONGLE_SPEED: /* Figure out what we are going to send as a control byte */ switch (speed) { case 2400: byte = TOIM3232_PW|TOIM3232_2400; break; default: speed = 9600; ret = -EINVAL; /* fall thru */ case 9600: byte = TOIM3232_PW|TOIM3232_9600; break; case 19200: byte = TOIM3232_PW|TOIM3232_19200; break; case 38400: byte = TOIM3232_PW|TOIM3232_38400; break; case 57600: byte = TOIM3232_PW|TOIM3232_57600; break; case 115200: byte = TOIM3232_115200; break; } /* Set DTR, Clear RTS: Go into baud programming mode */ sirdev_set_dtr_rts(dev, TRUE, FALSE); /* Wait at least 7us */ udelay(14); /* Write control byte */ sirdev_raw_write(dev, &byte, 1); dev->speed = speed; state = TOIM3232_STATE_WAIT_SPEED; delay = toim3232delay; break; case TOIM3232_STATE_WAIT_SPEED: /* Have transmitted control byte * Wait for 'at least 1us' */ udelay(14); /* Set DTR, Set RTS: Go into normal data mode */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Wait (TODO: check this is needed) */ udelay(50); break; default: printk(KERN_ERR "%s - undefined state %d\n", __func__, state); ret = -EINVAL; break; } dev->fsm.substate = state; return (delay > 0) ? delay : ret; } /* * Function toim3232reset (driver) * * This function resets the toim3232 dongle. Warning, this function * must be called with a process context!! * * What we should do is: * 0. Pull RESET high * 1. Wait for at least 7us * 2. Pull RESET low * 3. Wait for at least 7us * 4. Pull BR/~D high * 5. Wait for at least 7us * 6. Send control byte to set baud rate * 7. Wait at least 1us after stop bit * 8. Pull BR/~D low * 9. Should then be in data mode * * Because the IR320ST-2 doesn't have the RESET line connected for some reason, * we'll have to do something else. * * The default speed after a RESET is 9600, so lets try just bringing it up in * data mode after switching it off, waiting for the supply capacitor to * discharge, and then switch it back on. This isn't actually pulling RESET * high, but it seems to have the same effect. * * This behaviour will probably work on dongles that have the RESET line connected, * but if not, add a flag for the IR320ST-2, and implment the above-listed proper * behaviour. * * RTS is inverted and then fed to BR/~D, so to put it in programming mode, we * need to have pull RTS low */ static int toim3232_reset(struct sir_dev *dev) { IRDA_DEBUG(2, "%s()\n", __func__); /* Switch off both DTR and RTS to switch off dongle */ sirdev_set_dtr_rts(dev, FALSE, FALSE); /* Should sleep a while. This might be evil doing it this way.*/ set_current_state(TASK_UNINTERRUPTIBLE); schedule_timeout(msecs_to_jiffies(50)); /* Set DTR, Set RTS (data mode) */ sirdev_set_dtr_rts(dev, TRUE, TRUE); /* Wait at least 10 ms for power to stabilize again */ set_current_state(TASK_UNINTERRUPTIBLE); schedule_timeout(msecs_to_jiffies(10)); /* Speed should now be 9600 */ dev->speed = 9600; return 0; } MODULE_AUTHOR("David Basden <[email protected]>"); MODULE_DESCRIPTION("Vishay/Temic TOIM3232 based dongle driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("irda-dongle-12"); /* IRDA_TOIM3232_DONGLE */ module_init(toim3232_sir_init); module_exit(toim3232_sir_cleanup);
/** * Removes a GLWindow from by this renderer. * * @param win window object */ public void removeWindow(GLWindow win) { if (windowsList != null) { windowsList.remove(win); } }
/* The evolutionary model. * * Contents: * 1. The TKF_MODEL object: allocation, initialization, destruction. * 2. Convenience routines for setting fields in an TKF. * 3. Renormalization and rescaling counts in TKF. * 4. Debugging and development code. * 5. Other routines in the API. * 6. Unit tests. * 7. Test driver. * 8. Copyright and license. * */ #include "p7_config.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include "easel.h" #include "esl_alphabet.h" #include "esl_vectorops.h" #include "esl_random.h" #include "esl_dirichlet.h" #include "esl_dmatrix.h" #include "esl_stats.h" #include "hmmer.h" #include "e2.h" #include "tkf_rate.h" #include "tkf_model.h" #include "ratematrix.h" /***************************************************************** *# 1. The TKF_MODEL object: allocation, initialization, destruction. *****************************************************************/ /* Function: tkf_model_Create() * Synopsis: Allocate a new <TKF_MODEL>. * * Purpose: Allocate a <TKF_MODEL> for symbol * alphabet <abc>, and return a pointer to it. * * The TKF_MODEL only keeps a copy of the <abc> alphabet * pointer. The caller is responsible for providing the * alphabet, keeping it around while the TKF_MODEL is in use, * and (eventually) free'ing the alphabet when it's * not needed any more. (Basically, just a step removed * from keeping the alphabet as a global.) * * Throws: <NULL> on allocation failure. */ TKF_MODEL * tkf_model_Create(TKF_RATE *R, double time, double alpha, const double *fins, int L, const ESL_ALPHABET *abc, double tol, int verbose) { TKF_MODEL *tkf = NULL; double tsubs; int status; ESL_ALLOC(tkf, sizeof(TKF_MODEL)); tkf->sub = NULL; tkf->abc = abc; tkf->R = R; tkf->time = time; tkf->gammat = 1.0 - exp(-R->mu*time); status = tkf_model_BetaFunc(R, time, &(tkf->betat)); if (tkf->betat < 0. || tkf->betat > 1.0 || isnan(tkf->betat)) { printf("tkfbeta failed %f\n", tkf->betat); goto ERROR; } if (abc != NULL) { tsubs = time * alpha; tkf->sub = ratematrix_ConditionalsFromRate(tsubs, R->em->Qstar, tol, NULL, verbose); } if (fins != NULL) esl_vec_DCopy(fins, e2_MAXABET, tkf->ins); return tkf; ERROR: if (tkf != NULL) tkf_model_Destroy(tkf); return NULL; } /* Function: tkf_model_Destroy() * Synopsis: Free a <TKF_MODEL>. * * Purpose: Frees both the shell and body of an <tkf>. * Works even if the <tkf> is damaged (incompletely allocated) * or even <NULL>. * * Note: Remember, leave reference pointers like abc, gm, and * bg alone. These are under the application's control not ours. * * Returns: (void). */ void tkf_model_Destroy(TKF_MODEL *tkf) { if (tkf == NULL) return; if (tkf->sub) esl_dmatrix_Destroy(tkf->sub); free(tkf); return; } /* */ int tkf_model_BetaFunc(TKF_RATE *R, double time, double *ret_beta) { double a; /* a = ldI-muI */ double E; /* E = exp(a*t) */ double A; /* A = lambda * exp(a*t) = exp(a*t + log(lambda)) */ double num, den; double beta; int status; if (R->lambda >= R->mu) { printf("tkf condition: ld < mu is violated \n"); status = eslFAIL; goto ERROR;} /* some asignments */ a = R->lambda - R->mu; E = exp(time * a); A = exp(time * a + log(R->lambda)); num = R->lambda * (1.0 - E); den = R->mu - A; beta = (fabs(den) > 0.)? num/den : 1e-8; #if 0 printf("\neta[t=%.3f] = %.8f || ld=%.8f\tmu=%.8f\tetaz=%.8f num %f den %f\n", time, beta, R->lambda, R->mu, R->etaz, num, den); #endif if (beta < 0.) { printf("tkfbeta is negative \n"); status = eslFAIL; goto ERROR; } *ret_beta = beta; return eslOK; ERROR: return status; }
from .user_me import UserMe from .user_change_password import UserChangePassword
Walter Thurmond sits as one of the top remaining free agents. The defensive back could have a home already if he wanted. Thurmond, 28, has turned down offers of $4 million-plus per year as he ponders retirement, a source told NFL Media Insider Ian Rapoport on Wednesday. That Thurmond has garnered offers of more than $4 million isn't surprising. In his first year moving to safety, Thurmond played exceptionally well for Philadelphia. He and Malcolm Jenkins formed one of the top safety duos in the NFL. Thurmond's versatility to play safety and drop down to corner makes him a commodity plenty of teams desire. During his six-year career, however, Thurmond has suffered several injuries, including a pectoral tear in 2014 that wiped out all but 67 snaps with the New York Giants. Last season was the first time in his career he played 16 games. Thurmond wouldn't be the first player this season to walk away with plenty of talent left in the tank, but if he decides to play, the defensive back should have options.
Declarations and Reliability The previous discussion about auto left me with a nagging doubt, which I would like to discuss here. When I wrote about auto a while ago, some readers said that they thought auto was a bad idea because it allowed programmers to get by without knowing what types they were using. I explained my thinking about this issue. Nevertheless, the discussion left me with a nagging doubt, which I would like to discuss here. The first programming language I learned was FORTRAN, which had (and still has) the interesting characteristic that if you do not declare a variable, the compiler creates it for you. In fact, the early version of FORTRAN that I learned did not even allow users to declare variables. So, for example, if you intended to write FOO = 1.0 and actually wrote FOE = 1.0 and later wrote FOO = FOO * 2.0 the compiler would not complain that you had a variable named FOE that you never used, nor would it complain that you used a variable named FOO without giving it an initial value, and would blithely take whatever garbage was in the memory assigned to FOO and multiply it by 2.0, thereby yielding other garbage. I remember reading the claim — though I don't remember where — that one of the great advances of Algol over other languages (presumably FORTRAN) was that it required its programmers to declare every variable. In effect, when you write an Algol program, you have to state the name of every variable at least twice: once when you declare it, and then again when you use it. If those two statements don't match, the compiler will reject your program. The question, then, is this: If it is a good thing that a compiler requires you to state the name of every variable at least twice, why is it not a bad thing when the compiler figures out the types of your variables for you? For example: auto it = v.begin(); Why should the programmer not be required to know that v is a vector<string> , and therefore be required to write vector<string>::iterator it = v.begin(); or something similar? After thinking about it carefully, I believe that the difference between these two cases is that FORTRAN not only creates a variable if you do not declare it, but it also creates a value for that variable. To see why FORTRAN's behavior is dangerous, consider what would happen if a Python programmer were to try to execute FOE = 1.0 FOO = FOO * 2.0 When it came time to execute the second statement, the implementation would complain that no variable named FOO exists, because in Python, a variable does not exist until a value has been assigned to it. Similarly, in C++, when I execute auto it = v.begin(); I am not asking the compiler to invent anything for me. I've written v.begin() , which is a legitimate expression, and I've said that I want to put the result of that expression somewhere. If I want to use that result, then its type is going to have to be consistent with the way(s) in which I intend to use it, so the compiler will check whatever aspects of the result's type are necessary in order for me to use that result.
The phenomenology of death, embodiment and organ transplantation. Organ transplantation is an innovative 21st century medical therapy that offers the potential to enhance and save life. In order to do so it depends on a supply of organs, usually from cadaveric donors who have suffered brain stem death. Regardless of whether and how the deceased recorded their wishes about donation, health professionals will approach the bereaved relatives, before organs are removed. In this article, the results from 19 semi-structured interviews with Scottish donor families will be presented. These accounts will focus exclusively on the families' beliefs about death, the dead body and bonds with the deceased, and whether these affected the donation decision or the organs donated. What the families said about brain stem death (BSD); how and when they understood that death had occurred; and whether the families thought that death caused a 'disembodiment' (that the self was no longer embodied) will be explored. Finally, attention will turn to the bereaved's previous relationship with the embodied person. I conclude that the phenomenology of embodiment, death and organ transplantation offers new answers to the question of 'Who am I'? That is, in order to understand what identity is, one might look for what it is that is lost at death; the body, the self and relationships with others.
Controversies in the Principles for Management of Orbital Fractures in the Pediatric Population. is preferred over a primary T-point to correct eventual residual skin redundancy. However, the technique described by Webster might represent a valuable and interesting alternative to our approach, which we will consider in our future clinical practice. An approach quite similar to that of Webster was recently published by Bracaglia et al.6 They used an L-shaped incision to overcome the evident problems associated with a T-point at the groin area. Despite the possible advantage of either the helicoidal or L-shaped approach, we try to avoid extending the incision in the area of the popliteal fossa to prevent functional problems from potential scar contracture in the posterior knee area. We feel that wound healing may be impaired when incisions run in this area because of the imminent motion. Therefore, we perform our incision along the axis of the adductor magnus muscle down to the inner aspect of the knee. A further aspect that should be discussed with the patient preoperatively is scar visibility in this helicoidal approach. Inevitably, there will be some caudal migration of the scar in the postoperative course, and this will move the scar on the anterior aspect of the thigh, at least in the upper part. This part cannot be covered with clothing such as underwear or swimsuits. In patients where there are a lot of striae, this might not be too conspicuous, but in patients with otherwise good skin conditions, this scar will be very obvious. Finally, we would like to congratulate Dr. Webster for his efforts in advancing the surgical care of patients after massive weight loss and for his kind comments on our article. DOI: 10.1097/PRS.0000000000003098
<gh_stars>1-10 // Code generated by protoc-gen-go. DO NOT EDIT. // source: cluster.proto package cloud import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" common "github.com/microsoft/moc/rpc/common" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type ClusterResponse struct { Clusters []*Cluster `protobuf:"bytes,1,rep,name=Clusters,proto3" json:"Clusters,omitempty"` Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"` Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ClusterResponse) Reset() { *m = ClusterResponse{} } func (m *ClusterResponse) String() string { return proto.CompactTextString(m) } func (*ClusterResponse) ProtoMessage() {} func (*ClusterResponse) Descriptor() ([]byte, []int) { return fileDescriptor_3cfb3b8ec240c376, []int{0} } func (m *ClusterResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ClusterResponse.Unmarshal(m, b) } func (m *ClusterResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ClusterResponse.Marshal(b, m, deterministic) } func (m *ClusterResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_ClusterResponse.Merge(m, src) } func (m *ClusterResponse) XXX_Size() int { return xxx_messageInfo_ClusterResponse.Size(m) } func (m *ClusterResponse) XXX_DiscardUnknown() { xxx_messageInfo_ClusterResponse.DiscardUnknown(m) } var xxx_messageInfo_ClusterResponse proto.InternalMessageInfo func (m *ClusterResponse) GetClusters() []*Cluster { if m != nil { return m.Clusters } return nil } func (m *ClusterResponse) GetResult() *wrappers.BoolValue { if m != nil { return m.Result } return nil } func (m *ClusterResponse) GetError() string { if m != nil { return m.Error } return "" } type Cluster struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Fqdn string `protobuf:"bytes,3,opt,name=fqdn,proto3" json:"fqdn,omitempty"` Status *common.Status `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` UserOwned bool `protobuf:"varint,5,opt,name=UserOwned,proto3" json:"UserOwned,omitempty"` IsLocalCluster bool `protobuf:"varint,6,opt,name=IsLocalCluster,proto3" json:"IsLocalCluster,omitempty"` Domain string `protobuf:"bytes,7,opt,name=domain,proto3" json:"domain,omitempty"` Nodes []*Node `protobuf:"bytes,8,rep,name=Nodes,proto3" json:"Nodes,omitempty"` LocationName string `protobuf:"bytes,9,opt,name=locationName,proto3" json:"locationName,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Cluster) Reset() { *m = Cluster{} } func (m *Cluster) String() string { return proto.CompactTextString(m) } func (*Cluster) ProtoMessage() {} func (*Cluster) Descriptor() ([]byte, []int) { return fileDescriptor_3cfb3b8ec240c376, []int{1} } func (m *Cluster) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Cluster.Unmarshal(m, b) } func (m *Cluster) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Cluster.Marshal(b, m, deterministic) } func (m *Cluster) XXX_Merge(src proto.Message) { xxx_messageInfo_Cluster.Merge(m, src) } func (m *Cluster) XXX_Size() int { return xxx_messageInfo_Cluster.Size(m) } func (m *Cluster) XXX_DiscardUnknown() { xxx_messageInfo_Cluster.DiscardUnknown(m) } var xxx_messageInfo_Cluster proto.InternalMessageInfo func (m *Cluster) GetName() string { if m != nil { return m.Name } return "" } func (m *Cluster) GetId() string { if m != nil { return m.Id } return "" } func (m *Cluster) GetFqdn() string { if m != nil { return m.Fqdn } return "" } func (m *Cluster) GetStatus() *common.Status { if m != nil { return m.Status } return nil } func (m *Cluster) GetUserOwned() bool { if m != nil { return m.UserOwned } return false } func (m *Cluster) GetIsLocalCluster() bool { if m != nil { return m.IsLocalCluster } return false } func (m *Cluster) GetDomain() string { if m != nil { return m.Domain } return "" } func (m *Cluster) GetNodes() []*Node { if m != nil { return m.Nodes } return nil } func (m *Cluster) GetLocationName() string { if m != nil { return m.LocationName } return "" } func init() { proto.RegisterType((*ClusterResponse)(nil), "moc.cloudagent.cluster.ClusterResponse") proto.RegisterType((*Cluster)(nil), "moc.cloudagent.cluster.Cluster") } func init() { proto.RegisterFile("cluster.proto", fileDescriptor_3cfb3b8ec240c376) } var fileDescriptor_3cfb3b8ec240c376 = []byte{ // 435 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x52, 0x4d, 0x6f, 0x13, 0x31, 0x10, 0x65, 0xb7, 0xcd, 0x36, 0x99, 0xa4, 0x45, 0xb2, 0x50, 0x65, 0x22, 0x04, 0x21, 0x48, 0x90, 0x0b, 0x5e, 0x29, 0x1c, 0x39, 0x51, 0x84, 0x2a, 0xa4, 0xaa, 0xa0, 0x45, 0x45, 0x7c, 0x9c, 0x1c, 0xdb, 0x09, 0x2b, 0x79, 0x3d, 0x8b, 0xed, 0x55, 0xff, 0x0a, 0xfc, 0x4d, 0x7e, 0x01, 0x5a, 0xdb, 0x69, 0x45, 0x45, 0x95, 0x53, 0x6f, 0x33, 0xcf, 0x6f, 0xde, 0x3c, 0xcf, 0x0c, 0x1c, 0x0a, 0xdd, 0x39, 0xaf, 0x2c, 0x6b, 0x2d, 0x7a, 0x24, 0xc7, 0x0d, 0x0a, 0x26, 0x34, 0x76, 0x92, 0x6f, 0x94, 0xf1, 0x2c, 0xbd, 0x4e, 0x1f, 0x6f, 0x10, 0x37, 0x5a, 0x95, 0x81, 0xb5, 0xea, 0xd6, 0xe5, 0xa5, 0xe5, 0x6d, 0xab, 0xac, 0x8b, 0x75, 0xd3, 0x89, 0xc0, 0xa6, 0x41, 0x93, 0x32, 0x30, 0x28, 0x55, 0x8c, 0xe7, 0xbf, 0x32, 0xb8, 0xff, 0x36, 0xaa, 0x54, 0xca, 0xb5, 0x68, 0x9c, 0x22, 0xaf, 0x61, 0x98, 0x20, 0x47, 0xb3, 0xd9, 0xde, 0x62, 0xbc, 0x7c, 0xc2, 0xfe, 0xdf, 0x98, 0x6d, 0x4b, 0xaf, 0x0a, 0xc8, 0x12, 0x8a, 0x4a, 0xb9, 0x4e, 0x7b, 0x9a, 0xcf, 0xb2, 0xc5, 0x78, 0x39, 0x65, 0xd1, 0x1b, 0xdb, 0x7a, 0x63, 0x27, 0x88, 0xfa, 0x33, 0xd7, 0x9d, 0xaa, 0x12, 0x93, 0x3c, 0x80, 0xc1, 0x3b, 0x6b, 0xd1, 0xd2, 0xbd, 0x59, 0xb6, 0x18, 0x55, 0x31, 0x99, 0xff, 0xce, 0xe1, 0x20, 0xc9, 0x12, 0x02, 0xfb, 0x86, 0x37, 0x8a, 0x66, 0x81, 0x10, 0x62, 0x72, 0x04, 0x79, 0x2d, 0x43, 0x97, 0x51, 0x95, 0xd7, 0xb2, 0xe7, 0xac, 0x7f, 0x4a, 0x93, 0x44, 0x42, 0x4c, 0x9e, 0x41, 0xe1, 0x3c, 0xf7, 0x9d, 0xa3, 0xfb, 0xc1, 0xcd, 0x38, 0x7c, 0xe4, 0x53, 0x80, 0xaa, 0xf4, 0x44, 0x1e, 0xc1, 0xe8, 0xc2, 0x29, 0xfb, 0xe1, 0xd2, 0x28, 0x49, 0x07, 0xb3, 0x6c, 0x31, 0xac, 0xae, 0x01, 0xf2, 0x1c, 0x8e, 0xde, 0xbb, 0x33, 0x14, 0x5c, 0x27, 0x33, 0xb4, 0x08, 0x94, 0x1b, 0x28, 0x39, 0x86, 0x42, 0x62, 0xc3, 0x6b, 0x43, 0x0f, 0x82, 0x81, 0x94, 0x91, 0x12, 0x06, 0xe7, 0x28, 0x95, 0xa3, 0xc3, 0x30, 0xca, 0x87, 0x37, 0x47, 0x19, 0x96, 0xd1, 0x33, 0xaa, 0xc8, 0x23, 0x73, 0x98, 0x68, 0x14, 0xdc, 0xd7, 0x68, 0xce, 0xfb, 0x3f, 0x8f, 0x82, 0xdc, 0x3f, 0xd8, 0xf2, 0x4f, 0x0e, 0x93, 0xd4, 0xf8, 0x4d, 0xaf, 0x42, 0xbe, 0xc2, 0xf8, 0x0c, 0xb9, 0xdc, 0x9a, 0xd9, 0xb5, 0xb0, 0xe9, 0x8b, 0x5d, 0x1b, 0x4d, 0xc7, 0x30, 0xbf, 0x47, 0xbe, 0xc3, 0xe1, 0x85, 0xd1, 0x77, 0x24, 0xfe, 0x05, 0xe0, 0x54, 0xf9, 0xbb, 0x50, 0xfe, 0x08, 0xc3, 0x53, 0xe5, 0xe3, 0x48, 0x77, 0xea, 0x3e, 0xbd, 0x7d, 0x2b, 0x57, 0x8a, 0x27, 0xe5, 0xb7, 0x97, 0x9b, 0xda, 0xff, 0xe8, 0x56, 0x4c, 0x60, 0x53, 0x36, 0xb5, 0xb0, 0xe8, 0x70, 0xed, 0xcb, 0x06, 0x45, 0x69, 0x5b, 0x51, 0x5e, 0x97, 0xc7, 0x70, 0x55, 0x84, 0x9b, 0x7f, 0xf5, 0x37, 0x00, 0x00, 0xff, 0xff, 0xb4, 0x29, 0x26, 0x65, 0xc6, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // ClusterAgentClient is the client API for ClusterAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type ClusterAgentClient interface { LoadCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) UnloadCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) GetCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) GetNodes(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*NodeResponse, error) } type clusterAgentClient struct { cc *grpc.ClientConn } func NewClusterAgentClient(cc *grpc.ClientConn) ClusterAgentClient { return &clusterAgentClient{cc} } func (c *clusterAgentClient) LoadCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) { out := new(ClusterResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.cluster.ClusterAgent/LoadCluster", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *clusterAgentClient) UnloadCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) { out := new(ClusterResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.cluster.ClusterAgent/UnloadCluster", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *clusterAgentClient) GetCluster(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*ClusterResponse, error) { out := new(ClusterResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.cluster.ClusterAgent/GetCluster", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *clusterAgentClient) GetNodes(ctx context.Context, in *Cluster, opts ...grpc.CallOption) (*NodeResponse, error) { out := new(NodeResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.cluster.ClusterAgent/GetNodes", in, out, opts...) if err != nil { return nil, err } return out, nil } // ClusterAgentServer is the server API for ClusterAgent service. type ClusterAgentServer interface { LoadCluster(context.Context, *Cluster) (*ClusterResponse, error) UnloadCluster(context.Context, *Cluster) (*ClusterResponse, error) GetCluster(context.Context, *Cluster) (*ClusterResponse, error) GetNodes(context.Context, *Cluster) (*NodeResponse, error) } // UnimplementedClusterAgentServer can be embedded to have forward compatible implementations. type UnimplementedClusterAgentServer struct { } func (*UnimplementedClusterAgentServer) LoadCluster(ctx context.Context, req *Cluster) (*ClusterResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method LoadCluster not implemented") } func (*UnimplementedClusterAgentServer) UnloadCluster(ctx context.Context, req *Cluster) (*ClusterResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UnloadCluster not implemented") } func (*UnimplementedClusterAgentServer) GetCluster(ctx context.Context, req *Cluster) (*ClusterResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetCluster not implemented") } func (*UnimplementedClusterAgentServer) GetNodes(ctx context.Context, req *Cluster) (*NodeResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetNodes not implemented") } func RegisterClusterAgentServer(s *grpc.Server, srv ClusterAgentServer) { s.RegisterService(&_ClusterAgent_serviceDesc, srv) } func _ClusterAgent_LoadCluster_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Cluster) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ClusterAgentServer).LoadCluster(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.cluster.ClusterAgent/LoadCluster", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ClusterAgentServer).LoadCluster(ctx, req.(*Cluster)) } return interceptor(ctx, in, info, handler) } func _ClusterAgent_UnloadCluster_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Cluster) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ClusterAgentServer).UnloadCluster(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.cluster.ClusterAgent/UnloadCluster", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ClusterAgentServer).UnloadCluster(ctx, req.(*Cluster)) } return interceptor(ctx, in, info, handler) } func _ClusterAgent_GetCluster_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Cluster) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ClusterAgentServer).GetCluster(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.cluster.ClusterAgent/GetCluster", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ClusterAgentServer).GetCluster(ctx, req.(*Cluster)) } return interceptor(ctx, in, info, handler) } func _ClusterAgent_GetNodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Cluster) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ClusterAgentServer).GetNodes(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.cluster.ClusterAgent/GetNodes", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ClusterAgentServer).GetNodes(ctx, req.(*Cluster)) } return interceptor(ctx, in, info, handler) } var _ClusterAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "moc.cloudagent.cluster.ClusterAgent", HandlerType: (*ClusterAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "LoadCluster", Handler: _ClusterAgent_LoadCluster_Handler, }, { MethodName: "UnloadCluster", Handler: _ClusterAgent_UnloadCluster_Handler, }, { MethodName: "GetCluster", Handler: _ClusterAgent_GetCluster_Handler, }, { MethodName: "GetNodes", Handler: _ClusterAgent_GetNodes_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "cluster.proto", }
/* Lightweight function to convert a frequency (in Mhz) to a channel number. */ static inline u8 bcm43xx_freq_to_channel_a(int freq) { return ((freq - 5000) / 5); }
/** * Get the address of a worker. * * @param random If true, select a random worker * @param hostname If <code>random</code> is false, select a worker on this host * @return the address of the selected worker, or null if no address could be found * @throws NoWorkerException if there is no available worker * @throws IOException if the connection fails */ public synchronized NetAddress user_getWorker(boolean random, String hostname) throws NoWorkerException, IOException { while (!mIsClosed) { connect(); try { return mClient.user_getWorker(random, hostname); } catch (NoWorkerException e) { throw e; } catch (TException e) { LOG.error(e.getMessage(), e); mConnected = false; } } return null; }
Space News space history and artifacts articles Messages space history discussion forums Sightings worldwide astronaut appearances Resources selected space history documents Websites related space history websites advertisements Challenger debris auction repeats history According to eBay seller 'hook4hand,' this is a recovered piece of space shuttle Challenger's external tank foam. (eBay) UPDATE 10:23 p.m. ET, July 6, 2001 — The seller has responded with the following: "I am really sorry and am writing this email to all of you who responded to my fake eBay auction item. This auction was a joke. The item wasn't authentic, I just listed it as a dare and was going to cancel the auction after a couple of days anyway. I didn't realize that would taken so seriously or that it was in such poor taste. I'm sorry to anyone who was interested in purchasing this item. I would like to extend and apology to all those offended or hurt by my action." If the listing was a hoax, the seller may still be prosecuted for fraud. As of Friday morning (July 6), after the auction was cancelled, NASA said its investigation was ongoing. UPDATE 2:11 a.m. ET, July 6, 2001 — The auction was canceled by the seller at 11:54 p.m. ET Thursday, a little over a day after it was first posted to eBay. Prior to it being pulled, collectSPACE received an e-mail from the seller regarding the item's history: "My father was friends with a man from the navy who was assigned to be on the recovery crew for the shuttle. My father was in Florida, 3 days after the explosion and was a collector of rare music memorablila and he traded a rare item for this piece of the challenger. When the explosion occured, all branches of the military were assigned to shuttle recovery. I have the millitary information and name of the man who found and traded the item, however I did not include it in the auction to protect his privacy, I also did not want to get him in trouble." collectSPACE also spoke with Sam Maxey, the Assistant Inspector General at NASA Headquarters, confirming the space agency would investigate the sale. July 5, 2001 — Like many, eBay seller 'hook4hand' chose to mark Independence Day (July 4) by remembering his United States history. His decision however, to sell debris from the space shuttle Challenger may soon serve to limit his personal freedom. The seller, identified only by his username on the website, described his sale lot as offering "a genuine piece of the Challenger Shuttle collected from Cape Canaveral, FL. by a member of the recovery crew serving there at the time." His description and photograph further identified the item as a 2 by 3/4 inch fragment of insulation recovered from the orange colored external tank. "This is an extrememly rare piece of American history from a tragic event that shocked the nation," hook4hand wrote. The fragment's rarity may be traced to federal law, which prohibits the possession of debris from the space shuttle Challenger wreckage. Violation is subject to a maximum $10,000 fine, 10 years in prison or a combination of both. The auction, which began Wednesday on (July 4) at 5:26 p.m. ET, comes almost one year after another eBay user was tried for a similar sale. Charles Starowesky of Somerset, Ohio, posted a 6 by 6 by 2.5 inch thermal tile to the online auction site on Oct. 28, 1999. He explained he had "pulled [the fragment] from the water of the Atlantic Ocean" as a member of the first U.S. Coast Guard recovery team to respond to the scene. After a NASA Office of Inspector General investigation, Starowesky pled guilty to violating Title 18, Section 641 of the U.S. Code, Theft of Government Property. On August 23, 2000, he was sentenced to two years probation. Soon after hook4hand's lot was posted, an unidentified but concerned collector alerted the space agency. "I have contacted the NASA Inspector General's office," read a post to an online discussion group, "and have left a message on two machines regarding the item, which will undoubtably become an investigation." At the time of publication, the auction remained scheduled to end July 14, with no bids yet for the minimum $1,000 stipulated by the seller. Attempts to reach hook4hand for comment were unsuccessful. © 2019 collectSPACE.com All rights reserved.
import pygame import sys from pygame.locals import * from random import randint import copy import math # Определяем размер экрана и другие свойства FPS = 5 WINDOWWIDTH = 640 WINDOWHEIGHT = 700 boxsize = min(WINDOWWIDTH, WINDOWHEIGHT) // 4 margin = 5 thickness = 0 # Цвета, которые будем использовать WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) DARKGREEN = (0, 155, 0) DARKGRAY = (40, 40, 40) LIGHTSALMON = (255, 160, 122) ORANGE = (221, 118, 7) LIGHTORANGE = (227, 155, 78) CORAL = (255, 127, 80) BLUE = (0, 0, 255) LIGHTBLUE = (0, 0, 150) colorback = (189, 174, 158) colorblank = (205, 193, 180) colorlight = (249, 246, 242) colordark = (119, 110, 101) fontSize = [100, 85, 70, 55, 40] dictcolor1 = { 0: colorblank, 2: (238, 228, 218), 4: (237, 224, 200), 8: (242, 177, 121), 16: (245, 149, 99), 32: (246, 124, 95), 64: (246, 95, 59), 128: (237, 207, 114), 256: (237, 204, 97), 512: (237, 200, 80), 1024: (237, 197, 63), 2048: (237, 194, 46), 4096: (237, 190, 30), 8192: (239, 180, 25)} dictcolor2 = { 2: colordark, 4: colordark, 8: colorlight, 16: colorlight, 32: colorlight, 64: colorlight, 128: colorlight, 256: colorlight, 512: colorlight, 1024: colorlight, 2048: colorlight, 4096: colorlight, 8192: colorlight} BGCOLOR = LIGHTORANGE UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' TABLE = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] SCORE = 0 def main(): global FPSCLOCK, screen, BASICFONT pygame.init() FPSCLOCK = pygame.time.Clock() screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) BASICFONT = pygame.font.Font('freesansbold.ttf', 18) SCORE = 0 pygame.display.set_caption('2048') while True: runGame(TABLE) def randomfill(TABLE): # Поиск 0 на игровом поле и рандомное заполнение flatTABLE = sum(TABLE, []) if 0 not in flatTABLE: return TABLE empty = False w = 0 while not empty: w = randint(0, 15) if TABLE[w // 4][w % 4] == 0: empty = True z = randint(1, 5) if z == 5: TABLE[w // 4][w % 4] = 4 else: TABLE[w // 4][w % 4] = 2 return TABLE def gameOver(TABLE): # Возвращает FALSE, если поле пустое или два поля могут объединиться x = [-1, 0, 1, 0] y = [0, 1, 0, -1] for pi in range(4): for pj in range(4): if TABLE[pi][pj] == 0: return False for point in range(4): if pi + x[point] > -1 and pi + x[point] < 4 and pj + y[point] > -1 and pj + \ y[point] < 4 and TABLE[pi][pj] == TABLE[pi + x[point]][pj + y[point]]: return False return True def showGameOverMessage(): # Отображение экрана GAMEOVER global SCORE titleFont = pygame.font.Font('freesansbold.ttf', 60) titleSurf1 = titleFont.render('GAME OVER', True, WHITE, ORANGE) totalScore = titleFont.render(f'Ваш счёт: {SCORE}', True, WHITE, ORANGE) showMainMenu() while True: screen.fill(BGCOLOR) display_rect = pygame.transform.rotate(titleSurf1, 0) rectangle = display_rect.get_rect() rectangle.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2) display_score_rect = pygame.transform.rotate(totalScore, 0) score_rect = display_score_rect.get_rect() score_rect.center = (WINDOWWIDTH / 2, (WINDOWHEIGHT / 2) + 50) screen.blit(display_rect, rectangle) screen.blit(display_score_rect, score_rect) showMainMenu() pygame.display.update() if checkForKeyPress(): if len(pygame.event.get()) > 0: SCORE = 0 main() FPSCLOCK.tick(FPS) def showMainMenu(): # Отображение меню pressKeySurf = BASICFONT.render('Нажмите любую кнопку чтобы играть снова', True, WHITE) pressKeyRect = pressKeySurf.get_rect() pressKeyRect.topleft = (10, WINDOWHEIGHT - 30) screen.blit(pressKeySurf, pressKeyRect) def checkForKeyPress(): # Проверка нажатия кнопки if len(pygame.event.get(QUIT)) > 0: terminate() keyUpEvents = pygame.event.get(KEYUP) if len(keyUpEvents) == 0: return None if keyUpEvents[0].key == K_ESCAPE: terminate() return keyUpEvents[0].key def show(TABLE): # Отображение игрового поля screen.fill(colorback) for i in range(4): for j in range(4): pygame.draw.rect(screen, dictcolor1[TABLE[i][j]], (j * boxsize + margin, i * boxsize + margin, boxsize - 2 * margin, boxsize - 2 * margin), thickness) if TABLE[i][j] != 0: order = int(math.log10(TABLE[i][j])) myfont = pygame.font.SysFont( "Arial", fontSize[order], bold=True) label = myfont.render("%4s" % (TABLE[i][j]), 1, dictcolor2[TABLE[i][j]]) screen.blit( label, (j * boxsize + 2 * margin, i * boxsize + 9 * margin)) scoreFont = pygame.font.Font('freesansbold.ttf', 30) score = scoreFont.render(f"СЧЁТ: {SCORE}", True, WHITE) scoreRect = score.get_rect() scoreRect.topleft = (10, WINDOWHEIGHT - 40) screen.blit(score, scoreRect) pygame.display.update() def runGame(TABLE): TABLE = randomfill(TABLE) TABLE = randomfill(TABLE) show(TABLE) running = True while True: for event in pygame.event.get(): if event.type == QUIT: print("QUIT") pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if running: desired_key = None if event.key == pygame.K_UP: desired_key = "w" if event.key == pygame.K_DOWN: desired_key = "s" if event.key == pygame.K_LEFT: desired_key = "a" if event.key == pygame.K_RIGHT: desired_key = "d" if desired_key is None: continue new_table = key(desired_key, copy.deepcopy(TABLE)) if new_table != TABLE: TABLE = randomfill(new_table) show(TABLE) if gameOver(TABLE): showGameOverMessage() def key(DIRECTION, TABLE): if DIRECTION == 'w': for pi in range(1, 4): for pj in range(4): if TABLE[pi][pj] != 0: TABLE = moveup(pi, pj, TABLE) elif DIRECTION == 's': for pi in range(2, -1, -1): for pj in range(4): if TABLE[pi][pj] != 0: TABLE = movedown(pi, pj, TABLE) elif DIRECTION == 'a': for pj in range(1, 4): for pi in range(4): if TABLE[pi][pj] != 0: TABLE = moveleft(pi, pj, TABLE) elif DIRECTION == 'd': for pj in range(2, -1, -1): for pi in range(4): if TABLE[pi][pj] != 0: TABLE = moveright(pi, pj, TABLE) return TABLE def movedown(pi, pj, T): global SCORE justcomb = False while pi < 3 and (T[pi + 1][pj] == 0 or (T[pi + 1][pj] == T[pi][pj] and not justcomb)): if T[pi + 1][pj] == 0: T[pi + 1][pj] = T[pi][pj] elif T[pi + 1][pj] == T[pi][pj]: T[pi + 1][pj] += T[pi][pj] SCORE += T[pi + 1][pj] justcomb = True T[pi][pj] = 0 pi += 1 return T def moveleft(pi, pj, T): global SCORE justcomb = False while pj > 0 and (T[pi][pj - 1] == 0 or (T[pi][pj - 1] == T[pi][pj] and not justcomb)): if T[pi][pj - 1] == 0: T[pi][pj - 1] = T[pi][pj] elif T[pi][pj - 1] == T[pi][pj]: T[pi][pj - 1] += T[pi][pj] SCORE += T[pi][pj - 1] justcomb = True T[pi][pj] = 0 pj -= 1 return T def moveright(pi, pj, T): global SCORE justcomb = False while pj < 3 and (T[pi][pj + 1] == 0 or (T[pi][pj + 1] == T[pi][pj] and not justcomb)): if T[pi][pj + 1] == 0: T[pi][pj + 1] = T[pi][pj] elif T[pi][pj + 1] == T[pi][pj]: T[pi][pj + 1] += T[pi][pj] SCORE += T[pi][pj + 1] justcomb = True T[pi][pj] = 0 pj += 1 return T def moveup(pi, pj, T): global SCORE justcomb = False while pi > 0 and (T[pi - 1][pj] == 0 or (T[pi - 1][pj] == T[pi][pj] and not justcomb)): if T[pi - 1][pj] == 0: T[pi - 1][pj] = T[pi][pj] elif T[pi - 1][pj] == T[pi][pj]: T[pi - 1][pj] += T[pi][pj] SCORE += T[pi - 1][pj] justcomb = True T[pi][pj] = 0 pi -= 1 return T def terminate(): pygame.quit() sys.exit() if __name__ == "__main__": main()
export declare type UseTimeoutReturn = [() => boolean | null, () => void, () => void]; export default function useTimeout(ms?: number): UseTimeoutReturn;
/** * Add new method and start editing parameters of new method * @return instance of {@link MethodInfo} */ public MethodInfo addMethod() { MethodInfo method = new MethodInfo(this); this.methods.add(method); return method; }
Main Street Gyros in Seattle was closed Tuesday after three people who ate there were reported to have symptoms of norovirus, health officials said. Main Street Gyros in Seattle has been closed after symptoms of norovirus were linked to the Mediterranean restaurant, health officials said Wednesday. The site at 301 Second Ave. S was closed Tuesday and required to perform a top-down cleaning, said officials with Public Health — Seattle & King County. The move followed reports from two parties, a total of three people, who developed symptoms of norovirus, a highly contagious viral infection. The two groups did not know each other but ate the same food at the restaurant on the same day. None of the people was hospitalized and they won’t be tested, officials said. Food-safety staff met with the restaurant operator Wednesday to detail criteria that must be met before an inspection Thursday morning. Norovirus is the leading cause of disease outbreaks from contaminated food, according to federal health officials. It causes acute gastrointestinal problems, including diarrhea and vomiting. It spreads easily and affects people of all ages.
#include <bits/stdc++.h> using namespace std; #define MAX_N 200005 int n, q; int a[MAX_N]; long long bit[MAX_N]; void Update(int p, int val) { for (int i = p; i <= n; i += i & -i) bit[i] += val; } long long getSum(int p) { long long ret = 0; for (int i = p; i; i -= i & -i) ret += bit[i]; return ret; } int main() { cin.tie(0)->sync_with_stdio(false); // Initialization cin >> n >> q; for (int i = 1; i <= n; i++) { cin >> a[i]; Update(i, a[i]); } // Queries for (int t, p, x, l, r; q--;) { cin >> t; if (t == 1) { cin >> p >> x; Update(p, x - a[p]); a[p] = x; continue; } cin >> l >> r; cout << getSum(r) - getSum(l - 1) << "\n"; } }
Share. You're bacon me crazy. You're bacon me crazy. Little Caesars is working overtime to help sate the bacon cravings of America. In a new creation called the Bacon Wrapped Crust Deep! Deep! Dish Pizza, the chain restaurant has wrapped 3 1/2 feet of bacon around the sides of a deep-dish pizza with pepperoni and bacon bits sprinkled on top. It costs $12 and is the replacement for the Soft Prezel Crust Pizza. With 450 calories, 23 grams of fat, 830 mg of sodium, and 40 mg of cholesterol in one slice, USA Today reports it's being heralded as "a more indulgent offering" from the pizza menu by Little Caesars CEO David Scrivano. "You can always get a plain, cheese pizza or a veggie pizza," he said in response to health concerns. Scrivano admits the pizza could have negative results on the restaurants, including the possibility of order disruptions caused by the amount of time it will take to successfully wrap bacon around the entire crust. He also notes that bacon-wrapped fast food items do not necessarily always travel well. The Bacon Wrapped Crust Deep! Deep! Dish Pizza will be available starting February 23 through April. Exit Theatre Mode In other food-related news, select Kentucky Fried Chicken restaurants in the Philippines have been serving a hot dog wrapped in a chicken breast bun, and two IGN editors recently tried 3D-printed pizza. Photo Credit: Little Caesars Enterprises Cassidee is a freelance writer for various outlets around the web. You can chat with her about all things geeky on Twitter.
// this should upconvert the deprecated VolumeMounts struct func (h *TaskHandler) DesireTask_r1(logger lager.Logger, w http.ResponseWriter, req *http.Request) { var err error logger = logger.Session("desire-task") request := &models.DesireTaskRequest{} response := &models.TaskLifecycleResponse{} defer func() { exitIfUnrecoverable(logger, h.exitChan, response.Error) }() defer func() { writeResponse(w, response) }() err = parseRequest(logger, req, request) if err != nil { logger.Error("failed-parsing-request", err) response.Error = models.ConvertError(err) return } for i, mount := range request.TaskDefinition.VolumeMounts { request.TaskDefinition.VolumeMounts[i] = mount.VersionUpToV1() } err = h.controller.DesireTask(logger, request.TaskDefinition, request.TaskGuid, request.Domain) response.Error = models.ConvertError(err) }
/** * Base class for test cases. */ public abstract class BaseFilterTest { /** * Creates a file select info object for the given file. * * @param file * File to create an info for. * * @return File selct info. */ protected static FileSelectInfo createFSI(final File file) { try { final FileSystemManager fsManager = VFS.getManager(); final FileObject fileObject = fsManager.toFileObject(file); return new FileSelectInfo() { @Override public FileObject getFile() { return fileObject; } @Override public int getDepth() { return 0; } @Override public FileObject getBaseFolder() { try { return fileObject.getParent(); } catch (FileSystemException ex) { throw new RuntimeException(ex); } } }; } catch (FileSystemException ex) { throw new RuntimeException(ex); } } /** * Returns a ZIP file object. * * @param file * File to resolve. * * @return File object. * * @throws FileSystemException * Error resolving the file. */ protected static FileObject getZipFileObject(final File file) throws FileSystemException { final FileSystemManager fsManager = VFS.getManager(); return fsManager.resolveFile("zip:" + file.toURI()); } /** * Asserts that the array contains the given file names. * * @param files * Array to check. * @param filenames * File names to find. */ protected void assertContains(final FileObject[] files, final String... filenames) { for (String filename : filenames) { if (!find(files, filename)) { fail("File '" + filename + "' not found in: " + Arrays.asList(files)); } } } private boolean find(final FileObject[] files, final String filename) { for (FileObject file : files) { final String name = file.getName().getBaseName(); if (name.equals(filename)) { return true; } } return false; } /** * Returns the temporary directory. * * @return java.io.tmpdir */ protected static File getTempDir() { return new File(System.getProperty("java.io.tmpdir")); } /** * Returns a sub directory of the temporary directory. * * @param name * Name of the sub directory. * * @return Sub directory of java.io.tmpdir. */ protected static File getTestDir(final String name) { return new File(getTempDir(), name); } }
<reponame>leegeunhyeok/clow import Context from 'src/core/context'; import Module from 'src/core/common/module'; import Connector from 'src/core/common/connector'; import { G } from '@svgdotjs/svg.js'; export enum DataTypes { NULL = 0, STRING, OBJECT, ANY, PAGE, ELEMENT, } export interface Renderable { g: G | null; create(ctx: Context): this; update(): void; destroy(): void; } export interface Connectable { inConnectRelation: boolean; connectors: Connector[]; initConnection(): void; isConnectedWith(targetModule: Module): boolean; isConnectable(targetModule: Module): boolean; connect(connector: Connector): void; disconnect(connector: Connector): void; } export interface Point { x: number; y: number; }
May Day / After Prague The first series is called Kryry May Day . Kryry is a provincial town about 55 miles west of Prague, population about 2,500. As you will see, May Day is still celebrated here in the Czech Republic but it has turned into (or perhaps re-turned to) a carnival. I was specifically interested in the red, hammer-and-sickle, Soviet flags flying here and there. I thought it an anachronism twenty years after the fall of the Soviet bloc. And no doubt there's a strong element of the carnivalesque in it, and yet, and yet... it all depends on who or what is being carnivalized. I call the second series Prague Pictures, it's self-explanatory.
/** Berechnung Taupunkttemperatur TD(r, T) * \param me Taupunkt data */ static void Calc_TD(struct Tp* me) { float DD = me->r / 100.0 * me->SDD; float v = log10(DD / 6.1078); me->TD = me->b * v / (me->a - v); }
def bazin_fit(self, minpbobs=6, recompute=False): bazin_params = getattr(self, 'bazin_params', None) if bazin_params is not None: if not recompute: return bazin_params bazin_params = {} trigger_time = self.trigger_time filters = self.filters outlc = self.get_lc(recompute=recompute) for i, pb in enumerate(filters): tlc = outlc.get(pb) ttime, tFlux, tFluxErr, tFluxUnred, tFluxErrUnred, tFluxRenorm, tFluxErrRenorm, tphotflag, tzeropoint, tobsId = tlc nobs = len(ttime) if nobs < minpbobs: print(nobs, "Not enough obs") continue pre_trigger = ttime <= trigger_time npre_trigger = len(ttime[pre_trigger]) if npre_trigger <= 3: print(npre_trigger, "Not enough obs before trigger") continue npost_trigger = nobs - npre_trigger if npost_trigger <= 3: print(npost_trigger, "Not enough obs after trigger") continue nd_ind = (tphotflag == constants.NONDETECT_PHOTFLAG) sat_ind = (tphotflag == constants.BAD_PHOTFLAG) good_ind = ~(nd_ind | sat_ind) ngood = len(ttime[good_ind]) if ngood <= 3: print(ngood, "not enough good observations") continue use_ind = ~sat_ind x = ttime[use_ind] - trigger_time y = tFluxUnred[use_ind] dy = tFluxErrUnred[use_ind] limit_A = (1E-6, np.percentile(y, 99)) limit_B = (-2000., 2000.) limit_t0 = (-10., 1.) limit_trise = (1., 50.) limit_tfall = (1., 50.) def _bazin_model(A, B, t0, trise, tfall): f = A*(np.exp(-(x-t0)/tfall)/(1.+np.exp((x-t0)/trise))) + B return f def _bazin_likelihood(A, B, t0, trise, tfall): f = _bazin_model(A, B, t0, trise, tfall) chisq = np.sum(((y - f)**2.)/dy**2.) return chisq m = Minuit(_bazin_likelihood,\ A= np.percentile(y, 75), B=0., t0=0., trise=15., tfall=20.,\ limit_A=limit_A, limit_B=limit_B, limit_t0=limit_t0, limit_trise=limit_trise, limit_tfall=limit_tfall,\ print_level=1) m.migrad() vals = m.values tparams = [] for param in m.parameters: tparams += [m.values[param], m.errors[param],] tparams += [m.fval,] bazin_params[pb] = tparams return bazin_params
def input_mask(self, binstate): return ''.join(compress(binstate, self.mask))
<reponame>jfbloom22/capacitor-site<gh_stars>0 import { State, Component, ComponentInterface, Element, Prop, Host, h, Listen, } from '@stencil/core'; import { importResource } from '../../utils/common'; declare global { interface Window { docsearch: (opts?: {}) => any; } } @Component({ tag: 'docs-search', styleUrl: 'docs-search.scss', }) export class DocsSearch implements ComponentInterface { @Element() el: HTMLElement; @Prop() placeholder = 'Search'; @State() searchLeft: number = 0; @State() input: { el?: HTMLInputElement; isPristine: boolean; isEmpty: boolean; } = { isPristine: true, isEmpty: true, }; private uniqueId = Math.random().toString().replace('.', ''); private algoliaCdn = { js: 'https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js', css: 'https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css', }; componentWillLoad() { const linkEls = document.head.querySelectorAll('link'); const hasAlgoliaCss = Array.from(linkEls).some(link => { return link.href === this.algoliaCdn.css; }); if (!hasAlgoliaCss) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = this.algoliaCdn.css; document.head.append(link); } } componentDidLoad() { importResource( { propertyName: 'docsearch', link: this.algoliaCdn.js }, () => this.setupSearch(), ); } @Listen('resize', { target: 'window' }) handleResize() { requestAnimationFrame(() => { const widths = { body: document.body.offsetWidth, search: 600, }; const searchBarLeft = this.input.el?.getBoundingClientRect()?.left; this.searchLeft = (widths.body - searchBarLeft) / 2 - widths.search + 64; }); } setupSearch() { window.docsearch({ apiKey: '<KEY>', indexName: `capacitorjs`, inputSelector: `#input-${this.uniqueId}`, debug: false, // Set debug to true if you want to inspect the dropdown queryHook: () => { if (this.input.isPristine) { this.input.isPristine = false; this.input.el = this.el.querySelector( `#id-${this.uniqueId} input[name="search"]`, ) as HTMLInputElement; this.input.el.oninput = () => this.handleInput(); this.handleInput(); this.handleResize(); } }, }); } handleInput() { if (this.input.el.value === '') { document.body.classList.remove('no-scroll'); this.input = { ...this.input, isEmpty: true }; } else { this.input = { ...this.input, isEmpty: false }; if (document.body.offsetWidth < 768) { document.body.classList.add('no-scroll'); } } } render() { const { placeholder } = this; return ( <Host id={`id-${this.uniqueId}`} style={{ '--search-left': this.searchLeft.toString().concat('px'), }} > <ion-icon class="search" icon="search" /> <input id={`input-${this.uniqueId}`} name="search" type="search" autocomplete="off" placeholder={placeholder} aria-label={placeholder} required /> <ion-icon style={{ display: this.input.isEmpty ? 'none' : 'block', }} class="close" icon="close" onClick={() => { this.input.el.value = ''; this.input = { ...this.input, isEmpty: true, }; }} /> <site-backdrop visible={!this.input.isEmpty} onClick={() => { this.input.el.value = ''; this.input = { ...this.input, isEmpty: true, }; }} /> </Host> ); } }
The information management with ontology together with N-Gram technology for the deployment in the stakeholders communication using real-time application, a case study of Research and Development Office, Prince of Songkla University Communication is the main factor in acknowledging information for correct implementation. Therefore, it is essential that the information management process suits the stakeholder. In order to increase the speed, accuracy, and precision of information input, we used ontology technique to analyze, classify, and display information according to the need of stakeholders by classifying information into Classes and Sub-classes. News headlines are analyzed according to stakeholders into 4 Classes and 7 Sub-Classes. The details of each part will be the condition in determining the relationship of the need for information. N-Gram technology was used to increase channels and efficiency in the query, and to process and display the results through an Android-based smart phone application. Evaluation of user satisfaction showed that most users were very satisfied (mean = 4.65, standard deviation = 0.657). The technology can be appropriately used in management of public relations information according to the need of the stakeholders.
class Variable: def __init__(self, value:str): self.value=value def evaluation(self): try: a = float(self.value) except Exception as e: print(e) return None else: return a def multiply(self,item): a = Expression("*",self,item) return a def divide(self,item): a = Expression("/",self,item) return a def subtract(self,item): a = Expression("-",self,item) return a def add(self,item): a = Expression("+") a.lhs=self a.rhs=item return a def __str__(self): return self.value class Expression: def __init__(self, operator:str, lhs=None, rhs=None): self.lhs=lhs self.operator=operator self.rhs=rhs def _operation(self, lhs, rhs): if lhs != None and rhs != None: if self.operator == "+": return lhs+rhs elif self.operator == "-": return lhs-rhs elif self.operator == "*": return lhs*rhs elif self.operator == "/": return lhs/rhs else: return None else: return None def evaluation(self): a = self.lhs.evaluation() b = self.rhs.evaluation() #""" if self.operator == "*": if a != None and b == None: if type(self.rhs) == Expression: a1 = self.rhs.lhs.evaluation() b1 = self.rhs.rhs.evaluation() if self.rhs.operator == "*": if a1 != None: new1 = Expression("*",self.lhs,self.rhs.lhs) self.lhs = new1 self.rhs = self.rhs.rhs self.evaluation() elif b1 != None: new1 = Expression("*",self.lhs,self.rhs.rhs) self.lhs = self.rhs.lhs self.rhs = new1 self.evaluation() if self.rhs.operator == "/": if a1 != None: new1 = Expression("*",self.lhs,self.rhs.lhs) self.lhs = new1 self.rhs = self.rhs.rhs self.operator = "/" elif b1 != None: new1 = Expression("/",self.lhs,self.rhs.rhs) self.lhs = self.rhs.lhs self.rhs = new1 self.evaluation() elif a == None and b != None: if type(self.lhs) == Expression: a1 = self.lhs.lhs.evaluation() b1 = self.lhs.rhs.evaluation() if self.lhs.operator == "*": if a1 != None: c = self.lhs.rhs new1 = Expression("*",self.lhs.lhs,self.rhs) self.lhs = new1 self.rhs = c self.evaluation() elif b1 != None: new1 = Expression("*",self.lhs.rhs,self.rhs) self.lhs = self.lhs.lhs self.rhs = new1 self.evaluation() elif self.lhs.operator == "/": if a1 != None: c = self.lhs.rhs new1 = Expression("*",self.lhs.lhs,self.rhs) self.lhs = new1 self.rhs = c self.operator = "/" self.evaluation() elif b1 != None: new1 = Expression("/",self.rhs,self.lhs.rhs) self.lhs = self.lhs.lhs self.rhs = new1 self.evaluation() elif self.operator == "/": if a != None and b == None: pass elif a == None and b != None: pass #""" return self._operation(a,b) def toString(self): view = str() if self.evaluation() == None: if type(self.lhs) == Variable: view = self.lhs.value elif type(self.lhs) == Expression: view = f"({self.lhs.toString()})" else: return None view += self.operator if type(self.rhs) == Variable: view += self.rhs.value elif type(self.rhs) == Expression: view += f"({self.rhs.toString()})" else: return None else: view = str(self.evaluation()) return view def __str__(self): return self.toString() class Equation: def __init__(self, asignmentOperator="=", lhs=None, rhs=None): self.lhs=lhs self.asignmentOperator=asignmentOperator self.rhs=rhs def toString(self): view = str() if type(self.lhs) == Variable: view = self.lhs.value elif type(self.lhs) == Expression: view = f"{self.lhs.toString()}" else: return None view += self.asignmentOperator if type(self.rhs) == Variable: view += self.rhs.value elif type(self.lhs) == Expression: view += f"{self.rhs.toString()}" else: return None return view def __str__(self): return self.toString()
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); String[] data = reader.readLine().split("\\s"); Circle a = new Circle(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); data = reader.readLine().split("\\s"); Circle b = new Circle(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); data = reader.readLine().split("\\s"); Circle c = new Circle(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); Point ans = getCenter(a, b, c); if (ans != null) { writer.printf("%.5f %.5f", ans.x, ans.y); } writer.close(); } public static Point getCenter(Circle a, Circle b, Circle c) { double totalX = (a.x + b.x + c.x) / 3.0; double totalY = (a.y + b.y + c.y) / 3.0; double angel = angel(totalX, totalY, a, b, c); double step = 1.0; while (step > 1e-7) { boolean stop = false; for (int i = 0; i < 4; i++) { double newX = totalX + step * offset(i, 0); double newY = totalY + step * offset(i, 1); double newAngel = angel(newX, newY, a, b, c); if (newAngel < angel) { angel = newAngel; totalX = newX; totalY = newY; stop = true; } } if (!stop) step *= 0.8; } if (angel < 1e-6) { return new Point(totalX, totalY); } return null; } private static int offset(int i, int j) { switch (i) { case 0: return j==0 ? 1 : 0; case 1: return j==0 ? -1 : 0; case 2: return j==0 ? 0 : 1; case 3: return j==0 ? 0 : -1; } return 0; } private static double angel(double x, double y, Circle a, Circle b, Circle c) { double at = Math.sqrt(((a.x - x) * (a.x - x)) + ((a.y - y) * (a.y - y))) / a.r; double bt = Math.sqrt(((b.x - x) * (b.x - x)) + ((b.y - y) * (b.y - y))) / b.r; double ct = Math.sqrt(((c.x - x) * (c.x - x)) + ((c.y - y) * (c.y - y))) / c.r; double answer = (at - bt) * (at - bt); answer += (bt - ct) * (bt - ct); answer += (ct - at) * (ct - at); return answer; } static class Circle { int x; int y; int r; Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } } static class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } } }
#include "stdafx.h" #include "DecodeHints.h" #include "GenericLuminanceSource.h" #include "HybridBinarizer.h" #include "MultiFormatReader.h" #include "Result.h" #include "holojs/private/error-handling.h" #include "include/holojs/windows/qr-scanner.h" #include <collection.h> #include <functional> #include <ppltasks.h> #include <robuffer.h> #include <windows.storage.streams.h> #include <wrl.h> using namespace concurrency; using namespace HoloJs::Platforms::Win32; using namespace std; using namespace Windows::Graphics::Imaging; using namespace Windows::Media::Capture; using namespace Windows::Media::MediaProperties; using namespace Windows::Storage::Streams; class scope_exit { public: scope_exit(const std::function<void()>& func) : m_func(func) {} void dismiss() {} virtual ~scope_exit() { try { if (!m_isDismissed) { m_func(); } } catch (...) { } } private: bool m_isDismissed = false; std::function<void()> m_func; }; ZXing::Result tryDecodeFromBuffer(unsigned int width, unsigned int height, unsigned char* buffer, int bpp, int redIndex, int greenIndex, int blueIndex) { auto luminance = make_shared<ZXing::GenericLuminanceSource>( width, height, buffer, bpp * width, bpp, redIndex, greenIndex, blueIndex); auto binarizer = make_unique<ZXing::HybridBinarizer>(luminance); auto decodeHints = ZXing::DecodeHints(); vector<ZXing::BarcodeFormat> formats = {ZXing::BarcodeFormat::QR_CODE}; decodeHints.setPossibleFormats(formats); auto reader = make_unique<ZXing::MultiFormatReader>(decodeHints); return reader->read(*binarizer.get()); } HRESULT QrScanner::tryDecode() { RETURN_IF_TRUE(m_isBusy); m_isBusy = true; auto mediaCapture = ref new MediaCapture(); auto initializeTask = create_task(mediaCapture->InitializeAsync()); auto capturedMediaCapture = Platform::Agile<MediaCapture>(mediaCapture); initializeTask.then([this, capturedMediaCapture](task<void> previousTask) { auto autoClearIsBusy = scope_exit([this]() { m_isBusy = false; }); auto autoFireFailedCallback = scope_exit([this]() { m_callback(false, L""); }); try { previousTask.get(); } catch (...) { return; } auto captureFormat = getEncodingProperties(capturedMediaCapture); EXIT_IF_TRUE(captureFormat == nullptr); const auto height = captureFormat->Height; const auto width = captureFormat->Width; auto captureStream = ref new InMemoryRandomAccessStream(); IBuffer ^ imageBuffer = nullptr; for (int i = 0; i < 10; i++) { captureStream->Seek(0); // take photo auto captureTask = create_task(capturedMediaCapture->CapturePhotoToStreamAsync(captureFormat, captureStream)); try { captureTask.wait(); } catch (...) { return; } unsigned char* imageNativeBuffer; EXIT_IF_FAILED(readCaptureStreamAndGetBytes(captureStream, &imageBuffer, &imageNativeBuffer)); auto result = tryDecodeFromBuffer(width, height, imageNativeBuffer, m_pixelFormatBpp, m_pixelFormatRedIndex, m_pixelFormatGreenIndex, m_pixelFormatBlueIndex); if (result.isValid()) { autoFireFailedCallback.dismiss(); m_callback(true, result.text()); break; } } }); return S_OK; } ImageEncodingProperties ^ QrScanner::getEncodingProperties(Platform::Agile<MediaCapture> mediaCapture) { auto captureFormat = ImageEncodingProperties::CreateUncompressed(m_pixelFormat); bool foundImageEncoding = false; auto streamProperties = mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(MediaStreamType::Photo); for (unsigned int i = 0; i < streamProperties->Size; i++) { auto property = streamProperties->GetAt(i); if (_wcsicmp(property->Type->Data(), L"Image") == 0) { auto videoProperties = safe_cast<ImageEncodingProperties ^>(property); if (videoProperties->Height * videoProperties->Width > captureFormat->Height * captureFormat->Width) { captureFormat->Height = videoProperties->Height; captureFormat->Width = videoProperties->Width; foundImageEncoding = true; } } } return foundImageEncoding ? captureFormat : nullptr; } HRESULT QrScanner::readCaptureStreamAndGetBytes(InMemoryRandomAccessStream ^ captureStream, IBuffer ^* intermediateBuffer, unsigned char** captureBytes) { captureStream->Seek(0); RETURN_IF_TRUE(captureStream->Size > UINT32_MAX); if (*intermediateBuffer == nullptr || (*intermediateBuffer)->Capacity < captureStream->Size) { *intermediateBuffer = ref new Buffer(static_cast<unsigned int>(captureStream->Size)); } auto readAsync = captureStream->ReadAsync( *intermediateBuffer, static_cast<unsigned int>(captureStream->Size), InputStreamOptions::None); create_task(readAsync).wait(); auto buffer = readAsync->GetResults(); Microsoft::WRL::ComPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess; RETURN_IF_FAILED( reinterpret_cast<IInspectable*>(*intermediateBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess))); RETURN_IF_FAILED(bufferByteAccess->Buffer(captureBytes)); return S_OK; }
/** * Compare the two compound curves for equality * * @param expected * @param actual * @parma delta */ private static void compareCompoundCurve(CompoundCurve expected, CompoundCurve actual, double delta) { compareBaseGeometryAttributes(expected, actual); TestCase.assertEquals(expected.numLineStrings(), actual.numLineStrings()); for (int i = 0; i < expected.numLineStrings(); i++) { compareLineString(expected.getLineStrings().get(i), actual .getLineStrings().get(i), delta); } }
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_TASK_INDEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.StringUtil; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.person.Person; import seedu.address.model.task.Task; /** * Marks task(s) identified using its displayed index in the task list as not done. */ public class UndoCommand extends Command { public static final String COMMAND_WORD = "undotask"; public static final String MESSAGE_SUCCESS = "Marked %1$d %2$s of %3$s as not done."; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks the task, specified by the TASKINDEX, from person " + "identified by the index number used in the displayed person list as not done.\n" + "Parameters: INDEX (must be a positive integer) " + PREFIX_TASK_INDEX + " TaskIndex (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1 " + PREFIX_TASK_INDEX + " 2"; public static final String DESCRIPTION = "Marks the task(s), specified by the TASK_INDEX, " + "from person specified by the INDEX as not done"; private final Index targetPersonIndex; private final List<Index> targetTaskIndexes; /** * Constructor for a DoneCommand to mark a task of a person as done. * * @param targetPersonIndex The Index of the target person. * @param targetTaskIndexes The Index of the target Task that belongs to target person. */ public UndoCommand(Index targetPersonIndex, List<Index> targetTaskIndexes) { requireAllNonNull(targetPersonIndex, targetTaskIndexes); this.targetPersonIndex = targetPersonIndex; this.targetTaskIndexes = targetTaskIndexes; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Person> lastShownList = model.getFilteredPersonList(); if (targetPersonIndex.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } Person personToEdit = lastShownList.get(targetPersonIndex.getZeroBased()); List<Task> taskListToModify = getTaskListToModify(model, personToEdit); assert taskListToModify != null : "view all task list functionality not implemented correctly!"; //Make new copy for defensive programming. List<Task> tasks = new ArrayList<>(personToEdit.getTasks()); List<Index> copyOfIndexList = new ArrayList<>(targetTaskIndexes); copyOfIndexList.sort(Collections.reverseOrder()); checkTargetIndexesValidity(personToEdit, taskListToModify); List<Task> targetTasks = extractTargetTasks(taskListToModify, copyOfIndexList); int notDone = markTargetTasksAsNotDone(tasks, targetTasks); Person editedPerson = createEditedPersonWithUpdatedTasks(personToEdit, tasks); model.setPerson(personToEdit, editedPerson); return generateWriteCommandResult(notDone, editedPerson); } public String getCommand() { return COMMAND_WORD; } public String getDescription() { return DESCRIPTION; } private CommandResult generateWriteCommandResult(int alreadyDone, Person editedPerson) { CommandResult commandResult = new CommandResult( generateSuccessMessage(editedPerson, targetTaskIndexes.size(), alreadyDone)); commandResult.setWriteCommand(); return commandResult; } private Person createEditedPersonWithUpdatedTasks(Person personToEdit, List<Task> tasks) { return new Person( personToEdit.getName(), personToEdit.getPhone(), personToEdit.getEmail(), personToEdit.getAddress(), personToEdit.getTags(), tasks, personToEdit.getDescription(), personToEdit.getImportance()); } private int markTargetTasksAsNotDone(List<Task> tasks, List<Task> targetTasks) { int notDone = 0; for (Task targetTask : targetTasks) { for (int i = 0; i < tasks.size(); i++) { if (!(tasks.get(i) == targetTask)) { continue; } if (!tasks.get(i).getDone()) { notDone++; } else { Task editedTask = new Task(tasks.get(i).getTaskName(), tasks.get(i).getDate(), tasks.get(i).getTime(), tasks.get(i).getVenue()); editedTask.updateDueDate(); editedTask.setNotDone(); tasks.set(i, editedTask); } } } return notDone; } private void checkTargetIndexesValidity(Person personToEdit, List<Task> tasks) throws CommandException { for (Index targetTaskIndex : targetTaskIndexes) { if (targetTaskIndex.getZeroBased() >= tasks.size()) { throw new CommandException(String.format(Messages.MESSAGE_INVALID_TASK, personToEdit.getName())); } } } private List<Task> extractTargetTasks(List<Task> taskList, List<Index> targetTaskIndexes) { List<Task> targetTasks = new ArrayList<>(); for (Index targetIndex : targetTaskIndexes) { targetTasks.add(taskList.get(targetIndex.getZeroBased())); } return targetTasks; } /** * Generates a command execution success message based on * the task removed. * {@code personToEdit}. */ private String generateSuccessMessage(Person personToEdit, int amount, int notDone) { int tasksMarked = amount - notDone; String taskOrTasks = StringUtil.singularOrPlural("task", tasksMarked); String taskOrTasksNotMarked = StringUtil.singularOrPlural("task", notDone); String markedTasks = String.format(MESSAGE_SUCCESS, tasksMarked, taskOrTasks, personToEdit.getName()); String notMarkedTasks = String.format("%1$d %2$s are already not done.", notDone, taskOrTasksNotMarked); return notDone == 0 ? markedTasks : markedTasks + "\n" + notMarkedTasks; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UndoCommand // instanceof handles nulls && targetPersonIndex.equals(((UndoCommand) other).targetPersonIndex) && targetTaskIndexes.equals(((UndoCommand) other).targetTaskIndexes)); // state check } }
/** * @module object */ /** * 获取嵌套对象某一属性值 * @param {Object} obj 需要获取属性的对象 * @param {String[]} keys 键名数组 * @return {Any} 属性值 */ export function optionalGet(obj: any, [...keys]: Array<string | number>): any { let result = obj; for (let i = 0; i < keys.length && result !== undefined; i++) { const key = keys[i]; result = result[key]; } return result; } /** * 嵌套设置对象某一属性值,在访问过程中如果遇到属性不存在的情况时会创建一空对象 * @param {Object} obj 设置的对象 * @param {String[]} keys 键名数组 * @param {Any} value 设置的值 * @return {Any} 属性值 */ export function optionalSet(obj: any, [...keys]: Array<string | number>, value: any): any { const lastKey = keys.pop(); keys.reduce((prev, key) => { if (!prev[key]) { prev[key] = {}; } return prev[key]; }, obj)[lastKey] = value; return value; } /** * 浅对比两个对象 * @param {Object} objA 对象A * @param {Object} objB 对象B * @return {Boolean} 两对象是否浅层相等 */ export function shallowEqual(objA: any, objB: any): boolean { return ( Object.values(objA).length === Object.values(objB).length && Object.entries(objA).every(([key, value]) => objB[key] === value) ); } /** * 将键值对数组转为对象时,传入 reduce 方法中的 reducer * @param {Object|undefined} prev 前一次累计对象 * @param {Array} param1 当前键值对 * @param {String} param1.0 键 * @param {Any} param1.1 值 * @return {Object} 累计对象 */ export function unentriesReducer<T>( prev: Record<string, T>, [key, value]: [string, T], ): Record<string, T> { prev[key] = value; return prev; } /** * 将键值对数组转为对象,Object.entries 的反操作 * @param {Array} array 键值对数组 * @return {Object} 对象 */ export function unentries<T>(array: Array<[string, T]>): Record<string, T> { return array.reduce<Record<string, T>>(unentriesReducer, {}); }
# 写経AC N,M = map(int, input().split()) edge = [[] for _ in range(N)] for _ in range(M): a,b = map(int, input().split()) edge[a-1].append(b-1) edge[b-1].append(a-1) Q = int(input()) VDC = [[int(i) for i in input().split()] for _ in range(Q)] for i in range(Q): VDC[i][0] -= 1 color = [0] * N # visited[v][d]: 頂点vから距離d以下は塗装済みか visited = [[False] * 11 for _ in range(N)] for v,d,c in reversed(VDC): if visited[v][d]: # 既に塗装済み continue if color[v] == 0: color[v] = c for dist in range(d + 1): # 距離d以下は塗装済み visited[v][dist] = True q = [v] for t in range(d - 1, -1, -1): qq = [] for v in q: for w in edge[v]: if visited[w][t]: continue for dist in range(t + 1): visited[w][dist] = True if color[w] == 0: color[w] = c qq.append(w) q = qq print(*color, sep="\n")
/** * fast_idct - Figure A.3.3 IDCT (informative) on A-5 of the ISO DIS * 10918-1. Requires and Guidelines. This is a fast IDCT, it much more * effecient and only inaccurate at about 1/1000th of a percent of values * analyzed. Cannot be static because initMatrix must run before any * fast_idct values can be computed. * * @param input * @return */ public short[][] fast_idct(short[][] input) { short output[][] = new short[8][8]; short temp[][] = new short[8][8]; short temp1; int i, j, k; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { temp[i][j] = 0; for (k = 0; k < 8; k++) { temp[i][j] += input[i][k] * c[k][j]; } } } for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { temp1 = 0; for (k = 0; k < 8; k++) temp1 += cT[i][k] * temp[k][j]; temp1 += 128.0; if (temp1 < 0) output[i][j] = 0; else if (temp1 > 255) output[i][j] = 255; else output[i][j] = (short) Math.round(temp1); } } return output; }
import sys input = sys.stdin.readline ''' ''' from math import ceil a1,a2,a3 = map(int, input().split()) b1,b2,b3 = map(int, input().split()) n = int(input()) shelves_cup = ceil((a1+a2+a3) / 5) shelves_medal = ceil((b1+b2+b3) / 10) print("YES" if shelves_cup+shelves_medal <= n else "NO")
#Calculate maximum no of dominos(2*1) that can be put to cover the rectangular box of given dimension m, n = map(int, raw_input().split(" ")) area = m*n if (area % 2 == 0): print area/2 else: print (area-1)/2
/** * Handles reminder timers. * @author Alex811 */ public class ReminderTimer { private static final Map<UUID, ReminderTimer> active = Collections.synchronizedMap(new HashMap<>()); private final UUID id; private final Timer timer; private final int seconds; private final String name; private long start = -1; /** * Timer constructor. Doesn't start the timer, you need to do that manually. * @param seconds seconds to wait before notifying that the time's up * @param name timer title * @see #start() * @see ReminderTimer#startNew(int, String) */ public ReminderTimer(int seconds, String name) { this.id = UUID.randomUUID(); this.timer = new Timer(true); this.seconds = seconds; this.name = name; } /** * Starts timer thread, stores timer as {@link #active} & displays appropriate message. */ public void start() { active.put(id, this); start = getCurrSecs(); timer.schedule(new Task(), seconds * 1000L); ModConfig.Reminder settings = ModConfig.getInstance().reminder; Message.auto(settings.msgTypeStart, () -> TextUtil.buildText( Message.CHAT_PRE_INFO, TextUtil.getWithFormat( Strings.isNullOrEmpty(name) ? new TranslatableText("msg.notifmod.reminder.start.long.unnamed", TextUtil.getWithFormat(NumUtil.secToHMSString(seconds), Formatting.YELLOW)) : new TranslatableText("msg.notifmod.reminder.start.long.named", TextUtil.getWithFormat(NumUtil.secToHMSString(seconds), Formatting.YELLOW), TextUtil.getWithFormat(name, Formatting.YELLOW)), Formatting.AQUA)), () -> TextUtil.getWithFormat(new TranslatableText("msg.notifmod.reminder.start.short"), Formatting.AQUA) ); } /** * Makes new timer & runs {@link #start()} on it. * @param seconds seconds to wait before notifying that the time's up * @param name timer title */ public static void startNew(int seconds, String name) { new ReminderTimer(seconds, name).start(); } /** * Stops timers that haven't finished, removes from the {@link #active} list. */ public void kill() { timer.cancel(); active.remove(id); } /** * Runs {@link #kill()} on all {@link #active} timers. */ public static void killAll() { List.copyOf(active.values()).forEach(ReminderTimer::kill); } /** * Returns collection of all active timers. * @return active timers */ public static Collection<ReminderTimer> getActive() { return active.values(); } public String getName() { return name; } /** * Returns remaining seconds of a running timer. * If finished, it'll be negative. * If it never started, it'll be -1. * @return remaining seconds or -1 if it never ran */ public int getRemaining() { return start >= 0 ? (int) (start + seconds - getCurrSecs()) : -1; } public boolean isActive(){ return active.containsKey(id); } public boolean hasName(){ return !name.isEmpty(); } /** * Returns current time in seconds. * @see System#currentTimeMillis() * @return current time in seconds */ private long getCurrSecs() { return Math.floorDiv(System.currentTimeMillis(), 1000); } /** * A {@link TimerTask} that notifies the player when the timer finishes and removes the timer from the {@link #active} list. */ private class Task extends TimerTask { @Override public void run() { ModConfig.Reminder settings = ModConfig.getInstance().reminder; Message.auto(settings.msgTypeDone, () -> TextUtil.buildText( Message.CHAT_PRE_INFO, TextUtil.getWithFormat( Strings.isNullOrEmpty(name) ? new TranslatableText("msg.notifmod.reminder.done.unnamed") : new TranslatableText("msg.notifmod.reminder.done.named", TextUtil.getWithFormat(name, Formatting.YELLOW)), Formatting.GREEN)), () -> Strings.isNullOrEmpty(name) ? TextUtil.getWithFormat(new TranslatableText("msg.notifmod.reminder.done.unnamed"), Formatting.GREEN) : TextUtil.getWithFormat(name, Formatting.GREEN) ); if (settings.soundEnabled) settings.soundSequence.play(settings.volume); active.remove(id); } } }
<filename>react-app/src/Redux/index.ts<gh_stars>0 import { createSlice, PayloadAction, createStore, combineReducers } from '@reduxjs/toolkit' interface CounterState { value: number } const initialState = { value: 0 } as CounterState const counter = createSlice({ name: 'counter', initialState, reducers: { increment(state) { state.value++ }, decrement(state) { state.value-- }, incrementByAmount(state, action: PayloadAction<number>) { state.value += action.payload }, }, }) const reducer = combineReducers({ counter: counter.reducer, }) const store = createStore(reducer) export const { increment, decrement, incrementByAmount } = counter.actions export default store;
<gh_stars>1-10 from airflow.plugins_manager import AirflowPlugin from gotowebinar_plugin.hooks.gotowebinar_hook import GoToWebinarHook from gotowebinar_plugin.operators.gotowebinar_to_redshift_operator import GoToWebinarToRedshiftOperator class GoToWebinarPlugin(AirflowPlugin): name = "gotowebinar_plugin" operators = [GoToWebinarToRedshiftOperator] hooks = [GoToWebinarHook] # Leave in for explicitness even if not using executors = [] macros = [] admin_views = [] flask_blueprints = [] menu_links = []
/** * Details of a signed certificate timestamp (SCT). */ public static class SignedCertificateTimestamp { /** * Validation status. */ public String status; /** * Origin. */ public String origin; /** * Log name / description. */ public String logDescription; /** * Log ID. */ public String logId; /** * Issuance date. */ public Double timestamp; /** * Hash algorithm. */ public String hashAlgorithm; /** * Signature algorithm. */ public String signatureAlgorithm; /** * Signature data. */ public String signatureData; public String toString() { return "SignedCertificateTimestamp{status=" + status + ", origin=" + origin + ", logDescription=" + logDescription + ", logId=" + logId + ", timestamp=" + timestamp + ", hashAlgorithm=" + hashAlgorithm + ", signatureAlgorithm=" + signatureAlgorithm + ", signatureData=" + signatureData + "}"; } }
/** * Get sub-account details * * This endpoint will provide the details of specified sub-account organization * * @throws Exception * if the Api call fails */ @Test public void corporateSubAccountIdGetTest() throws Exception { Long id = null; SubAccountDetailsResponse response = api.corporateSubAccountIdGet(id); }
package com.google.common.primitives; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Preconditions; import java.util.Comparator; @GwtCompatible @Beta public final class UnsignedInts { static final long INT_MASK = 4294967295L; enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedInts.compare(left[i], right[i]); } } return left.length - right.length; } } private UnsignedInts() { } static int flip(int value) { return Integer.MIN_VALUE ^ value; } public static int compare(int a, int b) { return Ints.compare(flip(a), flip(b)); } public static long toLong(int value) { return ((long) value) & INT_MASK; } public static int min(int... array) { boolean z; if (array.length > 0) { z = true; } else { z = false; } Preconditions.checkArgument(z); int min = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } public static int max(int... array) { boolean z; if (array.length > 0) { z = true; } else { z = false; } Preconditions.checkArgument(z); int max = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } public static String join(String separator, int... array) { Preconditions.checkNotNull(separator); if (array.length == 0) { return ""; } StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toString(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } public static int divide(int dividend, int divisor) { return (int) (toLong(dividend) / toLong(divisor)); } public static int remainder(int dividend, int divisor) { return (int) (toLong(dividend) % toLong(divisor)); } public static int decode(String stringValue) { ParseRequest request = ParseRequest.fromString(stringValue); try { return parseUnsignedInt(request.rawValue, request.radix); } catch (NumberFormatException e) { String str = "Error parsing value: "; String valueOf = String.valueOf(stringValue); NumberFormatException decodeException = new NumberFormatException(valueOf.length() != 0 ? str.concat(valueOf) : new String(str)); decodeException.initCause(e); throw decodeException; } } public static int parseUnsignedInt(String s) { return parseUnsignedInt(s, 10); } public static int parseUnsignedInt(String string, int radix) { Preconditions.checkNotNull(string); long result = Long.parseLong(string, radix); if ((INT_MASK & result) == result) { return (int) result; } String valueOf = String.valueOf(String.valueOf(string)); throw new NumberFormatException(new StringBuilder(valueOf.length() + 69).append("Input ").append(valueOf).append(" in base ").append(radix).append(" is not in the range of an unsigned integer").toString()); } public static String toString(int x) { return toString(x, 10); } public static String toString(int x, int radix) { return Long.toString(((long) x) & INT_MASK, radix); } }
Plane Symmetric Domain Wall in Lyra Geometry In this paper general solutions are found for domain walls in Lyra geometry in the plane symmetric spacetime metric given by Taub. Expressions for the energy density and pressure of domain walls are derived in both cases of uniform and time varying displacement field $\beta$. It is also shown that the results obtained by Rahaman et al are particular case of our solutions. Finally, the geodesic equations and acceleration of the test particle are discussed. Introduction The study of topological defects in cosmology relevant to structure formation and evolution of the universe has been widely studied . Of all the topological defects domain walls are deceptively simple to study. It is established that absolutely stable domain walls that have a mass per unit area greater than 4 × 10 −3 g/cm 2 are cosmological disaster . However, unstable (but perhaps long-lived) domain walls could have been present in the early universe . Furthermore, light domain walls might even be present today . In either case domain walls may play an important role in the universe. Domain walls form when a discrete symmetry is spontaneously broken . In simplest models, symmetry breaking is accomplished by a real scalar field φ whose vacuum manifold is disconnected. . After symmetry breaking, different regions of the universe can settle into different parts of the vacuum with domain walls forming the boundaries between these regions. The stress energy for a static, plane-symmetric domain wall consists of a positive surface energy density and a surface tension equal in magnitude to the surface energy . We note, however that this analysis neglects the effects of gravity . Locally, the stress energy for a wall of arbitrary shape is similar to that of a plane-symmetric wall having both surface energy density and surface tension. Closed-surface domain walls collapse due to their surface tension. However, the details of the collapse for a wall with arbitrary shape and finite thickness are largely unknown. The spacetime of cosmological domain walls has now been a subject of interest for more than a decade since the work of Vilenkin and Ipser and Sikivie who use Israel's thin wall formalism to compute the gravitational field of an infinitesimally thin planar domain wall. After the original work by Vilenkin, Ipser and Sikivie for thin walls, attempts focused on trying to find a perturbative expansion in the wall thickness . With the proposition by Hill, Schramn and Fry of a late phase transition with thick domain walls, there was some effort in finding exact thick solution . Recently, Bonjour et al considered gravitating thick domain wall solutions with planar and reflection symmetry in the Goldstone model. Bonjour et al also investigated the spacetime of a thick gravitational domain wall for a general potential V (φ). Jensen and Soleng have studied anisotropic domain walls where the solution has naked singularities and the generic solution is unstable to Hawking decay. The universe is spherically symmetric and the matter distribution in it is on the whole isotropic and homogeneous. But during the early stages of evolution, it is unlikely that it could have had such a smoothed out picture. Hence we consider plane symmetry which provides an opportunity for the study of inhomogeneity. Most studies in cosmology involve a perfect fluid. Large entropy per baryon and the remarkable degree of isotropy of the cosmic microwave background radiation, suggest that we should analyse dissipative effects in cosmology. Further, there are several processes which are expected to give rise to viscous effect. These are the decoupling of neutrinos during the radiation era and the recombination era , decay of massive super string modes into massless modes , gravitational string production and particle creation effect in grand unification era . It is known that the introduction of bulk viscosity can avoid the big bang singularity. Thus, we should consider the presence of a material distribution other than a perfect fluid to have realistic cosmological models (see Grøn for a review on cosmological models with bulk viscosity). To study thick domain walls, one can study the field equations as well as equations of the domain walls treated as the self interacting scalar field. A thick domain wall can be viewed as a soliton-like solution of the scalar field equation coupled with gravity. In order to determine the gravitational field one has to solve Einstein's equation with an energy momentum tensor T µν describing a scalar field φ with self-interactions contained in a potential V (φ) . In another approach to study the phenomenon one has to assume the energy momentum tensor in the form where ρ is the energy density of the wall, p is the pressure in the direction normal to the plane of the wall and W i is a unit space like vector in the same direction . In 1951 Lyra proposed a modification of Riemannian geometry by introducing a gauge function into the structureless manifold, as a result of which the cosmological constant arises naturally from geometry. This bears a remarkable resemblance to Weyl's geometry . But in Lyra's geometry, unlike Weyl's, the connection is metric preserving as in Riemannian; in other words, length transfers are integrable. Lyra also introduced the notion of a gauge and in the "normal" gauge the curvature scalar is identical to that of Weyl. In subsequent investigations Sen , Sen and Dunn proposed a new scalar-tensor theory of gravitation and constructed an analog of the Einstein field equations based on Lyra's geometry. It is, thus, possible to construct a geometrised theory of gravitation and electromagnetism along the lines of Weyl's "unified" field theory without inconvenience of nonintegrability length transfer. Halford has pointed out that the constant vector displacement field φ i in Lyra's geometry plays the role of cosmological constant Λ in the normal general relativistic treatment. It is shown by Halford that the scalar-tensor treatment based on Lyra's geometry predicts the same effects, within observational limits as the Einstein's theory. Several investigators viz. Sen and Vanstone , Bhamra , Karade and Borikar , Kalyanshetti and Wagmode , Reddy and Innaiah , Beesham , Reddy and Venkateswarlu , Soleng , Singh and Singh , Singh and Desikan , Pradhan and Vishwakarma , Pradhan et al have studied cosmological models based on Lyra's manifold with a constant displacement field vector. However, this restriction of the displacement field to be constant is merely one of convenience and there is no a priori reason for it. Soleng has pointed out that the cosmologies based on Lyra's manifold with constant gauge vector φ will either include a creation field and be equal to Hoyle's creation field cosmology − or contain a special vacuum field which together with the gauge vector term may be considered as a cosmological term. In the latter case the solutions are equal to the general relativistic cosmologies with a cosmological term. In this paper we obtain all possible general solutions for domain wall in Lyra geometry in the plane symmetric spacetime metric given by Taub. Expressions for the energy density and pressure of domain walls are obtained in both cases of uniform and time varying displacement field β. We have also shown that the result obtained by Rahaman et al is a special case of our solutions. Field Equations In this section we shall consider the field equations, in normal gauge for Lyra's manifold, obtained by Sen as for study domain walls. The energy momentum tensor T ij in comoving coordinates for thick domain walls take the form and displacement vector φ i is defined by φ i = (0, 0, 0, β), where β may be considered constant as well as function of time coordinate like cosmological constant in Einstein's theory of gravitation. We consider the most general plane symmetric spacetime metric suggested by Taub where A and B are functions of t and z. Using equation (4) the field equations (3) for the metric (5) reduce to In order to solve the above set of field equations we assume the separable form of the metric coefficients as follows From Eqs. (9) and (10), we obtain where m is considered as separation constant Eq. (11) yields the solution Again, subtracting Eq. (8) from Eq. (6) and using Eq. (10), we obtain where k is another separation constant. With the help of Eqs (12) and (13), Eq. (14) may be written as Solutions of the field equations In this section we shall obtain exact solutions for thick domain walls in different cases. Using the substitution u = e B 1 and a = k 1−m , Eq. (15) takes the form which has solution where c 1 and c 2 are integrating constants. Eq. (18) represent the complete solution of the differential Eq. (17). It may be noted that Rahaman et al have obtained a particular solution for the case a < 0. Their solution can be obtained from Eq. (18) by taking c 1 = 0 and c 2 = 2 for the case a < 0. Eq. (16) may be written as Now we shall consider uniform and time varying displacement field β separately. Case I : Uniform displacement field (β = β 0 , constant) where . Again, it can be easily seen that Eq. (20) possesses the solution wherec 1 andc 2 are integrating constants. Hence the metric coefficients have the explicit forms as when a < 0, b < 0 With the help of Eqs. (22) and (23), the energy density and pressure can be obtained from Eqs. (6) and (7) 32πρ = Using the aforesaid power law relation between time coordinate and displacement field, Eq. (19) may be written as where Now, it is difficult to find a general solution of Eq. (26) and hence we consider a particular case of physical interest. It is believed that β 2 has similar behaviour as the cosmological constant which decreases during expansion of universe. Several authors − have considered the relation β ∼ 1 t for study of cosmological models in different context. Eq. (28) yields the general solution where where c 3 and c 4 are integrating constants. Hence the metric coefficients have the explicit forms as when a < 0 With the help of Eq. (31) and (34), the energy density and pressure can be obtained from Eqs. (6) and (7) 32πρ = From the above results in both cases it is evident that at any instant the domain wall density ρ and pressure p 1 in the perpendicular direction decreases on both sides of the wall away from the symmetry plane and both vanish as Z −→ ±∞. The space times in both cases are reflection symmetry with respect to the wall. All these properties are very much expected for a domain wall. Study of Geodesics The trajectory of the test particle x i {t(λ), x(λ), y(λ), z(λ)} in the gravitational field of domain wall can be determined by integrating the geodesic equations for the metric (5). It has been already mentioned in , the acceleration of the test particle in the direction perpendicular to the domain wall ( i.e. in the z-direction) may be expressed as By simple but lengthy calculation one can get expression for acceleration which may be positive, negative (or zero) depending on suitable choice of the constants. This implies that the gravitational field of domain wall may be repulsive or attractive in nature (or no gravitational effect). Conclusions The present study deals with plane symmetric domain wall within the framework of Lyra geometry. The essential difference between the cosmological theories based on Lyra geometry and Riemannian geometry lies in the fact that the constant vector displacement field β arises naturally from the concept of gauge in Lyra geometry whereas the cosmological constant λ was introduced in adhoc fashion in the usual treatment. Currently the study of domain walls and cosmological constant have gained renewed interest due to their application in structure formation in the universe. Recently Rahaman et al have presented a cosmological model for domain wall in Lyra geometry under a specific condition by taking displacement fields β as constant. The cosmological models based on varying displacement vector field β have widely been considered in the literature in different context − . Motivated by these studies it is worthwhile to consider domain walls with a time varying β in Lyra geometry. In this paper both cases viz., constant and time varying displacement field β, are discussed in the context of domain walls with the framework of Lyra geometry. It has been pointed out that the result of Rahman et al is a special case of our results. Further for the sake of completeness all possible solutions of the field equations are presented in this paper.