content
stringlengths
10
4.9M
import { Component } from '@angular/core'; import { SingleStatView } from '../../../models/content'; import { AbstractViewComponent } from '../../abstract-view/abstract-view.component'; @Component({ selector: 'app-single-stat', templateUrl: './single-stat.component.html', styleUrls: ['./single-stat.component.scss'], }) export class SingleStatComponent extends AbstractViewComponent<SingleStatView> { constructor() { super(); } update() {} }
// GetRequestTokens retrieves tokens from the request headers and/or cookies // Mobile Clients/Secure Servers: Access tokens must be provided as a Bearer token // in the "Authorization" header // Web Clients: Access tokens must be provided in the "rokwire-access-token" cookie // and CSRF tokens must be provided in the "CSRF" header func GetRequestTokens(r *http.Request) (string, string, error) { authorizationHeader := r.Header.Get("Authorization") if authorizationHeader != "" { splitAuthorization := strings.Fields(authorizationHeader) if len(splitAuthorization) != 2 { return "", "", errors.New("invalid authorization header format") } if strings.ToLower(splitAuthorization[0]) != "bearer" { return "", "", errors.New("authorization header missing bearer token") } idToken := splitAuthorization[1] return idToken, "", nil } csrfToken := r.Header.Get("CSRF") if csrfToken == "" { return "", "", errors.New("missing authorization and csrf header") } accessCookie, err := r.Cookie("rokwire-access-token") if err != nil || accessCookie == nil || accessCookie.Value == "" { return "", "", errors.New("missing access token") } return accessCookie.Value, csrfToken, nil }
import * as data from "../../../data/loresheets"; import { zeroCost } from "../../models/character/costs"; import * as actions from "./loresheets"; const refLoresheetUid = "wulinsage"; describe("Testing loresheet action creators", () => { it("should create an open action", () => { const lsUid = data.getLoresheetData(refLoresheetUid).uid; const a = actions.open(lsUid, zeroCost); expect(a.payload.uid).toBe(lsUid); expect(a).toMatchSnapshot(); }); it("should not create an invalid open action", () => { const lsUid = "invalid uid yeah"; expect(() => actions.open(lsUid, zeroCost)).toThrow(); }); it("should create a buy option action", () => { const lsUid = data.getLoresheetData(refLoresheetUid).uid; const optUid = data.getLoresheetData(refLoresheetUid).options[0].uid; const a = actions.buyOption(lsUid, optUid, zeroCost); expect(a.payload.lsUid).toBe(lsUid); expect(a.payload.uid).toBe(optUid); expect(a).toMatchSnapshot(); }); it("should not create a buy option action for an invalid loresheet", () => { const lsUid = "invalid uid yeah"; const optUid = "some uid, yeah"; expect(() => actions.buyOption(lsUid, optUid, zeroCost)).toThrow(); }); it("should not create a buy invalid option action", () => { const lsUid = data.getLoresheetData(refLoresheetUid).uid; const optUid = "some uid, yeah"; expect(() => actions.buyOption(lsUid, optUid, zeroCost)).toThrow(); }); });
Neuromyelitis Optica: An Antibody-Mediated Disorder of the Central Nervous System Neuromyelitis optica (NMO) is a recurrent inflammatory disease that preferentially targets the optic nerves and spinal cord leading to blindness and paralysis. The hallmarks of NMO include bilateral optic neuritis and longitudinally extensive transverse myelitis. Woman and African Americans are overrepresented in the US patient population. NMO is associated with the NMO-IgG biomarker, which targets the aquaporin-4 water channel on astrocytes. The humoral pathology of NMO lesions include IgG and IgM deposits and infiltration by granulocytes suggesting that the NMO-IgG may be involved in the pathogenesis of disease. This review of the recent NMO literature covers the clinical features, epidemiology, radiology and pathology of disease and includes discussion of the important basic science research work in the field. Introduction Neuromyelitis optica (NMO) is an autoimmune inflammatory disorder of the central nervous system that predominately affects the optic nerves and spinal cord. In 1870, Allbutt was the first to report a case of NMO , but it was Devic who described the disorder in detail, and summarized 16 cases in the existing literature in 1894 . Based on this initial description, historically, NMO has been regarded as a severe, generally monophasic disorder of the optic nerves and spinal cord and was thought to be a variant of multiple sclerosis (MS). A convincing body of evidence in the past decade has established NMO as a distinct disease entity from MS. NMO is now recognized as a recurrent disease that largely targets the spinal cord and optic nerves but can also affect the brain as well. NMO occupies a unique position in the spectrum of inflammatory central nervous system demyelinating disorders in that it is the only such disorder that has an associated disease-specific antibody, aquaporin-4 antibody (AQP4 Ab), or NMO-IgG. Recognition of this antibody has been instrumental in elucidating the underlying pathobiology and in guiding treatment options for NMO. Clinical Features The clinical hallmarks of NMO are acute optic neuritis that is often bilateral and transverse myelitis that is often longitudinally extensive. Commonly reported symptoms include unilateral and bilateral loss of visual acuity, ocular pain, severe paraplegia, a symmetric sensory level, bladder dysfunction, paroxysmal tonic spasms of the trunk and limbs, and Lhermitte's phenomenon . Rostral extension of cervical cord lesions into the cervicomedullary junction can cause symptoms such as acute respiratory decompensation, nausea, intractable vomiting, and hiccups. These symptoms can precede or occur in association with the more typical features of optic neuritis or transverse myelitis . Clinical features attributable to locations outside of the optic nerves and spinal cord can also occur in patients with NMO. Hypothalamic-pituitary axis dysfunction can manifest as hypersomnolence, hyponatremia, hypothermia, hypothyroidism, and hyperprolactinemia . In addition, confusion, abrupt changes in level of consciousness, cortical blindness, and imaging findings suggestive of posterior reversible encephalopathy syndrome (PRES) have also been reported . The clinical course of NMO historically took one of two forms: monophasic or relapsing, with relapsing forms comprising approximately 80-90% of cases. However, after an index event, the distinction between monophasic and relapsing NMO is often difficult to make since relapses can occur many years after an event. In the vast majority of cases (∼80%), a relapse occurs by 2-3 years after the index event . Clinical features that may predict a relapsing course of disease include older age, female gender, less severe motor impairment with the initial myelitis event, and evidence of systemic autoimmunity . Clinical attacks typically progress over days, with varying degrees of recovery seen in the ensuing weeks to months. Recovery is usually incomplete, and most patients sustain residual disability, which increases with subsequent attacks . Factors predictive of mortality in patients with relapsing NMO include the presence of other systemic autoimmune disorders, higher attack frequency in the first two years, and poor motor recovery following the index myelitis event . Longitudinal case series of NMO patents with followup ranging from 5 to 10 years have demonstrated that the majority of patients (47-100%) have significant ambulatory difficulties at follow-up. Residual visual deficits are also common, with >60% of patients reporting significant vision loss in at least one eye. Mortality due to respiratory failure has been reported to take place in up to 32% of patients . Of note, this mortality figure was derived from the original Mayo Clinic study , which took place prior to the widespread recognition of NMO and NMOSDs, and the patient population may have been biased with respect to clinical disease severity. Therefore, the prognosis of NMO may not be as grave as was reported in these earlier studies. In 1999, Wingerchuk et al. proposed diagnostic criteria for NMO which were based on clinical and radiographic features . With the discovery of AQP4-Ab, these criteria were revised in 2006 to include the testing of this diseasespecific antibody. In addition, the necessary clinical features included were modified and simplified in an attempt to improve the diagnostic properties of the criteria. At present, the 2006 proposed diagnostic criteria for NMO consist of the presence of optic neuritis and transverse myelitis as well as 2 out of 3 of a contiguous spinal cord MRI lesion extending over more than 3 vertebral segments (i.e., longitudinally extensive), brain MRI not meeting diagnostic criteria for MS, and NMO-IgG seropositive status . These criteria are 99% sensitive and 90% specific for the diagnosis of NMO and have been independently validated in different patient populations . The recent literature suggests that in addition to its utility in the diagnosis of NMO, the presence of NMO-IgG may have a role in disease prognosis. In a prospective study of patients with longitudinally extensive transverse myelitis (LETM), 55% of those positive for NMO-IgG relapsed with recurrent LETM or optic neuritis, while none of the seronegative patients relapsed . Similarly, in a series of patients with recurrent optic neuritis, the presence of NMO-IgG heralded a 50% chance of developing transverse myelitis , while only 6.6% of seronegative patients developed transverse myelitis. More recently, Jarius et al. found that in acute monosymptomatic optic neuritis, 50% of NMO-IgG seropositive patients progressed to NMO within 12 months, while none of the seronegative patients progressed after a median follow-up of 26 months . In light of the fact that NMO is a disorder that has the potential to cause significant disability, the ability to recognize and differentiate NMO and related disorders from other demyelinating disorders is important from a clinical perspective. The term "NMO spectrum disorders" has been coined to reflect a variety of disorders thought to be related to NMO but do not quite meet the clinical diagnostic criteria for definite NMO. Disorders that are typically included in this classification are NMO-IgG seropositive limited forms of NMO (single or recurrent LETM, recurrent or simultaneous bilateral ON), Asian opticospinal MS (OSMS), optic neuritis or LETM associated with systemic autoimmune disease, and optic neuritis or myelitis associated with brain lesions typical of NMO (e.g., hypothalamic or brainstem lesions) . Whether the NMO-IgG seronegative forms of these disorders are a forme fruste of classic NMO or whether they are variants of other autoimmune diseases is, at present, unclear. Until we are able to better identify with certainty that these are distinct disorders, the designation of NMO spectrum disorders is useful, as it has specific prognostic and therapeutic implications for these potentially related disorders. Epidemiology NMO has a distinct epidemiological profile in comparison to MS. The median age of onset of NMO is typically in the fourth or fifth decade, which is older than the average age of onset of MS. The age of onset can be quite variable, however, and NMO is occasionally seen in children and the elderly. There is a significant female predominance in both diseases, but it is even more polarized in NMO, with a female-to-male ratio ranging from 5-11 : 1 . From a global perspective, NMO occurs much more commonly in nations with a predominately nonwhite population make-up, where it is a common cause of CNS demyelination. In Japan, up to 15-40% of MS is comprised of the opticospinal variant, which may be a synonymous disorder with NMO . Lau et al. reported that up to 36% of MS cases in Hong Kong had selective involvement of the optic nerves and spinal cord , and NMO comprised 17% of possible MS cases in French Afro-Caribbeans in Martinique . In a population-based study in Cuba, NMO comprised approximately 10% of demyelinating disorders . In contrast, in countries consisting of a predominately white population, NMO comprised less than 2% of all demyelinating disorders, and the majority of cases occurred in white patients . Similarly, in the Mayo series, Wingerchuk et al. found that NMO still tends to occur predominately in white populations . Our experience at the NMO clinic at Johns Hopkins Medical Institution has shown a significant racial predilection for NMO with African American populations comprising approximately 50% of patients, which is clearly epidemiologically distinct from MS (unpublished data). Of note, there is a differential demographic profile in monophasic and relapsing NMO, with a stronger female predominance in relapsing NMO (female : male = 9 : 1), while monophasic NMO seems to equally affect both genders (female : male = 1 : 1). In addition, the median age of onset in monophasic NMO is a decade earlier than relapsing NMO (29 years versus 39 years, resp.) . Genetics The distinct racial predilection of NMO suggests a possible genetic etiological contribution. Although there have been a handful of reports on familial cases of NMO, to date, a convincing human leukocyte antigen (HLA) class II allele association has not been established . Conventional Imaging Techniques. Conventional MRI is an important tool in the diagnosis of NMO. A classic MRI feature that is seen in the majority of NMO patients is a longitudinally extensive transverse myelitis (LETM) that spans more than 3 vertebral levels, which is associated with cord swelling and gadolinium enhancement in many cases ( Figure 1). The extent of the longitudinally extensive lesion in the cord, however, can be related to the proximity to the attack; therefore, in some cases the absence of LETM does not necessarily exclude the diagnosis of NMO. Cord atrophy can be observed in 22% of cases with follow-up imaging. Enhancement along the course of the optic nerve is another typical finding if the MRI is performed in close temporal proximity (within two weeks) of the onset of symptoms of optic neuritis . Although a "normal" MRI of the brain was initially thought to be a criterion of NMO, subsequent investigations confirm that the MRI brain is, in fact, abnormal in the majority of NMO patients. In patients with clinical and radiological features otherwise typical for NMO, 60-85% of cases have been shown to have abnormal brain lesions. Over time, up to 10% of patients develop lesions typical of MS . Lesions involving the diencephalon and brainstem distinctly atypical for MS have been commonly reported in NMO patients . These distinctive lesions predominately involve the hypothalamus and can extend to brain tissue surrounding the third and fourth ventricle and aqueduct of Sylvius and seem to be characteristic brain lesions of NMO. In a subsequent study, Pittock et al. demonstrated that these regions correspond with areas of AQP4 channel localization, which supports the notion that this area is particularly sensitive to pathogenic NMO-IgG . The revised diagnostic criteria for NMO recognize the common brain abnormalities seen in NMO patients and were modified to include patients with abnormal brain MRI atypical for MS, rather than those with normal brain MRI . Advanced Imaging Techniques. Advanced MRI techniques have enabled the establishment of further distinctions between NMO and MS patients, which increasingly supports the notion that NMO is a distinct disease entity. Filippi et al. demonstrated normal magnetization-transfer ratio (MTR) in the normal-appearing brain tissue of NMO patients, while patients with MS showed a significantly decreased MTR. In the spinal cord, on the other hand, MTR was significantly diminished in both NMO and MS patients. These findings correspond with clinical observations and suggest that the brain lesions of NMO are less destructive and, therefore more commonly asymptomatic, while spinal cord lesions tend to be much more destructive, and, therefore, more clinically symptomatic . A subsequent study using both diffusion-tensor and magnetization-transfer imaging of the brain assessed normal-appearing gray and white matter separately in NMO and demonstrated no abnormalities in normal-appearing white matter, but diminished MTR and increased mean diffusivity (MD) in the normal-appearing gray matter, suggesting the presence of tissue disruption in the gray matter of NMO patients . More recently, Yu et al. demonstrated the presence of abnormal diffusion (lower fractional anisotropy and higher mean diffusivity) in the white matter and gray matter of NMO patients in comparison to controls. Interestingly, further analysis of the white matter abnormalities showed that regions connected to the optic nerves and spinal cord had abnormal diffusion, while regions unconnected to the optic nerves and spinal cord demonstrated normal diffusion. This finding suggests that the observed abnormalities in water diffusion of the white matter tracts in NMO are largely caused by secondary degeneration from primary lesions in the optic nerves and spinal cord, rather than independent lesions . A more recent study investigating the normalappearing white matter in the spinal cord of NMO patients confirmed the presence of abnormal diffusion (diminished fractional anisotropy, elevated mean, and perpendicular diffusivity) in normal-appearing white matter and demonstrated a significant correlation of diffusion-tensor imagingderived indices to global measures of clinical dysfunction. Based on these findings, the authors postulated that the pathological substrate of clinical dysfunction in NMO was more likely due to demyelination rather than axonal loss and that diffusion-tensor imaging-based indices may be useful as biomarkers for NMO . Optical Coherence Tomography. Optical coherence tomography is an increasingly utilized method to visualize retinal pathology in optic-nerve-related disorders. de Seze et al. demonstrated a significantly thinner retinal nerve fiber layer (RNFL) in NMO patients in comparison to controls and a significant correlation to EDSS, a global measure of disability . Subsequent reports comparing NMO and MS patients found that the RNFL in NMO patients is thinner on average, and that, after an episode of optic neuritis, the RNFL is significantly thinner in NMO patients, suggesting more substantial retinal damage following optic neuritis in NMO in comparison to MS . Taken together, these findings confirm the utility of novel imaging techniques in providing increasing insight into NMO disease mechanisms. Laboratory evidence of non-organ-specific systemic autoimmunity is also common, and up to 25 Anti-Aquaporin-4 Antibody (NMO-IgG) The discovery of the NMO-IgG has played a pivotal role in the diagnosis and elucidation of disease mechanisms in NMO. The discovery of an NMO disease-specific antibody (NMO-IgG) by Lennon et al. in 2004 was fuelled by the observation that immunoglobulin and complement deposition in active lesions followed a distinct rim and rosette vasculocentric pattern, suggesting an antibody-mediated mechanism of disease . Later, the target of NMO-IgG was identified to be the aquaporin-4 (AQP4) water channel . The sensitivity and specificity of the NMO-IgG in identifying NMO in the Lennon et al. series were 73% and 91%, respectively . Subsequently, multiple groups have validated the specificity of the NMO-IgG in identifying NMO using various immune assays. Waters and Vincent compared the sensitivities and specificities of the five main methods developed in relapsing NMO patients, which include indirect immunofluorescence (IIF), a cell-based assay (CBA), a radioimmunoprecipitation assay (RIPA), a fluoroimmunopireciptation assay (FIPA), and enzyme-linked immunosorbent assay. All techniques had high specificities, ranging from 91 to 100%, with the CBA and FIPA both having specificities of 100%. Sensitivities, on the other hand, varied and ranged from 57 to 91%, with IIF, FIPA, and CBA showing the highest sensitivities at 86, 83, and 91%, respectively . There is evidence that rates of NMO-IgG seropositivity in patients meeting clinical diagnostic criteria for NMO may vary significantly depending on the population being tested. A study comparing NMO-IgG seropositivity in patients fulfilling the 1999 Wingerchuk diagnostic criteria for NMO in the Caribbean and Europe demonstrated a lower rate in the Caribbean (33.3%), as compared with Caucasian patients from Spain and Italy (62.5%) and France (53.8%) . In comparison, 2 studies of NMO-IgG detection rates in Japanese patients with OSMS and LETM varied significantly, with one reporting NMO-IgG seropositivity in 60% of patients, while another reports seropositivity in 35% of such patients . At present, it is unclear whether there is truly a subset of patients with clinical NMO that are NMO-IgG negative, or if this is a result of inadequate sensitivity of existing immunoassays to detect the antibody, or inadequately sensitive and specific diagnostic criteria, or a combination of all of these factors. Given the variability in the diagnostic properties of different assays, until further insight is available into this issue, current expert recommendations are to test for the presence of NMO-IgG using two separate detection methods, one of which should be indirect immunofluorescence . Pathological Features and Proposed Disease Mechanisms AQP4 is an integral homotetrameric protein complex and is expressed primarily on the abluminal surface of astrocyte foot process and can also be found on ependymocytes and endothelial cells . It is one of the main water channels in the central nervous system but is also found outside of the central nervous system in many solid organs including renal distal collecting tubules and in a portion of gastric parietal cells. In astrocytes, AQP4 is anchored by a dystroglycan complex and is found in highest concentrations in astrocytes having direct contact with capillaries and pia in the brain and spinal cord . AQP4 likely acts in concert with potassium and bicarbonate channels to regulate water dynamics in the CNS between brain, blood, and CSF and is therefore an integral element of brain volume and ion homeostasis . AQP4 has also been shown to play a role in astrocyte migration and neural signal transduction in animal models . The absence of AQP4 in knockout mouse models is known to exacerbate the recovery from vasogenic edema, and AQP4 has been shown to mediate cerebral edema in various models of neurological injury, including epilepsy, ischemia, and trauma . Interestingly, a recent study in AQP4-knockout mice found that experimental autoimmune encephalomyelitis (EAE) was attenuated in comparison to wild-type mice, which implicates AQP4 as a novel disease determinant of the severity of EAE and likely other autoimmune disorders of the CNS . Zhang and Verkman demonstrated the presence of high concentrations of AQP4 in perivascular astrocytic foot processes in the cerebral cortex, subependymal and vasculocentric regions of the brainstem, and gray and white matter of the spinal cord, and in a vasculocentric pattern in the optic nerves . This pattern seems to coincide, for the most part, with sites of preferential lesion formation in NMO. However, the presence of high concentrations of AQP4 in astrocytic foot processes in the cerebral cortex, as well as in retinal Muller cells , which are not areas in which NMO lesions are typically seen clinically, suggests that there is selectivity of AQP4 involvement in the pathogenesis of NMO. Basic structural pathology of the spinal cord in NMO typically shows extensive demyelination across multiple levels associated with necrosis, cavitation, and axonal loss, involving both the gray and white matter. Lesions typically localize to the central cord, and there is evidence of myelin preservation in the periphery, with a significant loss of oligodendrocytes. In chronic lesions, evidence of gliosis, atrophy, and cavitation is commonly seen. The optic nerves and chiasm have also been reported to show inactive demyelination, partial remyelination, as well as gliosis and cavitation . Nagelhus et al. described two distinct types of NMO lesions: those with AQP4 loss and demyelination and necrosis, which are typically seen in the optic nerve and spinal cord, and those with AQP4 loss without demyelination or necrosis, which are typically seen in the medulla and area postrema . The absence of demyelination and necrosis in the latter type of lesions corresponds to the reversible nature of MRI lesions in the medulla and area postrema, as well as resolution of clinical dysfunction attributable to these regions . Inflammatory infiltrates within active demyelinating lesions consist of extensive infiltration of macrophages and microglia, numerous B lymphocytes, occasional CD3+ and CD8+ T lymphocytes, as well as prominent perivascular granulocytes and eosinophils. In early active demyelinating lesions, there is prominent IgG and complement reactivity and macrophage staining in a distinct perivascular rosette pattern, as well as along the rim of thickened vessel walls, suggesting a role for humoral autoimmunity in NMO disease mechanisms . Accumulating pathological evidence is convincing that the targeted attack of AQP4 by the NMO-IgG is an important initiating event in the development of NMO. The discovery of a disease-specific autoantibody in NMO, the identification of AQP4 as the antibody target , and the demonstration that most NMO lesions have marked loss of AQP4 provide support for this hypothesis . Furthermore, in NMO lesions, the pattern of AQP4 loss has been shown to correspond to the characteristic vasculocentric rim and rosette pattern of IgG and complement deposition. Finally, areas with marked AQP4 loss concurrently show significantly reduced staining for glial fibrillary astrocytic protein (GFAP), with relatively preserved myelin-basic protein, suggesting that astrocytes are the primary target of the NMO-IgG . Taken together, these pathological findings support the notion that a targeted attack of AQP4 in astrocytic foot processes plays a prominent role in NMO pathogenesis involving an immune cascade of events which ultimately results in the clinical manifestations of the disease. Different hypotheses on the exact immunopathogenic mechanisms by which NMO-IgG exerts it effects have been promoted by separate groups. Lucchinetti et al. have postulated that binding of NMO-IgG to AQP4 initiates two separate events: activation of the lytic complement cascade, and downregulation of AQP4 by endocytosis and degradation . A few important observations support this notion, including: the colocalization of immunoglobulin with a marker of the terminal lytic complement complex (C9neo antigen), the presence of activated macrophages and significant vascular hyalinization in perivascular regions in active NMO lesions , and in vitro experiments which demonstrate the colocalization of AQP4 with EAAT2, a glutamate transporter and the fact that AQP4 and EAAT2 were endocytosed in the presence of NMO-IgG . Based on these observations, Hu and Lucchinetti propose that binding of NMO-IgG to AQP4 in astrocytic foot processes initiates complement-mediated effects but also disrupts glutamate homeostasis, which can lead to oligodendrocyte injury in the spinal cord and optic nerves, both of which are highly sensitive structures to fluctuations in ambient glutamate concentrations . In addition, they postulate that aberrations in glutamate homeostasis render these structures more sensitive to complement-mediated attacks. On a similar note, Misu et al. found significantly diminished AQP4 and GFAP staining, most prominently in perivascular regions with complement and immunoglobulin deposition with relative preservation of myelin-basic protein. The conclusion from this group was that these observations provide further support for the hypothesis that astrocytic impairment associated with humoral autoimmunity directed against AQP4, which causes AQP4 downregulation, is the primary immunopathogenic mechanism in NMO . By way of comparison, Parratt and Prineas demonstrated in pathological case series examining NMO versus MS lesions that the chief pathological feature unique to NMO was not downregulation of AQP4 expression, but an early complete destruction of perivascular astrocytes, with gliosis initiated by a population of astrocyte progenitors . Although this conclusion can still support an important pathogenic role of NMO-IgG and complement-mediated damage to astrocytes in NMO, it raises the possibility that the acute breakdown of large numbers of astrocytes may in fact be the initiating factor for the generation of NMO-IgG, rather than vice versa. More recently, in a pathological case series of NMO versus MS lesions, Matsuoka et al. found significant variability in the degree of AQP4 loss in actively demyelinating lesions in between patients with NMO and significant lesion-tolesion heterogeneity of AQP4 expression even in patients with preferential AQP4 loss. The authors also observed significant variability in the relationship between AQP4 loss and the perivascular deposition of activated complement and immunoglobulin. Furthermore, different patterns of AQP4 loss and perivascular deposition of activated complement and immunoglobulins were observed even within a single lesion. The conclusion from this study was that that there is a heterogeneous relationship between anti-AQP4 antibody and loss of AQP4 expression and that AQP4-mediated immunological destruction may not be the sole mechanism by which NMO lesions are formed . Animal studies have shed some insight into the complexity of NMO disease mechanisms by demonstrating that the presence of the NMO-IgG alone is not directly pathogenic. Kinoshita et al. demonstrated that while passive transfer of IgG obtained from NMO patients to EAE-induced Lewis rats resulted in active lesions with histopathological features suggestive of those observed in human NMO , a subsequent study by Bradl et al. showed that the infusion of IgG from NMO patients to healthy (i.e., non-EAE) rats does not cause lesions or clinical symptoms suggestive of human NMO . These findings suggest that human NMO-IgG in and of itself is not pathogenic in rodents but requires the presence of T-cell-mediated CNS inflammation to exert its pathogenic effects. Clinical reports of NMO-IgG identified in patients many years before the clinical onset of symptoms and a significant portion of patients reporting antecedent viral infections prior to symptom onset are both supportive of this hypothesis . It is worth noting, however, that the pathogenic effects of human NMO-IgG infused into these EAE mice may have been exaggerated due to the species-specific nature of complement inhibitors, which are typically abundant throughout the CNS. In addition to T-cell-mediated CNS inflammation, a complex array of immune cells are evidently at play in NMO disease pathogenesis. Recently, Chihara et al. demonstrated that a subpopulation of B cells resembling plasmablasts was increased in the peripheral blood of patients with NMO and that this population of cells was predominately responsible for the production of NMO-IgG. Interestingly, IL-6 was found to increase the survival of this population of plasmablasts and blockade of IL-6 receptor signaling reduced their survival. From a therapeutic perspective, this is of significant interest in NMO as IL-6 receptor blockading agents (tocilizumab) are already approved for clinical use in the treatment of other autoimmune disorders such as rheumatoid arthritis . To date, an animal model that recapitulates all aspects of human NMO has yet to be identified. The development of such a model of disease will enable further elucidation of proposed disease mechanisms. Until then, we will continue to use various animal models including those that are based on EAE with passive transfer of NMO-IgG. Taking all of the aforementioned pathological, in vitro, and animal studies into account, it is evident that NMO-IgG plays an important role in NMO disease mechanisms, However, at present, it is difficult to derive any definitive conclusions on the specific role of AQP4 in evolving NMO lesions. The development of more accurate animal models of NMO and further pathological studies in humans will allow clarification of the precise sequence of pathological events in NMO. Treatment of Acute Relapses. Acute relapses of NMO are generally treated with high-dose intravenous methylprednisolone at 1 g daily for 3-5 days. In some cases, this is followed by an oral prednisone taper. This practice is based on evidence from MS treatment trials rather than any specific controlled trials in NMO patients. Observational studies have shown that the majority of patients (80%) improve with a short course of methylprednisolone . The efficacy of PLEX has been evaluated in a series of retrospective studies which demonstrated clinical improvement in 50-60% of steroid-refractory NMO patients who were treated with PLEX , as well as significant clinical improvement in PLEX-treated patients in comparison to those treated with steroids alone . A randomized, shamcontrolled trial demonstrated the efficacy of PLEX in a combination of acute CNS demyelinating diseases, which included 2 cases of NMO. The proportion of patients with clinical improvement was significantly higher in patients who had undergone PLEX in comparison to sham treatment (42.1% versus 5.9%) . The typical courses of PLEX used in these reports consisted of 4-7 exchanges over a period of 5-14 days. The literature supporting the use of IVIG in NMO relapses is sparse and includes only one isolated case report . Therefore, there is insufficient evidence to support the utility of IVIG in the treatment of acute relapses of NMO. Preventive Treatment. The preventive treatments used in NMO are based largely on retrospective or open-label trials and case series, which makes it difficult to draw definitive conclusions on the efficacy of many of these agents. A summary of the existing evidence for various preventive agents is presented below. Immunomodulatory Agents. The use of IFN-beta-1b in the preventive treatment of NMO has been reported predominately in the context of Japanese OSMS, and most reports support the notion that interferons are not helpful and may even be harmful in these patients. Uzawa et al. compared the efficacy of IFN-beta-1b in NMO versus MS patients and found that this agent was ineffective in NMO patients . Warabi et al. reported clinical relapses consisting of optic neuritis and myelitis in patients with OSMS treated with IFN-beta-1b . Shimizu et al. reported the development of tumefactive brain lesions in 2 NMO patients treated with IFN-beta-1b, with complete clinical stabilization after the initiation of immunosuppressive treatment with azathioprine . More recently, in a retrospective analysis of carefully selected patients with "genuine" OSMS (rather than NMO), Shimizu et al. reported a significant therapeutic benefit of IFN-beta-1b, with diminished relapse rates and disability progression . In a retrospective analysis conducted by Papeix et al. comparing NMO patients treated with various immunosuppressive agents versus interferon-beta treatment, those treated with immunosuppressive agents showed a significant decrease in relapse rate . A recent case report by Palace et al. reported clinical relapses and high anti-AQP4 Ab titres in a patient with NMO treated with interferon-beta-1a and subsequent clinical stabilization and lower titres with the initiation of azathioprine . Taken together, the existing literature does not support the use of interferon-beta immunomodulatory treatment in NMO and even suggests that these agents may exacerbate the disorder. An important caveat to this conclusion, however, is that, in some cases of "genuine" OSMS, IFN-beta-1b may have therapeutic efficacy. On the other hand, the use of Copaxone, another first-line immunomodulatory agent used in MS, has been reported in the context of NMO in only two case reports, both which showed a beneficial response . Immunosuppressive Agents. The humoral-mediated immune mechanisms underlying NMO provide theoretical support for the use of rituximab, which is a monoclonal antibody targeting CD20, a protein present on the surface of mature B-lymphocytes. The role of rituximab in ameliorating NMO disease mechanisms by B-lymphocyte depletion has yet to be definitely clarified, but recent evidence demonstrating that CD20-negative plasmablasts are the main subgroup of B-cells responsible for the production of NMO-IgG suggests that rituximab acts through mechanisms other than diminishing the production of antibodies, and possibly via antigen-presenting cells . The efficacy of rituximab in NMO was initially demonstrated in an open-label trial by Cree et al. where 8 NMO patients were treated and followed for a mean of 12 months. The majority (75%) of patients remained relapse-free at followup, and all but one patient (87.5%) showed significant neurological improvement. Rituximab was well tolerated in this trial, and no patients experienced any serious adverse reactions . A subsequent retrospective multicenter case series of 25 patients by Jacob et al. showed a significant decrease in relapse rate at a median follow-up of 19 months, 8 Neurology Research International as well as disability stabilization or improvement in the majority of patients (80%). Of note, 20% of patients in this series developed new or reactivated infections, and 1 patient died of sepsis . In support of the safety profile of this agent, the literature on the use of rituximab in hematological and rheumatological disorders confirms the long-term safety of this agent, with serious adverse effects seen in only a small minority of patients . A recent report by the European Federation of Neurological Societies by Zhang and Verkaman recommends rituximab as a first-line agent , which has also been our practice at Johns Hopkins. The optimal dosing regimen of rituximab has yet to be determined, and existing studies have utilized differing dosing regimens. Our practice at Johns Hopkins has been to give a single dose of rituximab at 1000 mg intravenously initially, followed by a repeat dose of 1000 mg intravenously after two weeks. Thereafter, CD19/20 cell counts are monitored on a monthly basis. When the CD19/20 cell counts climb above 0.1% of the total lymphocyte count, patients are given the same double dose of rituximab (1000 mg iv × 1, followed by 1000 mg iv after two weeks). If the CD19/20 cell count is undetectable 6 months after the last dose, a single dose of 1000 mg iv is given, and CD19/20 counts are followed closely. In children, an initial single dose of rituximab of 375 mg/m 2 is given, and this dose is repeated when the CD19/20 cell count climbs above 0.1% as in adults. Further laboratory parameters to routinely monitor are outlined in Table 1. Azathioprine (AZA) is an oral immunosuppressive agent commonly used in organ-transplant-related immunosuppression, as well as in the treatment of systemic autoimmune disorders such as SLE and rheumatoid arthritis. AZA is a purine antagonist that interferes with DNA and RNA synthesis, which results in immune cell inhibition by a variety of mechanisms. The efficacy of AZA in the preventive treatment of NMO patients was described by Mandler et al. in an openlabel prospective trial of 7 NMO patients, where sustained disability improvement and the absence of any subsequent relapses over 19 months was documented in all subjects . Subsequently, Bichuetti et al. performed a retrospective review of 36 cases of NMO, of which 27 patients were on AZA at a mean follow-up of 47 months. AZA alone or in combination with prednisone was shown to significantly diminish relapse rate and stabilize disability . Of note, in both reports, there were no serious adverse effects in any patients treated with AZA. Most recently, Costanzi et al. performed a retrospective review of 99 patients with NMO spectrum disorders treated with AZA. AZA used alone or in combination with prednisone significantly reduced annualized relapse rates by 76%, and in 70 patients with more than 12 months of follow-up EDSS was stable or improved in 60% of patients. Of note, 3 cases of lymphoma were reported in this study . The causal link between AZA and lymphoma is at present controversial; however, until further information is available, this is another serious adverse effect of which clinicians should be aware. The utility of AZA in diminishing relapse rate has also been documented in a handful of case reports and case series , as well as a subset of a cohort of NMO patients described by Jarius et al. . The dosing regimen for AZA varies across different centers, but at Johns Hopkins, our preference is to start at 2 mg/kg/day, divided into two daily doses. If there is no clinical response, the dose is increased to 3 mg/kg/day. For resistant cases, prednisone at 1 mg/kg/day is added or the decision is made to switch to another immunosuppressive agent. Patients considering initiating AZA should be tested for the thiopurine S-methyltransferase (TPMT) mutation, which is seen in up to 10% of the US population . Individuals harboring this mutation can develop significant bone marrow toxicity with AZA; therefore, this medication is best avoided in these patients. Further laboratory parameters to monitor are outlined in Table 1. Mycophenolate mofetil (MMF) is another oral immunosuppressive agent commonly used in organ-transplantrelated immunosuppression and rheumatological disorders. MMF acts as an inhibitor of a rate-limiting enzyme in the synthesis of guanine ribonucleotide and 2-deoxyribonucleotide, which ultimately suppresses the immune system by inhibiting dendritic cell and T and B lymphocyte functioning. The efficacy of MMF in NMO was described in a retrospective case series of 24 patients with NMO and NMO spectrum disorders, which demonstrated a significantly diminished relapse rate, as well as stable or improved disability measures in the majority (91%) of patients which included rituximab failures. Of note, 25% of patients reported adverse effects, and 1 patient had a low WBC count that necessitated discontinuing the medication . One serious adverse effect derived from the transplant literature is a 14.4 in 100,000 risk of PML . At Johns Hopkins, our practice has been to utilize MMF as a first-line agent. Patients are started on a dose of 500 mg twice daily, which is titrated up to 1000 mg twice daily over 4 weeks. At the 4-week mark, the WBC count and differential is assessed. The target total WBC count is 3-4 × 10 3 /µL (approximately half of normal). Alternatively, the target absolute lymphocyte count is 1-1.2 × 10 3 /µL. The absolute lymphocyte count should not fall below 1 × 10 3 /µL. If either target is not attained, the MMF dose is increased by 250 mg twice daily every two weeks, up to a maximum of 1500 mg twice daily. If the target is not attained at the maximum 1500 mg twice daily, other immunosuppressive agents such as rituximab can be considered. While the MMF dose is being titrated up to the target dose, prednisone is typically co-administered at 20-30 mg daily and weaned off when the target MMF dose is reached. Monthly liver function tests should be performed to rule out toxicity for six consecutive months while the dose is titrated, then twice yearly thereafter on a stable dose. Further laboratory parameters to monitor are outlined in Table 1. Cyclophosphamide (CYC) is an intravenous immunosuppressive drug that acts as a DNA alkylating agent, which ultimately impairs T and B lymphocyte activity, as well as various inflammatory cytokines. CYC is used in combination with other agents in the treatment of various malignancies, as well as in the treatment of systemic autoimmune disorders. There are no extensive case series or controlled trials on the use of CYC in NMO, but isolated case reports have shown a beneficial clinical effect on relapse rate and disability in , as well as in patients with NMO/SLE overlap . Methotrexate (MTX) is a dihydrofolate reductase inhibitor and acts by impairing DNA synthesis. MTX is a commonly used drug in the treatment of systemic autoimmune disorders and in combination with other drugs as a chemotherapeutic agent. The utility of a combination of MTX and prednisolone in NMO was described in a case report by Palace et al., where a patient remained relapse-free 3 years after the initiating treatment . Mitoxantrone (MITO) is a synthetic anthracenedione derivative that acts by inhibiting both DNA and RNA synthesis, which results in suppression of both T and B lymphocytes, and inhibition of proinflammatory cytokine secretion. The efficacy of MITO in NMO was demonstrated in a prospective open-label two-year study where 4 out of 5 patients (80%) showed significant clinical and radiographic improvement. In this study, MITO was generally well tolerated, with one patient having evidence of subclinical cardiac insufficiency that recovered after medication discontinuation . A subsequent retrospective case series by Kim et al. showed that MITO resulted in a significant decrease in relapse rate and stabilization or improvement in measures of disability in all patients. There were no serious adverse effects in any patients . Despite the apparent tolerability of MITO in these two trials, experience in MS and other disorders has shown that MITO can causes serious toxicity with reports of potentially lethal adverse effects such as opportunistic infection, cardiac systolic dysfunction, and therapy-related acute leukemia . Therefore, the clinical benefits associated with the use of MITO in NMO must be carefully weighed against the potential serious risks and the fact that the long-term tolerability in NMO patients remains unknown. Case reports have suggested that intermittent IVIG infusions may be of utility in preventing relapses and clinical deterioration. Bakker and Metz reported 2 cases of NMO treated with monthly infusions of IVIG that resulted in a significant decrease in relapse rate and clinical improvement . More recently, Okada et al. report a case of NMO that responded with monthly IVIG with respect to relapse rate and clinical disability . A recent case series of 2 patients with treatment-refractory NMO showed a significant decrease in relapse rate with the initiation of intermittent plasmapheresis . Although the existing evidence is not sufficient to recommend intermittent IVIG as preventive treatment in NMO, it may be considered for research trials in treatment-refractory individuals. Conclusion In the past decade, the discovery of a disease-specific antibody has enabled the establishment of NMO as a distinct disease entity in the spectrum of CNS demyelinating disorders. What was once thought of as a variant of MS is now regarded as a unique disease entity with significantly different prognostic and treatment implications. Although much progress has been made in clarifying the clinical, epidemiological, radiographic, and pathological features of NMO, much remains to be understood. Future directions of investigation include the development of an accurate animal model of disease, refinement of immunoassays for detection of the NMO-IgG, application of novel imaging techniques, and clarification of the epidemiological and genetic risk factors of NMO. Together, this will enable earlier disease detection and, ultimately, the development of more targeted treatment strategies for this debilitating neurological disorder.
class TriAnalyzer: """ Define basic tools for triangular mesh analysis and improvement. A TriAnalyzer encapsulates a `.Triangulation` object and provides basic tools for mesh analysis and mesh improvement. Attributes ---------- scale_factors Parameters ---------- triangulation : `~matplotlib.tri.Triangulation` The encapsulated triangulation to analyze. """ def __init__(self, triangulation): cbook._check_isinstance(Triangulation, triangulation=triangulation) self._triangulation = triangulation @property def scale_factors(self): """ Factors to rescale the triangulation into a unit square. Returns ------- (float, float) Scaling factors (kx, ky) so that the triangulation ``[triangulation.x * kx, triangulation.y * ky]`` fits exactly inside a unit square. """ compressed_triangles = self._triangulation.get_masked_triangles() node_used = (np.bincount(np.ravel(compressed_triangles), minlength=self._triangulation.x.size) != 0) return (1 / np.ptp(self._triangulation.x[node_used]), 1 / np.ptp(self._triangulation.y[node_used])) def circle_ratios(self, rescale=True): """ Return a measure of the triangulation triangles flatness. The ratio of the incircle radius over the circumcircle radius is a widely used indicator of a triangle flatness. It is always ``<= 0.5`` and ``== 0.5`` only for equilateral triangles. Circle ratios below 0.01 denote very flat triangles. To avoid unduly low values due to a difference of scale between the 2 axis, the triangular mesh can first be rescaled to fit inside a unit square with `scale_factors` (Only if *rescale* is True, which is its default value). Parameters ---------- rescale : bool, default: True If True, internally rescale (based on `scale_factors`), so that the (unmasked) triangles fit exactly inside a unit square mesh. Returns ------- masked array Ratio of the incircle radius over the circumcircle radius, for each 'rescaled' triangle of the encapsulated triangulation. Values corresponding to masked triangles are masked out. """ # Coords rescaling if rescale: (kx, ky) = self.scale_factors else: (kx, ky) = (1.0, 1.0) pts = np.vstack([self._triangulation.x*kx, self._triangulation.y*ky]).T tri_pts = pts[self._triangulation.triangles] # Computes the 3 side lengths a = tri_pts[:, 1, :] - tri_pts[:, 0, :] b = tri_pts[:, 2, :] - tri_pts[:, 1, :] c = tri_pts[:, 0, :] - tri_pts[:, 2, :] a = np.hypot(a[:, 0], a[:, 1]) b = np.hypot(b[:, 0], b[:, 1]) c = np.hypot(c[:, 0], c[:, 1]) # circumcircle and incircle radii s = (a+b+c)*0.5 prod = s*(a+b-s)*(a+c-s)*(b+c-s) # We have to deal with flat triangles with infinite circum_radius bool_flat = (prod == 0.) if np.any(bool_flat): # Pathologic flow ntri = tri_pts.shape[0] circum_radius = np.empty(ntri, dtype=np.float64) circum_radius[bool_flat] = np.inf abc = a*b*c circum_radius[~bool_flat] = abc[~bool_flat] / ( 4.0*np.sqrt(prod[~bool_flat])) else: # Normal optimized flow circum_radius = (a*b*c) / (4.0*np.sqrt(prod)) in_radius = (a*b*c) / (4.0*circum_radius*s) circle_ratio = in_radius/circum_radius mask = self._triangulation.mask if mask is None: return circle_ratio else: return np.ma.array(circle_ratio, mask=mask) def get_flat_tri_mask(self, min_circle_ratio=0.01, rescale=True): """ Eliminate excessively flat border triangles from the triangulation. Returns a mask *new_mask* which allows to clean the encapsulated triangulation from its border-located flat triangles (according to their :meth:`circle_ratios`). This mask is meant to be subsequently applied to the triangulation using `.Triangulation.set_mask`. *new_mask* is an extension of the initial triangulation mask in the sense that an initially masked triangle will remain masked. The *new_mask* array is computed recursively; at each step flat triangles are removed only if they share a side with the current mesh border. Thus no new holes in the triangulated domain will be created. Parameters ---------- min_circle_ratio : float, default: 0.01 Border triangles with incircle/circumcircle radii ratio r/R will be removed if r/R < *min_circle_ratio*. rescale : bool, default: True If True, first, internally rescale (based on `scale_factors`) so that the (unmasked) triangles fit exactly inside a unit square mesh. This rescaling accounts for the difference of scale which might exist between the 2 axis. Returns ------- bool array-like Mask to apply to encapsulated triangulation. All the initially masked triangles remain masked in the *new_mask*. Notes ----- The rationale behind this function is that a Delaunay triangulation - of an unstructured set of points - sometimes contains almost flat triangles at its border, leading to artifacts in plots (especially for high-resolution contouring). Masked with computed *new_mask*, the encapsulated triangulation would contain no more unmasked border triangles with a circle ratio below *min_circle_ratio*, thus improving the mesh quality for subsequent plots or interpolation. """ # Recursively computes the mask_current_borders, true if a triangle is # at the border of the mesh OR touching the border through a chain of # invalid aspect ratio masked_triangles. ntri = self._triangulation.triangles.shape[0] mask_bad_ratio = self.circle_ratios(rescale) < min_circle_ratio current_mask = self._triangulation.mask if current_mask is None: current_mask = np.zeros(ntri, dtype=bool) valid_neighbors = np.copy(self._triangulation.neighbors) renum_neighbors = np.arange(ntri, dtype=np.int32) nadd = -1 while nadd != 0: # The active wavefront is the triangles from the border (unmasked # but with a least 1 neighbor equal to -1 wavefront = (np.min(valid_neighbors, axis=1) == -1) & ~current_mask # The element from the active wavefront will be masked if their # circle ratio is bad. added_mask = wavefront & mask_bad_ratio current_mask = added_mask | current_mask nadd = np.sum(added_mask) # now we have to update the tables valid_neighbors valid_neighbors[added_mask, :] = -1 renum_neighbors[added_mask] = -1 valid_neighbors = np.where(valid_neighbors == -1, -1, renum_neighbors[valid_neighbors]) return np.ma.filled(current_mask, True) def _get_compressed_triangulation(self): """ Compress (if masked) the encapsulated triangulation. Returns minimal-length triangles array (*compressed_triangles*) and coordinates arrays (*compressed_x*, *compressed_y*) that can still describe the unmasked triangles of the encapsulated triangulation. Returns ------- compressed_triangles : array-like the returned compressed triangulation triangles compressed_x : array-like the returned compressed triangulation 1st coordinate compressed_y : array-like the returned compressed triangulation 2nd coordinate tri_renum : int array renumbering table to translate the triangle numbers from the encapsulated triangulation into the new (compressed) renumbering. -1 for masked triangles (deleted from *compressed_triangles*). node_renum : int array renumbering table to translate the point numbers from the encapsulated triangulation into the new (compressed) renumbering. -1 for unused points (i.e. those deleted from *compressed_x* and *compressed_y*). """ # Valid triangles and renumbering tri_mask = self._triangulation.mask compressed_triangles = self._triangulation.get_masked_triangles() ntri = self._triangulation.triangles.shape[0] if tri_mask is not None: tri_renum = self._total_to_compress_renum(~tri_mask) else: tri_renum = np.arange(ntri, dtype=np.int32) # Valid nodes and renumbering valid_node = (np.bincount(np.ravel(compressed_triangles), minlength=self._triangulation.x.size) != 0) compressed_x = self._triangulation.x[valid_node] compressed_y = self._triangulation.y[valid_node] node_renum = self._total_to_compress_renum(valid_node) # Now renumbering the valid triangles nodes compressed_triangles = node_renum[compressed_triangles] return (compressed_triangles, compressed_x, compressed_y, tri_renum, node_renum) @staticmethod def _total_to_compress_renum(valid): """ Parameters ---------- valid : 1d bool array Validity mask. Returns ------- int array Array so that (`valid_array` being a compressed array based on a `masked_array` with mask ~*valid*): - For all i with valid[i] = True: valid_array[renum[i]] = masked_array[i] - For all i with valid[i] = False: renum[i] = -1 (invalid value) """ renum = np.full(np.size(valid), -1, dtype=np.int32) n_valid = np.sum(valid) renum[valid] = np.arange(n_valid, dtype=np.int32) return renum
def fetch_from_url(obj, url): plugins_cache_dir = obj["plugins_cache_dir"] force = obj["force"] _fetch_plugin_and_store_in_cache(url, plugins_cache_dir, force)
This is the second post in a group of tutorials on deploying Clojure applications on various cloud platforms. All posts in the series: Part 1: Google App Engine Part 2: Heroku All posts in the series: Heroku is a PaaS provider that supports multiple languages, including Clojure. Therefore, deploying a Clojure application to Heroku is a rather simple task. image: Heroku Prerequisites for this tutorial are: In this tutorial we will create a simple movie title search page and deploy it to Heroku. Build the application Let’s use the leiningen Heroku template to create a project structure. $ lein new heroku flowa-movie-search Pick any name you like as long as it is not flowa-movie-search since that one is already taken. ;) Now the project looks like this: ├── Procfile ├── project.clj ├── README.md ├── resources │ ├── 404.html │ └── 500.html ├── src │ └── flowa_movie_search │ └── web.clj └── test └── flowa_movie_search └── web_test.clj This is a structure for a basic ring/compujure application except for Procfile. It is a text file that tells Heroku which command to run on the server when deploying the application. In our case it looks like this: web: java $JVM_OPTS -cp target/flowa-movie-search-standalone.jar clojure.main -m flowa-movie-search.web This file declares a process type web . It means that the application will use the Heroku HTTP routing stack. Store the application in Git $ git init $ git add . $ git commit -m init Run and test locally $ lein run -m flowa-movie-search.web 7000 Now point your browser to localhost:7000 and you should see: [“Hello” :from Heroku] Code away! If you are only interested in dealing with Heroku, feel free to jump straight to deploying to Heroku. Now that we have everything in place, let’s do some coding. We will implement a simple search page where you can find movies by their title. We will use OMDBApi for the movie data. We will modify 3 clojure files. Two of these were created by the leiningen plugin: project.clj web.clj And one file we will create ourselves: layout.clj The file structure will look like this: ├── Procfile ├── project.clj ├── README.md ├── resources │ ├── 404.html │ ├── 500.html │ └── public │ └── bootstrap.min.css ├── src │ └── flowa_movie_search │ ├── views │ │ └── layout.clj │ └── web.clj └── test └── flowa_movie_search └── web_test.clj You may have noticed that a css file was also added. It is there only to make the outcome a bit prettier. Let’s take a look at the code. project.clj We’ll add two new dependencies. The templating library Hiccup and the HTTP client library clj-http respectively. [hiccup "1.0.5"] [clj-http "0.9.1"] web.clj Let’s modify the route definition first. (defroutes app (route/resources "/") (ANY "/repl" {:as req} (drawbridge req)) (GET "/" [] (layout/common (layout/search-page))) (POST "/" request (result-page request)) (ANY "*" [] (route/not-found (slurp (io/resource "404.html"))))) At line 2 we enable the serving of resources. The root directory defaults to public. Since our css file is in resources/public we are good. Then we replace the hello world in GET “/” route with a call to our implementation of the search page and add a new route POST “/”, which handles the user input. The form handler function result-page queries the OMDBApi with the user input and then passes the JSON results to the search page, which knows how to render them. (defn result-page [{:keys [form-params]}] (let [title (get form-params "search-string" "") fetch (fn [search-str] (client/get "http://www.omdbapi.com/" {:query-params {:s search-str} :accept :json :as :json})) render-result (fn [json] (layout/common (layout/search-page json)))] (render-result (:body (fetch title))))) layout.clj Here we implement the search page using the templating library Hiccup. Checkout the App Engine post for a more detailed explanation on Hiccup. (ns flowa-movie-search.views.layout (:require [hiccup.page :refer [html5 include-css]]) (:require [hiccup.form :refer [form-to]])) (defn- custom-input [type name placeholder] [:div [:input {:type type :name name :placeholder placeholder :style "float:left"}]]) (defn- submit-btn [text] [:button {:id "submit" :class "btn btn-primary"} text]) (defn- movie-list [{entries :Search}] [:div [:h4 "Found:"] (for [{title :Title year :Year} entries] [:div (str title " (" year ")")])]) (defn common [& body] (html5 [:head [:title "Flowa Heroku demo"] (include-css "bootstrap.min.css")] [:body body])) (defn search-page [& [results]] [:div [:div {:class "well"} [:h4 "The amazing Flowa movie search"] (form-to [:post "/"] (custom-input "text" "search-string" "Movie title") (submit-btn "Search"))] (if results (movie-list results))]) There are two “public” functions: common and search-page. The first one creates an HTML document from the content and the latter creates the form and shows the results if a results collection is given as an argument. The function movie-list iterates over the collection and creates an HTML representation for the data. The result JSON is represented as a Clojure map. OMDBApi uses the following format: {"Search": [{"Title":"FooTitle","Year":"1964","imdbID":"tt111111","Type":"movie"} {"Title":"BarTitle","Year":"1982","imdbID":"tt222222","Type":"movie"}]} Deploy to Heroku Create a new Heroku app $ heroku login Ie. login to heroku from the CLI. You will need to enter your Heroku credentials. Then let’s create the app. $ heroku apps:create flowa-movie-search Now the app should be listed on the web dashboard. This also adds a new remote repository (heroku) to your git config. You can check your git config at <repo-dir>/.git/config . Deploy If you haven’t already committed the changes to your local repository, now it’s time to do it. $ git add -A $ git commit Then we can push the code to the remote repository. $ git push heroku master Note that if you are working locally on a branch other than master use $ git push heroku your-branch:master Start a dyno In Heroku, apps are run in virtual containers called dynos. We need to ensure that there is at least one dyno running the process type web which we declared in our Procfile. $ heroku ps:scale web=1 Check the state of the app’s dyno: $ heroku ps Open the page in the browser $ heroku open …or point your browser at http://<your-app-name>.herokuapp.com. And that should do it! Happy hacking with Clojure and Heroku!
/** * The default {@link CacheKeyInvocationContext} implementation. * * @author Stephane Nicoll * @since 4.1 * @param <A> the annotation type */ class DefaultCacheKeyInvocationContext<A extends Annotation> extends DefaultCacheInvocationContext<A> implements CacheKeyInvocationContext<A> { private final CacheInvocationParameter[] keyParameters; @Nullable private final CacheInvocationParameter valueParameter; public DefaultCacheKeyInvocationContext(AbstractJCacheKeyOperation<A> operation, Object target, Object[] args) { super(operation, target, args); this.keyParameters = operation.getKeyParameters(args); if (operation instanceof CachePutOperation) { this.valueParameter = ((CachePutOperation) operation).getValueParameter(args); } else { this.valueParameter = null; } } @Override public CacheInvocationParameter[] getKeyParameters() { return this.keyParameters.clone(); } @Override @Nullable public CacheInvocationParameter getValueParameter() { return this.valueParameter; } }
<reponame>maniaclee/kver<filename>src/main/java/maniac/lee/kver/Config.java package maniac.lee.kver; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher; /** * Created by lipeng on 16/2/1. */ public class Config { public static void main(String[] args) throws Exception { String path = "/test_path"; CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("localhost:2181") .namespace("psyco") .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)) .connectionTimeoutMs(5000) .build(); // 启动 上面的namespace会作为一个最根的节点在使用时自动创建 client.start(); // 创建一个节点 client.create().forPath("/head", new byte[0]); // 异步地删除一个节点 // client.delete().inBackground().forPath("/head"); // 创建一个临时节点 client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child", new byte[0]); // 取数据 client.getData().watched().inBackground().forPath("/test"); // 检查路径是否存在 client.checkExists().forPath(path); // 异步删除 client.delete().inBackground().forPath("/head"); // 注册观察者,当节点变动时触发 client.getData().usingWatcher((Watcher) event -> { System.out.println("node is changed"); }).inBackground().forPath("/test"); // 结束使用 client.close(); } }
from modules import import_data as id from configparser import ConfigParser import os import sys from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler class ImportSettings(): """ Class which create file dev_import necessary to import data. Inside the file we have two unique cods for files dataset and entities. The codes change every time we change anything in the files dataset and entites. If the codes has been changed the program loads new data. More about th code : https://www.computerhope.com/unix/sha512sum.htm """ def __init__(self): self.path = './import/dev_import.ini' self.config = ConfigParser() self.config.read(self.path) if 'hashes' not in self.config.sections(): self.create() def create(self): self.config.add_section('hashes') self.config.set('hashes', 'dataset', "") self.config.set('hashes', 'date', "") def update(self, files): self.config['hashes']['dataset'] = self.get_hash(files) self.config['hashes']['date'] = str(datetime.now()) def save(self): with open(self.path, 'w+') as cnfFile: self.config.write(cnfFile) def get_hash(self, path): return os.popen(f"sha512sum {path}").read() \ .split(' ')[0] def is_dataset_changed(self, files): hash = self.get_hash(files) return self.config['hashes']['dataset'] != hash def is_empty(self): if self.config['hashes']['dataset']: return False return True def start_import(rdb): """ Import data from entities and dataset files""" files = [] directories = [] settings = ImportSettings() print('starting import', datetime.now().strftime('%H:%M:%S')) for r, d, f in os.walk('./import'): if d: directories = d for file in f: if '.xml' in file: files.append(file) if not files: print(files) return print("Could not import to database missing export file", file=sys.stderr) elif not settings.is_dataset_changed('./import/'+files[0]): return print("Data set not changed", file=sys.stderr) else: print(files) # use function from import_dataset to create tables in database print("Start import data") id.create_database_data(rdb) id.insert_data(rdb, files) id.load_ecg_data_to_database(rdb, directories) id.alter_tables(rdb) path = './import/' + files[0] settings.update(files=path) settings.save() print("End load data") class Scheduler(): """ BackgroundScheduler runs in a thread inside existing application. Importing data check the data. Import data every day at 05.05 if the program see any changes. """ def __init__(self, rdb, day_of_week, hour, minute): self.bgs = BackgroundScheduler() start_import(rdb) self.bgs.add_job(start_import, 'cron', [rdb], day_of_week=day_of_week, hour=hour, minute=minute) def start(self): self.bgs.start() def stop(self): print('exit scheduler') self.bgs.shutdown()
from scipy.special import softmax from memreps import memreps from memreps import explicit def test_experts(): summaries = [ {'∈': 0.4, '∉': 0.6}, {'≺': 0.3, '≻': 0.4, '=': 0.1, '||': 1} ] hist = { '∈': {'∈': 3, '∉': 4}, '≺': {'≺': 2, '≻': 3, '=': 7, '||': 0}, } advice = memreps.worst_case_smax(summaries, hist) assert advice.argmax() == 0 advice = memreps.worst_case_smax_comparable(summaries, hist) assert advice.argmax() == 1 advice = memreps.historical_smax(summaries, hist) assert advice.argmax() == 1 # Inflate frequency of incomparable. hist = { '∈': {'∈': 3, '∉': 4}, '≺': {'≺': 2, '≻': 3, '=': 1, '||': 100}, } advice = memreps.historical_smax(summaries, hist) assert advice.argmax() == 0 # Always membership. advice = memreps.EXPERTS[0](summaries, hist) assert advice == [1, 0] advice = memreps.EXPERTS[1](summaries, hist) assert advice == [0, 1] def test_query_selector(): gen_concepts = explicit.create_explicit_concept_class( universe = {1,2,3}, concepts = [set(), {2}, {1}, {1, 2}], ) assert len(list(gen_concepts())) == 4 selector = memreps.QuerySelector(gen_concepts, 10, 1) queries = [('∈', 1), ('≺', (1, 2))] assert selector.summarize(queries[0]) == {'∈': 1/2, '∉': 1/2} assert selector.summarize(queries[1]) == { '≺': 3/4, '≻': 3/4, '=': 1/2, '||': 1, } for _queries in [queries, queries, queries]: query = selector(_queries) assert query in _queries if query[0] == '∈': assert selector.loss_map == { '∈': (1/2 + 1) / 2, '∉': (1/2 + 1) / 2, } selector.update('∈') else: assert selector.loss_map == { '≺': (3/4 + 1/10)/2, '≻': (3/4 + 1/10)/2, '=': (1/2 + 1/10)/2, '||': (1 + 1/10)/2, } selector.update('≺')
/* Here to allow other parts of the shell (like the trap stuff) to freeze and unfreeze the jobs list. */ int freeze_jobs_list () { int o; o = jobs_list_frozen; jobs_list_frozen = 1; return o; }
# coding=utf-8 import ConfigParser import unittest import telegram import telegram_commands.cric as cric class TestCric(unittest.TestCase): def test_cric(self): keyConfig = ConfigParser.ConfigParser() keyConfig.read(["keys.ini", "..\keys.ini"]) bot = telegram.Telegram.Bot(keyConfig.get('Telegram', 'TELE_BOT_ID')) chatId = keyConfig.get('BotAdministration', 'TESTING_PRIVATE_CHAT_ID') cric.run(bot, chatId, 'Admin', keyConfig, '')
def obtain_attrs(self): if not self.all_attrs: all_attrs = list(self.private_data.columns) try: all_attrs.remove(self.config['identifier']) except: pass self.all_attrs = all_attrs return self.all_attrs
// given values for a day, month and year, return if they represent a valid date public static boolean validateDateValues(String rawDay, String rawMonth, String rawYear) { try { int day = Integer.parseInt(rawDay); int month = Integer.parseInt(rawMonth) - 1; int year = Integer.parseInt(rawYear); Calendar calendar = Calendar.getInstance(); calendar.setLenient(false); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.YEAR, year); try { calendar.getTime(); return true; } catch (Exception e) { return false; } } catch(NumberFormatException e) { return false; } }
Gene-Targeted Deletion of Neurofibromin Enhances the Expression of a Transient Outward K+ Current in Schwann Cells: A Protein Kinase A-Mediated Mechanism Mutations in the neurofibromatosis type 1 gene predispose patients to develop benign peripheral nerve tumors (neurofibromas) containing Schwann cells (SCs). SCs from neurofibromatosis type-1 gene (Nf1) null mutant mice showed increased levels of Ras-GTP and cAMP. The proliferation and differentiation of SCs are regulated by Ras-GTP and cAMP-mediated signaling, which have been linked to expression of K+ channels. We investigated the differential expression of K+ currents inNf1 null mutant SCs (Nf1−/−) and their wild-type (Nf1+/+) counterparts and determined the mechanisms underlying the differences. The current densities of the sustained component of K+ currents were similar in the two genotypes. However, Nf1−/− SCs showed a significant increase (∼1.5-fold) in a 4-aminopyridine-sensitive transient outward K+ current (IA). Nonstationary fluctuation analysis revealed a significant increase in the number of functional channels in the null mutant cells. When the involvement of the Ras pathway in the modulation of the K+ current was examined using adenoviral-mediated gene transfer of a dominant-negative H-Ras N17 or the known H-Ras inhibitor (L-739,749), an additional increase in IA was observed. In contrast, protein kinase A (PKA) inhibitors, H89 and attenuated the enhancement of the current in theNf1−/− cells, suggesting that the increase inIA was mediated via activation of protein kinase A. The unitary conductance of the channel underlyingIA was unaltered by inhibitors of PKA. Activation of IA is thus negatively regulated by Ras-GTP and positively regulated by PKA.
<filename>helper/helper.py import re import os, sys import json import csv import shutil import ctypes import logging import datetime import fileinput import subprocess import xml.etree.ElementTree as etree DEFAULT_HELPER_PATH = "helper" class Logger(object): def __init__(self): """Init method """ self.terminal = sys.stdout self.log = open("image-gen-logfile.log", "a") def write(self, message): """Writes a log message :param message: :return: """ now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S - ') self.terminal.write(message) self.log.write(message) def flush(self): """Flushes a log message :return: """ # this flush method is needed for python 3 compatibility. # this handles the flush command by doing nothing. pass class helper(object): @staticmethod def executable_in_path(executable): '''Returns the full path to an executable according to PATH, otherwise None.''' if os.name == 'nt': return shutil.which('packer') else: path = os.environ.get('PATH') if not path: print >> sys.stderr, "Warning: No PATH could be searched" paths = path.split(':') for path in paths: fullpath = os.path.join(path, executable) if os.path.isfile(fullpath) and os.access(fullpath, os.X_OK): return fullpath return None @staticmethod def validate_argtype(arg, argtype): """Validates argument against given type :param arg: :param argtype: :return: """ if not isinstance(arg, argtype): raise HelperException('{0} argument must be of type {1}'.format( arg, argtype)) return arg @staticmethod def get_guestos(os_string, os_arch, vm_provider): """Returns guest os type for a specific provider :param os_string: :param os_arch: :param vm_provider: :return: """ if "linux" in os_string.lower(): guestos = re.sub(r'\W+', ' ', re.sub(r'\d+', ' ', os_string)).strip() if "windows" in os_string.lower(): guestos = os_string if os_arch == '64': guestos = guestos + "_" + str(os_arch) guestos = guestos.replace(" ", "_") data = "" try: guest_os_file = os.path.join(DEFAULT_HELPER_PATH, (vm_provider.lower() + '-guestos.json')) with open(guest_os_file) as data_file: data = json.load(data_file) except (OSError, IOError) as ex: print("error in opening packer template json file") logging.error(ex.message) print(str(ex.message)) assert isinstance(data, object) if guestos in data: return data[guestos] elif "windows" in guestos.lower(): if os_arch == 32: return data['Windows'] else: return data['Windows_64'] elif "linux" in guestos.lower(): if os_arch == 32: return data['Linux'] else: return data['Linux_64'] @staticmethod def run(cmd): """Runs a command :param cmd: Command :return: Execution status """ try: ''' p = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in iter(p.stdout.readline, ''): print(line) retval = p.wait() return retval ''' p = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) for line in iter(p.stdout.readline, b''): print(line.rstrip().decode('utf-8')), p.stdout.close() p.wait() #print(cmd) #p = subprocess.run(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #print('returncode:', p.returncode) #print('{}'.format(p.stdout.decode('utf-8'))) except (subprocess.CalledProcessError, KeyboardInterrupt) as e: print("Received keyboard interrupt, terminating the build process...") ''' """kill function for Win32""" kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, p.pid) return (0 != kernel32.TerminateProcess(handle, 0)) logging.error("Error occured while running command {0}, Error: {1}".format(cmd, e.message)) raise subprocess.CalledProcessError ''' @staticmethod def SearchReplaceInFile(file, searchpattern, replacewith): """ :param file: :param searchpattern: :param replacewith: :return: """ for line in fileinput.input(file, inplace=1): if searchpattern in line: line = line.replace(searchpattern, replacewith) sys.stdout.write(line) fileinput.close() @staticmethod def get_productkey(_dbms_query): """ :param _dbms_query: :return: """ return " " class HelperException(Exception): """Custom helper exception """ pass
Human milk feeding protects very low-birth-weight infants from retinopathy of prematurity: a pre–post cohort analysis Abstract Objectives: To examine the effect of early human milk (HM) feeding on the incidence of retinopathy of prematurity (ROP) among very low-birth-weight (VLBW) infants. Methods: Observational cohort research in a Level III neonatal intensive care unit. A total of 186 infants were enrolled in this pre–post cohort study (114 infants were included in the HM-fed group and 72 in the formula-fed group). ROP, type of feeding (early exclusive HM versus any formula), and potential confounding variables were measured. Differences between groups were explored. Results: The clinical characteristics of the neonates did not differ between the two groups. By bivariate analysis, HM feeding was associated with 75% lower odds of Stage 2 or 3 ROP (OR = 0.25, 95% CI: 0.091 to 0.705; p = 0.009) At multivariate logistic regression, type of milk feeding retained significance, exclusive HM being protective with p = 0.002. Conclusions: This study found an association between early exposure to formula in VLBW infants and ROP. An initial HM diet, devoid of cow milk-containing products before achieving full enteral feeding, may help prevent ROP.
def sync_results_to_new_location(self, worker_ip): if worker_ip != self._log_syncer.worker_ip: logger.info("Syncing (blocking) results to {}".format(worker_ip)) self._log_syncer.reset() self._log_syncer.set_worker_ip(worker_ip) self._log_syncer.sync_up() self._log_syncer.wait()
<gh_stars>0 package qj import ( "github.com/garyburd/redigo/redis" "log" "net/url" "os" "strings" "time" ) type settings struct { namespace string Pool *redis.Pool } var Settings *settings var managers = make(map[string]*manager) var Logger = log.New(os.Stdout, "=> ", log.Ldate|log.Lmicroseconds) func Setup(uri string, namespace string, size int) { Settings = &settings{ namespace, NewRedisPool(uri, size), } } func NewRedisPool(uri string, size int) *redis.Pool { u, err := url.Parse(uri) if err != nil { panic(err) } var password string = "" if u.User != nil { password, _ = u.User.Password() } var db string = "" if u.Path != "" { db = strings.Replace(u.Path, "/", "", 1) } return &redis.Pool{ MaxIdle: size, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", u.Host) if err != nil { return nil, err } if password != "" { if _, err := c.Do("AUTH", password); err != nil { c.Close() return nil, err } } if db != "" { if _, err := c.Do("SELECT", db); err != nil { c.Close() return nil, err } } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } } func KeyName(key string) string { return Settings.namespace + ":" + key } func Workers(queue string, task Task, concurrency int) { managers[queue] = NewManager(queue, task, concurrency) } func Start() { for _, manager := range managers { manager.start() } WaitWorkers() }
#include<bits/stdc++.h> using namespace std; #define MAXSIZE 1000000 #define DIV 1000000007 long long frac[MAXSIZE]; long long inv[MAXSIZE]; long long mypow(long long x, long long n){ long long ret=1,p,l=1,p2=1; p=x; while(1){ if(n&p2) ret*=p; p*=p; ret%=DIV; p%=DIV; p2*=2; if(p2>n) break; } return ret; } void nCk_init(){ //cout << "nCk_init start\n"; frac[0]=1; inv[0]=1; for(int i=1; i<MAXSIZE; i++){ frac[i]=(long long)frac[i-1]*i; frac[i]%=DIV; inv[i]=mypow(frac[i],DIV-2); inv[i]%=DIV; } //cout << "nCk_init finished\n"; } long long nCk(long long n,long long k){ //printf("nCk(%d,%d) start\n",n,k); long long ret; ret = frac[n]; ret = ((long long)ret*inv[n-k])%DIV; ret = ((long long)ret*inv[k])%DIV; return ret; //cout << "nCk finished\n"; } long long nHk(long long n,long long k){ return nCk(n+k-1,n-1); } int main(){ nCk_init(); long long n,k,ans=0; cin >> n >> k; if(n<k) k=n-1; for(long long m=k; m>=0; m--){ ans += ((long long)nCk(n,m)*nHk(n-m,m)); ans %=DIV; } cout << ans; return 0; }
Pitch-catch UGW-based multiple damage inference: a heterogeneous graph interpretation Ultrasonic guided waves (UGWs) have been extensively utilized in nondestructive testing and structural health monitoring (SHM) for detection and real-time monitoring of structural defects. By implementing multiple piezoelectric sensors onto a plane of the target structure to form a sensor network, damages within the sensing range can be detected or even visualized through a pitch-catch configuration. On the other hand, deep learning (DL) techniques have recently been widely used to aid UGW-based SHM when the waveform is over complicated to extract a specific mode of interest due to irregular structure or boundary reflections. However, not too much research work has been conducted to thoroughly combine sensor networks with DL. Existing research using DL approaches is mainly used to train and interpret waveforms from isolated sensor pairs. The topological structure of sensor layout and sensor-damage relative positions are hardly considered in the data-driven process. Motivated by these concerns, this study offers a first-of-its-kind perspective to interpret UGW data collected from a sensor network by mapping the physical sensor-damage layout into a graph, in which sensors and potential damages serve as graph vertices bearing heterogenous properties upon coming to UGWs and the process of UGW transmission between sensors are encapsulated as wavelike message passing between the vertices. A novel physics-informed end-to-end graph neural network model, named as WaveNet, was exquisitely and meticulously developed. By utilizing wave information and topological structure, WaveNet enables inference of multiple damages in terms of severity and location with satisfactory accuracy, even when the waveforms are chaotic, and the sensor arrangement is different at the training and testing stages. More importantly, beyond the SHM scenario, the present study is expected to enlighten new thinking on interconnecting physical wave propagation with virtual messaging passing in neural networks.
<filename>dm/dm.py # -*- encoding: utf-8 -*- import discord from discord.ext import commands from .utils import checks class Annoying: """Adds usefull custom crap""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) @checks.serverowner_or_permissions(administrator=True) async def spam(self, ctx, amount: int, *, message: str): """Spams in same channel {0} For number {1} for total {2} For amount left""" text = message try: await self.bot.add_reaction(ctx.message, "✔") await self.bot.delete_message(ctx.message) except: pass number = 0 while (number < amount): number = number + 1 await self.bot.send_message(ctx.message.channel, text.format(number, amount-number)) @commands.command(pass_context=True) @checks.serverowner_or_permissions(administrator=True) async def dspam(self, ctx, amount: int, *, message: str): """Spams then deletes the messages. Useful for pinging people. {0} For number {1} for total {2} For amount left""" text = message try: await self.bot.add_reaction(ctx.message, "✔") await self.bot.delete_message(ctx.message) except: pass number = 0 while (number < amount): number = number + 1 message = await self.bot.send_message(ctx.message.channel, text.format(number, amount, amount-number)) await self.bot.delete_message(message) @commands.command(pass_context=True) @checks.is_owner() async def dm(self, ctx, user: discord.User, *, message: str): """DMs a user""" await self.bot.send_message(user, "{} ".format(message)) try: await self.bot.add_reaction(ctx.message, "✔") await self.bot.delete_message(ctx.message) except: pass @commands.command(pass_context=True) @checks.is_owner() async def dmspam(self, ctx, user: discord.User, amount: int, *, message: str): """Spams DMs to a user. {0} For number {1} for total {2} For amount left""" try: await self.bot.add_reaction(ctx.message, "✔") await self.bot.delete_message(ctx.message) except: pass number = 0 while (number < amount): number = number + 1 await self.bot.send_message(user, message.format(number, amount, amount-number)) @commands.command(pass_context=True) @checks.is_owner() async def ddmspam(self, ctx, user: discord.User, amount: int, *, message: str): """Spams then delets DMs to a user. {0} For number {1} for total {2} For amount left""" text = message try: await self.bot.add_reaction(ctx.message, "✔") await self.bot.delete_message(ctx.message) except: pass number = 0 while (number < amount): number = number + 1 message = await self.bot.send_message(user, text.format(number, amount, amount-number)) await self.bot.delete_message(message) async def on_message(self, message): if message.channel.is_private: author = message.author if author.bot: return owner = discord.utils.get(self.bot.get_all_members(), id=self.bot.settings.owner) if author == owner: return description = "dm " + author.id + " <msg>" colour = discord.Colour.red() footer = "Sent by {} ({})".format(author, author.id) e = discord.Embed(colour=colour, description=message.content) if author.avatar_url: e.set_author(name=description, icon_url=author.avatar_url) else: e.set_author(name=description) e.set_footer(text=footer) ##await self.bot.send_message(, "{} ({}) said:\n{}".format(author, author.id, message.content)) await self.bot.send_message(owner, embed=e) def setup(bot): bot.add_cog(Annoying(bot))
import { DataFactory, Store } from 'n3'; import type { AccessCheckerArgs } from '../../../../src/authorization/access/AccessChecker'; import { AgentGroupAccessChecker } from '../../../../src/authorization/access/AgentGroupAccessChecker'; import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation'; import type { Representation } from '../../../../src/http/representation/Representation'; import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes'; import * as fetchUtil from '../../../../src/util/FetchUtil'; import { ACL, VCARD } from '../../../../src/util/Vocabularies'; const { namedNode, quad } = DataFactory; describe('An AgentGroupAccessChecker', (): void => { const webId = 'http://test.com/alice/profile/card#me'; const groupId = 'http://test.com/group'; const acl = new Store(); acl.addQuad(namedNode('groupMatch'), ACL.terms.agentGroup, namedNode(groupId)); acl.addQuad(namedNode('noMatch'), ACL.terms.agentGroup, namedNode('badGroup')); let fetchMock: jest.SpyInstance; let representation: Representation; let checker: AgentGroupAccessChecker; beforeEach(async(): Promise<void> => { const groupQuads = [ quad(namedNode(groupId), VCARD.terms.hasMember, namedNode(webId)) ]; representation = new BasicRepresentation(groupQuads, INTERNAL_QUADS, false); fetchMock = jest.spyOn(fetchUtil, 'fetchDataset'); fetchMock.mockResolvedValue(representation); fetchMock.mockClear(); checker = new AgentGroupAccessChecker(); }); it('can handle all requests.', async(): Promise<void> => { await expect(checker.canHandle(null as any)).resolves.toBeUndefined(); }); it('returns true if the WebID is a valid group member.', async(): Promise<void> => { const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credentials: { agent: { webId }}}; await expect(checker.handle(input)).resolves.toBe(true); }); it('returns false if the WebID is not a valid group member.', async(): Promise<void> => { const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credentials: { agent: { webId }}}; await expect(checker.handle(input)).resolves.toBe(false); }); it('returns false if there are no WebID credentials.', async(): Promise<void> => { const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credentials: {}}; await expect(checker.handle(input)).resolves.toBe(false); }); });
There is speculation that ace director Woody Allen has reportedly fired Bruce Willis from his new multi-starrer, yet-untitled movie, according to a report. Willis was the first actor chosen by Allen to cast in the film, which also stars Blake Lively, Parker Posey, Kristen Stewart, Jesse Eisenberg, Jeannie Berlin, Corey Stoll, Ken Stott, Anna Camp, Stephen Kunken, Sari Lennick and Paul Schneider, Deadline reported, adding that Willis' exit from the film was confirmed by Allen's team. Willis had to quit Allen's film because his schedule with Allen was conflicting with his other work. The “Die Hard” actor is working on the Broadway stage adaptation of Stephen King bestseller and movie, “Misery.” The report also added that Allen is now looking to recast another actor soon to fill in Willis' shoes. The news also went viral on Twitter. “He got fired so don't hold your breath...,” film reporter Jeff Sneider wrote on Twitter while talking about Willis. “‪@TheInSneider‪ Yep. Fired. A friend is on the film. Bruce couldn't remember a line. Cue cards were no help. Cast were losing their minds,” wrote another Twitter user Tom O'Leary. Meawnhile, various websites, including Tom and Lorenzo, published pictures of the actor working on the set of Allen's movie in Beverly Hills. However, the news of Willis getting fired should not come as a surprise because Allen has fired actors in the past too, even after shooting half of the film with them. Allen replaced actor Michael Keaton by Jeff Daniels after he shot for ten days with Allen for his movie, “The Purple Rose Of Cairo.” Actress Juliette Lewis replaced Emily Lloyd in “Husbands and Wives” after Lewis shot a couple of scenes in the film. Willis too does not enjoy a good reputation as an actor. Director Kevin Smith, who worked with the actor in “Cop Out,” said working with Willis was an unpleasant experience, Business Insider reported.
import os import pandas as pd from base import BaseFeature from encoding_func import target_encoding from google.cloud import storage, bigquery from google.cloud import bigquery_storage_v1beta1 class CountEncodingPresentDomains(BaseFeature): def import_columns(self): return [ "tweet_id", "engaging_user_id" ] def _read_present_domains_count_from_bigquery( self, train_table_name: str, test_table_name) -> pd.DataFrame: self._logger.info(f"Reading from {train_table_name} and {test_table_name}") query = """ WITH subset AS ( ( SELECT tweet_id, any_value(present_domains) AS present_domains FROM {} GROUP BY tweet_id ) UNION ALL ( SELECT tweet_id, any_value(present_domains) AS present_domains FROM {} GROUP BY tweet_id ) ) , unnest_subset AS ( SELECT tweet_id, present_domain FROM subset, unnest(present_domains) AS present_domain ) , count_present_domain AS ( SELECT present_domain, COUNT(*) AS cnt FROM unnest_subset GROUP BY present_domain ) SELECT tweet_id, AVG(cnt) AS mean_value, min(cnt) AS min_value, max(cnt) AS max_value, case when stddev(cnt) is null then 1 else stddev(cnt) end AS std_value FROM ( SELECT A.tweet_id, A.present_domain, B.cnt FROM unnest_subset AS A LEFT OUTER JOIN count_present_domain AS B ON A.present_domain = B.present_domain ) GROUP BY tweet_id """.format(train_table_name, test_table_name) if self.debugging: query += " limit 10000" bqclient = bigquery.Client(project=self.PROJECT_ID) bqstorageclient = bigquery_storage_v1beta1.BigQueryStorageClient() df = ( bqclient.query(query) .result() .to_dataframe(bqstorage_client=bqstorageclient) ) return df def make_features(self, df_train_input, df_test_input): # read unnested present_media count_present_domains = self._read_present_domains_count_from_bigquery( self.train_table, self.test_table ) feature_names = ["mean_value", "max_value", "min_value", "std_value"] print(count_present_domains.shape) print(count_present_domains.isnull().sum()) df_train_features = pd.DataFrame() df_test_features = pd.DataFrame() df_train_input = pd.merge(df_train_input, count_present_domains, on="tweet_id", how="left").fillna(0) df_test_input = pd.merge(df_test_input, count_present_domains, on="tweet_id", how="left").fillna(0) for fe in feature_names: df_train_features[fe] = df_train_input[fe].values df_test_features[fe] = df_test_input[fe].values print(df_train_features.isnull().sum()) print(df_test_features.isnull().sum()) return df_train_features, df_test_features if __name__ == "__main__": CountEncodingPresentDomains.main()
//+----------------------------------------------------------------------------- // // CDXTRadialWipeBase::_ScanlineIntervals // // A helper method that calculates the transition boundaries between the // two image regions on a scanline. Based on the type of transform, the scanline // consists of a series of alternating A and B image sections. The upper X // bound of each section is calculated and saved in array XBounds. The number // of useful entries in XBounds is variable. The end of array is determined // when one entry equals to the scanline (image) width. It is assumed that // XBounds[0] is the upper bound of the first A section. So if the scanline // starts with a B section, XBounds[0] will be 0. // // Example 1: scanline length = 16, first section is from A image // // AAAABBBBBAAABBAA XBounds should contain {4, 9, 12, 14, 16}. // // Example 2: scanline length = 16, first section is from B image // // BBBAAAAAABBBBBBB XBounds should contain {0, 3, 9, 16}. // // // Note: It is possible that some section has length 0 (i.e. two adjacent // bounds equal). {3, 9, 9, 16} is equivalent to {3, 16}. // // Parameters: // // width, height: width and height of both images. // XEdge, YEdge: coordinates of the intersection point of a ray with the image boundary // fProg: progress value from 0.0 to 1.0 // YScanline: Y cooridnate (height) of the current scanline // XBounds: array to hold the computed X bounds on return. // // // Created by: PhilLu 06/22/98 // //------------------------------------------------------------------------------ void CDXTRadialWipeBase::_ScanlineIntervals(long width, long height, long XEdge, long YEdge, float fProg, long YScanline, long *XBounds) { long CenterX, CenterY; CenterX = width/2; CenterY = height/2; switch(m_eWipeStyle) { case CRRWS_CLOCK: if (YEdge >= CenterY) { if (YScanline <= CenterY) { XBounds[0] = CenterX; XBounds[1] = width; } else if (YScanline <= YEdge) { XBounds[0] = CenterX + (XEdge-CenterX)*(YScanline-CenterY)/(YEdge-CenterY); XBounds[1] = width; } else if (XEdge < CenterX) { XBounds[0] = 0; XBounds[1] = width; } else { XBounds[0] = width; } } else if (XEdge < CenterX) { if (YScanline < YEdge) { XBounds[0] = CenterX; XBounds[1] = width; } else if (YScanline <= CenterY) { XBounds[0] = 0; XBounds[1] = CenterX + (XEdge-CenterX)*(YScanline-CenterY)/(YEdge-CenterY); XBounds[2] = CenterX; XBounds[3] = width; } else { XBounds[0] = 0; XBounds[1] = width; } } else { if (YScanline < YEdge) { XBounds[0] = CenterX; XBounds[1] = width; } else if (YScanline <= CenterY) { XBounds[0] = CenterX; XBounds[1] = CenterX + (XEdge-CenterX)*(YScanline-CenterY)/(YEdge-CenterY); XBounds[2] = width; } else { XBounds[0] = width; } } if (fProg == 0.0) { XBounds[0] = width; } else if(fProg == 1.0) { XBounds[0] = 0; XBounds[1] = width; } break; case CRRWS_WEDGE: if (YEdge >= CenterY) { if (YScanline <= CenterY) { XBounds[0] = 0; XBounds[1] = width; } else if (YScanline <= YEdge) { long deltaX = (XEdge-CenterX)*(YScanline-CenterY)/(YEdge-CenterY); XBounds[0] = 0; XBounds[1] = CenterX - deltaX; XBounds[2] = CenterX + deltaX; XBounds[3] = width; } else { XBounds[0] = width; } } else { if (YScanline < YEdge) { XBounds[0] = 0; XBounds[1] = width; } else if (YScanline <= CenterY) { long deltaX = (XEdge-CenterX)*(YScanline-CenterY)/(YEdge-CenterY); XBounds[0] = CenterX - deltaX; XBounds[1] = CenterX + deltaX; XBounds[2] = width; } else { XBounds[0] = width; } } break; case CRRWS_RADIAL: if (YScanline <= YEdge && YEdge > 0) { XBounds[0] = YScanline*XEdge/YEdge; XBounds[1] = width; } else { XBounds[0] = width; } break; default: _ASSERT(0); break; } }
<gh_stars>0 import IMongooseModel from './IMongooseModel'; import { IHttpActionModel } from '../../model/interfaces/IHttpActionModel'; export interface IHttpActionSchemaMongooseModel extends IMongooseModel, IHttpActionModel { }
def adjust_gain(self, gain): if self.signal is not None: return self.signal.adjust_gain(gain) return None
/** * enumeration of possible federate states */ public final class helics_federate_state { /** * when created the federate is in startup state */ public final static helics_federate_state helics_state_startup = new helics_federate_state("helics_state_startup", helicsJNI.helics_state_startup_get()); /** * entered after the enterInitializingMode call has returned */ public final static helics_federate_state helics_state_initialization = new helics_federate_state("helics_state_initialization", helicsJNI.helics_state_initialization_get()); /** * entered after the enterExectuationState call has returned */ public final static helics_federate_state helics_state_execution = new helics_federate_state("helics_state_execution", helicsJNI.helics_state_execution_get()); /** * the federate has finished executing normally final values may be retrieved */ public final static helics_federate_state helics_state_finalize = new helics_federate_state("helics_state_finalize", helicsJNI.helics_state_finalize_get()); /** * error state no core communication is possible but values can be retrieved */ public final static helics_federate_state helics_state_error = new helics_federate_state("helics_state_error", helicsJNI.helics_state_error_get()); /** * indicator that the federate is pending entry to initialization state */ public final static helics_federate_state helics_state_pending_init = new helics_federate_state("helics_state_pending_init", helicsJNI.helics_state_pending_init_get()); /** * state pending EnterExecution State */ public final static helics_federate_state helics_state_pending_exec = new helics_federate_state("helics_state_pending_exec", helicsJNI.helics_state_pending_exec_get()); /** * state that the federate is pending a timeRequest */ public final static helics_federate_state helics_state_pending_time = new helics_federate_state("helics_state_pending_time", helicsJNI.helics_state_pending_time_get()); /** * state that the federate is pending an iterative time request */ public final static helics_federate_state helics_state_pending_iterative_time = new helics_federate_state("helics_state_pending_iterative_time", helicsJNI.helics_state_pending_iterative_time_get()); /** * state that the federate is pending a finalize request */ public final static helics_federate_state helics_state_pending_finalize = new helics_federate_state("helics_state_pending_finalize", helicsJNI.helics_state_pending_finalize_get()); /** * state that the federate is finished simulating but still connected */ public final static helics_federate_state helics_state_finished = new helics_federate_state("helics_state_finished", helicsJNI.helics_state_finished_get()); public final int swigValue() { return swigValue; } public String toString() { return swigName; } public static helics_federate_state swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + helics_federate_state.class + " with value " + swigValue); } private helics_federate_state(String swigName) { this.swigName = swigName; this.swigValue = swigNext++; } private helics_federate_state(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; swigNext = swigValue+1; } private helics_federate_state(String swigName, helics_federate_state swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; swigNext = this.swigValue+1; } private static helics_federate_state[] swigValues = { helics_state_startup, helics_state_initialization, helics_state_execution, helics_state_finalize, helics_state_error, helics_state_pending_init, helics_state_pending_exec, helics_state_pending_time, helics_state_pending_iterative_time, helics_state_pending_finalize, helics_state_finished }; private static int swigNext = 0; private final int swigValue; private final String swigName; }
// BootstrapNetwork with HTTP p2p functionality func BootstrapNetwork(logger logrus.FieldLogger, genesisURL strfmt.URI, publicURL strfmt.URI, peerName string) (libnetwork.Network, error) { if genesisURL == "" { return nil, fmt.Errorf("No genesis URL provided in network configuration") } genesisURI, err := url.Parse(string(genesisURL)) if err != nil { return nil, fmt.Errorf("Could not parse genesis URL '%v'", genesisURL) } if publicURL == "" { return nil, fmt.Errorf("No public URL provided in network configuration") } _, err = url.Parse(string(publicURL)) if err != nil { return nil, fmt.Errorf("Could not parse public URL '%v'", publicURL) } if peerName == "" { return nil, fmt.Errorf("No peer name specified in network configuration") } transportConfig := genesis_client.TransportConfig{ Host: genesisURI.Host, BasePath: genesisURI.Path, Schemes: []string{genesisURI.Scheme}, } client := genesis_client.NewHTTPClientWithConfig(nil, &transportConfig) n := network{ publicURL: publicURL, peerName: peerName, state: NETWORK_STATE_BOOTSTRAPPING, genesisURL: genesisURL, logger: logger, client: *client, peers: make([]peers.Peer, 0), downloadChanged: p2pschema.DownloadChanged, } go n.bootstrap() return &n, nil }
/* All modification made by Intel Corporation: © 2016 Intel Corporation All contributions by the University of California: Copyright (c) 2014, 2015, The Regents of the University of California (Regents) All rights reserved. All other contributions: Copyright (c) 2014, 2015, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CAFFE_CONV_LAYER_HPP_ #define CAFFE_CONV_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/base_conv_layer.hpp" namespace caffe { /** * @brief Convolves the input image with a bank of learned filters, * and (optionally) adds biases. * * Caffe convolves by reduction to matrix multiplication. This achieves * high-throughput and generality of input and filter dimensions but comes at * the cost of memory for matrices. This makes use of efficiency in BLAS. * * The input is "im2col" transformed to a channel K' x H x W data matrix * for multiplication with the N x K' x H x W filter matrix to yield a * N' x H x W output matrix that is then "col2im" restored. K' is the * input channel * kernel height * kernel width dimension of the unrolled * inputs so that the im2col matrix has a column for each input region to * be filtered. col2im restores the output spatial structure by rolling up * the output channel N' columns of the output matrix. */ template <typename Dtype> class ConvolutionLayer : public BaseConvolutionLayer<Dtype> { public: /** * @param param provides ConvolutionParameter convolution_param, * with ConvolutionLayer options: * - num_output. The number of filters. * - kernel_size / kernel_h / kernel_w. The filter dimensions, given by * kernel_size for square filters or kernel_h and kernel_w for rectangular * filters. * - stride / stride_h / stride_w (\b optional, default 1). The filter * stride, given by stride_size for equal dimensions or stride_h and stride_w * for different strides. By default the convolution is dense with stride 1. * - pad / pad_h / pad_w (\b optional, default 0). The zero-padding for * convolution, given by pad for equal dimensions or pad_h and pad_w for * different padding. Input padding is computed implicitly instead of * actually padding. * - dilation (\b optional, default 1). The filter * dilation, given by dilation_size for equal dimensions for different * dilation. By default the convolution has dilation 1. * - group (\b optional, default 1). The number of filter groups. Group * convolution is a method for reducing parameterization by selectively * connecting input and output channels. The input and output channel dimensions must be divisible * by the number of groups. For group @f$ \geq 1 @f$, the * convolutional filters' input and output channels are separated s.t. each * group takes 1 / group of the input channels and makes 1 / group of the * output channels. Concretely 4 input channels, 8 output channels, and * 2 groups separate input channels 1-2 and output channels 1-4 into the * first group and input channels 3-4 and output channels 5-8 into the second * group. * - bias_term (\b optional, default true). Whether to have a bias. * - engine: convolution has CAFFE (matrix multiplication) and CUDNN (library * kernels + stream parallelism) engines. */ explicit ConvolutionLayer(const LayerParameter& param) : BaseConvolutionLayer<Dtype>(param) {} virtual inline const char* type() const { return "Convolution"; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual inline bool reverse_dimensions() { return false; } virtual void compute_output_shape(); }; } // namespace caffe #endif // CAFFE_CONV_LAYER_HPP_
<gh_stars>0 from sls.completion.item import CompletionItem from sls.document import Position, Range, TextEdit from sls.spec import CompletionItemKind, MarkupKind from .action import Action from .command import Command class Service(CompletionItem): """ An individual service """ def __init__(self, name, description, actions, commands, readme): self._name = name self._description = description self._actions = actions self._commands = commands self._readme = readme @classmethod def from_hub(cls, service_name, model): actions = {} if 'actions' in model.configuration: for name, action in model.configuration['actions'].items(): actions[name] = Action.from_hub(name, action) commands = {} if 'commands' in model.configuration: for name, action in model.configuration['commands'].items(): commands[name] = Command.from_hub(name, action) return cls( name=service_name, description=model.description, actions=actions, commands=commands, readme=model.readme, ) def name(self): return self._name def description(self): return self._description def actions(self): return self._actions.values() def action(self, action): return self._actions.get(action, None) def commands(self): return self._commands.values() def command(self, command): return self._commands.get(command, None) def to_completion(self, context): start = Position( line=context.pos.line, character=context.pos.char - len(context.word), ) end = Position( line=context.pos.line, character=context.pos.char, ) return self.completion_build( label=self.name(), detail=self.description(), text_edit=TextEdit(Range(start, end), f'{self.name()} '), documentation=self._readme, documentation_kind=MarkupKind.Markdown, completion_kind=CompletionItemKind.Method, context=context, )
// Start starts running the subscription. It can be stopped with context cancellation. func (w *PostgresWatcher) Start(ctx context.Context) error { w.log.Debug("Starting Watch") isInRecovery, err := w.conn.IsInRecovery(ctx) if isInRecovery { return markTemporaryError(errors.New("database is in recovery mode")) } if err != nil { return wrapError(err) } var snapshotName string slotLSN, snapshotName, err := w.conn.GetReplicationSlot(w.conf.Slot) if err != nil { return wrapError(errors.Wrap(err, "error getting replication slot")) } w.log.WithFields(logrus.Fields{ "consistentPoint": slotLSN, "snapshotName: ": snapshotName, }).Debug("Got replication slot") w.lsnCounter.updateReceivedLSN(slotLSN) if err := w.dumpIfShould(ctx, snapshotName); err != nil { return wrapError(err) } w.lsnCounter.txnFinished(slotLSN) if err := w.conn.StartReplication(w.conf.Slot, w.conf.Publication, 0); err != nil { return wrapError(errors.Wrap(err, "failed to start replication")) } return wrapError(w.runMessageProducer(ctx)) }
<filename>handler/service.go package handler import ( "context" "encoding/json" "github.com/paulvasilenko/nats-http-adapter/nats" "github.com/pkg/errors" ) type Service struct { NATS nats.Conn } type NATSMessage struct { Subject string `json:"subject"` Type string `json:"type"` Data json.RawMessage `json:"data"` } type NATSResult struct { Data interface{} `json:"data"` } func (s *Service) SendNATSMessage(ctx context.Context, m *NATSMessage) (*NATSResult, error) { if m.Subject == "" { return nil, BadRequest("subject is missing") } resp, err := s.NATS.SendNATSMessage(ctx, nats.SendNatsMessageParams{ Type: m.Type, Subject: m.Subject, Data: m.Data, }) if err != nil { if errors.Cause(err) == nats.ErrUnknownMessageType { return nil, BadRequest(err.Error()) } return nil, err } if len(resp) < 0 { return nil, nil } if json.Valid(resp) { return &NATSResult{ Data: json.RawMessage(resp), }, nil } return &NATSResult{ Data: string(resp), }, nil }
Reproducibility and variability of digital thermal monitoring of vascular reactivity Background:  Previous studies demonstrated that digital thermal monitoring (DTM) of vascular reactivity, a new test for vascular function assessment, is well correlated with Framingham Risk Score, coronary calcium score and CT angiography. This study evaluates the variability and reproducibility of DTM measurements. We hypothesized that DTM is reproducible, and its variability falls within the accepted range of clinical diagnostic tests.
package models import "errors" var ( // ErrMissCache ... ErrMissCache = errors.New("cache not found") // ErrCache ... ErrCache = errors.New("cache error") )
def main(args): print("The observation tutorial will show you the various observation configurations available.") background_name = background_names[1] demo = args.load_demo = input('Input path to demo file, such as demos/Sawyer_7.pkl: ') if demo == '': demo = args.load_demo = 'demos/Sawyer_7.pkl' agent_name, furniture_id = demo.split('/')[-1].split('.')[0].split('_') agent_name = agent_name[0].upper() + agent_name[1:] furniture_id = int(furniture_id) furniture_name = furniture_names[furniture_id] print() print("Include robot observation?\n") try: s = input("Put 1 for True or 0 for False: ") k = int(s) == 1 except: print("Input is not valid. Use 0 by default.") k = False args.robot_ob = k print() print("Include furniture observation?\n") try: s = input("Put 1 for True or 0 for False: ") k = int(s) == 1 except: print("Input is not valid. Use 0 by default.") k = False args.object_ob = k print() print("Use segmentation?\n") try: s = input("Put 1 for True or 0 for False: ") k = int(s) == 1 except: print("Input is not valid. Use 0 by default.") k = False use_seg = k print() print("Use depth map?\n") try: s = input("Put 1 for True or 0 for False: ") k = int(s) == 1 except: print("Input is not valid. Use 0 by default.") k = False use_depth = k env_name = 'Furniture{}Env'.format(agent_name) args.env = env_name args.furniture_id = furniture_id args.background = background_name print() print("Creating environment (robot: {}, furniture: {}, background: {})".format( env_name, furniture_name, background_name)) args.depth_ob = True args.segmentation_ob = True env = make_env(env_name, args) ob = env.reset(args.furniture_id, args.background) print('-' * 80) print('Observation configuration:') print(f"Robot ob: {args.robot_ob}, Furniture ob: {args.object_ob}") print(f"Depth Map: {use_depth}, Segmentation Map: {use_seg}") print() print("Observation Space:\n") print("The observation space is a dictionary. For furniture (object) observations, it is "+ "a multiple of 7 because each part has 3 dims for position and 4 dims for quaternion. "+ "The robot_ob is dependent on the agent, and contains position, velocity, or angles of "+ "the current robot.\n") print(env.observation_space) print() input("Type anything to record an episode's visual observations") rgb_frames = [] depth_frames = [] seg_frames = [] with open(env._load_demo, 'rb') as f: demo = pickle.load(f) all_qpos = demo['qpos'] for qpos in all_qpos: for i, body in enumerate(env._object_names): pos = qpos[body][:3] quat = qpos[body][3:] env._set_qpos(body, pos, quat) env._stop_object(body, gravity=0) if env._agent_type == 'Sawyer': env.sim.data.qpos[env._ref_joint_pos_indexes] = qpos['sawyer_qpos'] env.sim.data.qpos[env._ref_gripper_joint_pos_indexes] = qpos['l_gripper'] elif env._agent_type == 'Baxter': env.sim.data.qpos[env._ref_joint_pos_indexes] = qpos['baxter_qpos'] env.sim.data.qpos[env._ref_gripper_right_joint_pos_indexes] = qpos['r_gripper'] env.sim.data.qpos[env._ref_gripper_left_joint_pos_indexes] = qpos['l_gripper'] elif env._agent_type == 'Cursor': env._set_pos('cursor0', qpos['cursor0']) env._set_pos('cursor1', qpos['cursor1']) env.sim.forward() env._update_unity() img, depth = env.render('rgbd_array') seg = I.color_segmentation(env.render('segmentation')) rgb_frames.append(img) depth_frames.append(depth) seg_frames.append(seg) env.close() wide_frames = [] L = max(len(rgb_frames), len(rgb_frames), len(seg_frames)) for l in range(L): rgb = rgb_frames[l] f = [rgb * 255] if use_depth: depth = depth_frames[l] f.append(depth * 255) if use_seg: seg = seg_frames[l] f.append(seg) wide = np.concatenate(f, axis=1) wide_frames.append(wide) vr = VideoRecorder() vr._frames = wide_frames vr.save_video('observations.mp4')
import os import sys import tempfile import unittest from subprocess import Popen, PIPE PATH_TO_JQ = os.getenv('PATH_TO_JQ', './jq/jq') class jv_parser_test(unittest.TestCase): def setUp(self): if not os.path.isfile(PATH_TO_JQ): msg = """ jq binary not found at '%s'. To look in a different path, use: env PATH_TO_JQ=/path/to/jq python %s""" raise ValueError(msg % (PATH_TO_JQ, __file__)) self.gdbinit_fd, self.gdbinit_path = tempfile.mkstemp() gdbinit_sock = os.fdopen(self.gdbinit_fd, 'w') with open('./gdbinit.template', 'r') as gdbinit_template: for line in gdbinit_template: line = line.replace('/path/to/jq-gdb', os.getcwd()) gdbinit_sock.write(line) gdbinit_sock.close() def tearDown(self): os.remove(self.gdbinit_path) def gdb(self, expr): cmd = ['gdb', '-q', # less output from gdb '-nx', # ignore ~/.gdbinit '-x', self.gdbinit_path, # use our gdbinit '--args', PATH_TO_JQ, '--arg', 'k', 'v', # test_local_variable looks for this '.'] proc = Popen(cmd, stdin=PIPE, stdout=PIPE) outs, errs = proc.communicate(input=_str(""" break jq_compile_args run print %s quit """ % expr)) lines = outs.splitlines() expected = _str("(gdb) $1 = jv: ") result = next(line for line in lines if line.startswith(expected)) return result[len(expected):] def test_local_variable(self): self.assertEqual(self.gdb('args'), _str('[{"name":"k","value":"v"}]')) def test_invalid(self): self.assertEqual(self.gdb('jv_invalid()'), _str('<invalid>')) def test_invalid_with_msg(self): mk_invalid = 'jv_invalid_with_msg(jv_string("msg"))' self.assertEqual(self.gdb(mk_invalid), _str('<invalid:"msg">')) def test_null(self): self.assertEqual(self.gdb('jv_null()'), _str('null')) def test_false(self): self.assertEqual(self.gdb('jv_false()'), _str('false')) def test_true(self): self.assertEqual(self.gdb('jv_true()'), _str('true')) def test_integer(self): self.assertEqual(self.gdb('jv_number(100)'), _str('100')) def test_double(self): self.assertEqual(self.gdb('jv_number(1.618034)'), _str('1.618034')) def test_string(self): self.assertEqual(self.gdb('jv_string("test")'), _str('"test"')) def test_empty_array(self): self.assertEqual(self.gdb('jv_array()'), _str('[]')) def test_array(self): mk_array = 'jv_array_set(jv_array(), 2, jv_true())' self.assertEqual(self.gdb(mk_array), _str('[null,null,true]')) def test_empty_object(self): self.assertEqual(self.gdb('jv_object()'), _str('{}')) def test_object(self): mk_object = 'jv_object_set(jv_object(), jv_string("k"), jv_string("v"))' self.assertEqual(self.gdb(mk_object), _str('{"k":"v"}')) def _str(orig): """For Python 3, convert string to bytes.""" if sys.version_info[0] < 3: return orig else: return bytes(orig, "UTF-8") if __name__ == '__main__': if sys.version_info[:2] <= (2, 6): unittest.main() # verbosity parameter did not exist else: unittest.main(verbosity=2)
There are not many people who can say they have been a Chelsea fan for a century but that is exactly what Doris Wilkinson is. The feisty lady turned 100-years-old on Tuesday (11) as she celebrated at a party with friends at the Chiswick Nursing Centre in Ravenscourt Gardens. Having lived all her life in Fulham, she remembers the area fondly - playing tennis in Bishop’s Park with her beloved husband, John, watching the annual University Boat Race and of course supporting Chelsea FC. “We used to watch the Boat Race on the river bank in Fulham every year and now I watch it on TV but it really hasn’t changed. I’ve always supported Cambridge because I prefer the colour, sky blue is much better than Oxford’s dark blue! “I’ve always been a Chelsea supporter, never Fulham despite living there. I still watch the matches on TV, up the Blues!” The youngest of five children, Mrs Wilkinson left school at 14-years-old and started working at a luxury leather goods store in Picadilly which she remembers with much fondness. She said: “We sold all types of leather goods, wallets, cases, luggage. I was a cashier and we had lots of well-to-do people coming into the shop, it was lots of fun and I learnt a lot but it’s no longer there. “I also volunteered at the Royal Brompton Hospital which was so rewarding. I made great friends there and it’s such a fantastic hospital, I've got very good memories of working there.” She lived with her husband John in Queensmill Road opposite Fulham Palace Cemetery for many happy years but they had only been married for a year when the Second World War broke out and he was subsequently taken as a prisoner of war in Poland. “We got married in 1938 then the war broke out in 1939 and he went off with the army and was then captured so I didn’t see him until he came back to London in 1945. “It was difficult but then everybody was going through the same thing so we all helped each other out and everyone was much more friendly back then. We had to go to air raid shelters but luckily I didn’t have to sleep in the tube like lots of people did, it must’ve been horrible sleeping with hundreds of others all around you. “When John returned from the war there was no fanfare, we just got on with and it was lovely having him back so we could at last enjoy our marriage. He was such a lovely man, the love of my life.” The Wilkinsons used to run around Fulham in a yellow Ford Anglia, driven by Doris with John navigating. “John didn’t know how to drive so he was always the one reading the map. We made a good team, it was such fun driving that car.” And as for the secret to living for that long, Mrs Wilkinson said one does not exist. “I never thought I’d live ‘til 100. Just live life to the full and enjoy it.” Mrs Wilkinson has been at the Chiswick Nursing Centre for a few years now and had high praise for the staff and facilities there and it was obvious they are just as devoted to her.
N, K=input().split() hp=input().split() j = sorted([int(x) for x in hp]) print(sum([j[x] for x in range(int(N) - int(K))])) if int(K) < int(N) else print(0)
""" """ import sys from sys import stdin tt = int(stdin.readline()) ansl = [] for loop in range(tt): n,q = map(int,stdin.readline().split()) s = stdin.readline()[:-1] for i in range(q): l,r = map(int,stdin.readline().split()) l -= 1 r -= 1 ans = "NO" for j in range(l-1,-1,-1): if s[j] == s[l]: ans = "YES" for j in range(r+1,n): if s[j] == s[r]: ans = "YES" ansl.append(ans) print ("\n".join(ansl))
<reponame>AlejandroSantorum/AUTLEN_Assignments #ifndef AFND_H #define AFND_H #include <stdio.h> #define INICIAL 0 #define FINAL 1 #define INICIAL_Y_FINAL 2 #define NORMAL 3 typedef struct _AFND AFND; AFND * AFNDNuevo(char * nombre, int num_estados, int num_simbolos); void AFNDElimina(AFND * p_afnd); void AFNDImprime(FILE * fd, AFND* p_afnd); int AFNDIndiceDeSimbolo(AFND * p_afnd, char * nombre); int AFNDIndiceDeEstado(AFND * p_afnd, char * nombre); char * AFNDNombreEstadoEn(AFND * p_afnd, int pos); char * AFNDSimboloEn(AFND * p_afnd, int pos); AFND * AFNDInsertaSimbolo(AFND * p_afnd, char * simbolo); AFND * AFNDInsertaEstado(AFND * p_afnd, char * nombre, int tipo); AFND * AFNDInsertaTransicion(AFND * p_afnd, char * nombre_estado_i, char * nombre_simbolo_entrada, char * nombre_estado_f ); AFND * AFNDInsertaLTransicion(AFND * p_afnd, char * nombre_estado_i, char * nombre_estado_f ); AFND * AFNDInsertaLetra(AFND * p_afnd, char * letra); void AFNDImprimeConjuntoEstadosActual(FILE * fd, AFND * p_afnd); void AFNDImprimeCadenaActual(FILE *fd, AFND * p_afnd); void AFNDTransita(AFND * p_afnd); void AFNDProcesaEntrada(FILE * fd, AFND * p_afnd); int AFNDIndiceEstadoInicial(AFND * p_afnd); AFND * AFNDInicializaEstado (AFND * p_afnd); AFND * AFNDInicializaCadenaActual (AFND * p_afnd); AFND * AFNDCierraLTransicion (AFND * p_afnd); int AFNDLTransicionIJ(AFND * p_afnd, int i , int j); int AFNDTransicionIndicesEstadoiSimboloEstadof(AFND * p_afnd, int i_e1, int i_s, int i_e2); int AFNDCierreLTransicionIJ(AFND * p_afnd, int i, int j); int AFNDIndicePrimerEstadoFinal(AFND * p_afnd); /* FUNCIONES PARA IMPRIMIR DIAGRAMA */ void AFNDADot(AFND * p_afnd); /* FUNCIONES PARA OBTENER INFORMACIÓN DEL AUTÓMATA */ int AFNDNumSimbolos(AFND * p_afnd); int AFNDNumEstados(AFND * p_afnd); int AFNDTipoEstadoEn(AFND * p_afnd, int pos); #endif
<gh_stars>100-1000 import env from 'react-native-config'; import { Platform } from 'react-native'; import getAppVersion from '../../helpers/getAppVersion'; interface ReportIssueProps { email: string; name: string; body: string; } const OS_FIELD_KEY = '360033622032'; const OS_VERSION_FIELD_KEY = '360033618552'; const APP_VERSION_FIELD_KEY = '360033141172'; const APP_NAME_FIELD_KEY = '360034051891'; const ISSUE_SUBJECT = `Issue from GPS mobile application PathCheck ${ __DEV__ ? '[Dev Testing]' : '' }`; const ANONYMOUS = 'Anonymous'; const APP_NAME = 'PathCheck GPS'; const EMAIL_ERROR = 'Email:'; interface ErrorDescription { description: string; } interface ErrorDetails { requester?: ErrorDescription[]; base: ErrorDescription[]; } // Errors are of the form: // { // "error": "RecordInvalid", // "description": "Record validation errors", // "details": { // "requester": [ // { // "description": "Requester: Email: not_really_an_email.com is not properly formatted" // } // ] // } //} const parseErrorMessage = (zendeskError?: Record<string, unknown>): string => { if (zendeskError?.details) { const errorDetails = zendeskError.details as ErrorDetails; const errorMessage = (errorDetails?.requester || errorDetails.base) .map((error) => { return error.description; }) .join(','); if (errorMessage.indexOf(EMAIL_ERROR) !== -1) { return 'report_issue.errors.invalid_email'; } return errorMessage.replace(':', '-'); // so localize doesn't mess with error message } return ''; // fallback to no error message, just an error title for our alert. }; const reportIssue = async ({ email, name, body, }: ReportIssueProps): Promise<void> => { const requestBody = { request: { subject: ISSUE_SUBJECT, requester: { name: name.trim().length > 0 ? name : ANONYMOUS, email }, comment: { body }, custom_fields: [ { [OS_FIELD_KEY]: Platform.OS, [OS_VERSION_FIELD_KEY]: Platform.Version, [APP_VERSION_FIELD_KEY]: getAppVersion(), [APP_NAME_FIELD_KEY]: APP_NAME, }, ], }, }; const response = await fetch(env.ZENDESK_URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(requestBody), }); if (!response.ok) { const responseJson = await response.json(); throw new Error(parseErrorMessage(responseJson)); } }; export default reportIssue;
from django.urls import path from . import views app_name = "incidents" urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.IncidentView.as_view(), name='incident'), path('<int:pk>/update/', views.UpdateIncidentView.as_view(), name='update_incident'), path('<int:incident_pk>/machine_incident/<int:pk>/update/', views.UpdateMachineIncidentView.as_view(), name='update_machine_incident'), # events path('<int:pk>/events/', views.IncidentEventsView.as_view(), name='incident_events'), path('<int:pk>/events/fetch/', views.FetchIncidentEventsView.as_view(), name='fetch_incident_events'), path('<int:pk>/events/store_redirect/', views.IncidentEventsStoreRedirectView.as_view(), name='incident_events_store_redirect'), ] main_menu_cfg = { 'weight': 2, 'items': ( ('index', 'all incidents', False, ("incidents.view_incident",)), ), }
The punitive California Air Resources Board (CARB) has figured out how Audi cheated on a particular run of “several hundred thousand” of their cars, according to a new report by the German newspaper BILD am Sonntag. This time we Americans have discovered a trick in the car’s software that relates to the steering wheel. According to BILD am Sonntag’s new report this morning (view the link here, behind a paywall, or google around for a handful of other news sources re-covering the news including Reuters, Der Spiegel, Forbes and Automotive News), CARB figured out this software cheat months ago. Why we’re only hearing of this now, I do not know, and Bild am Sonntag cites no sources and we have as-yet no comment from CARB on the report, as Automotive News points out. But the cheat reportedly works thusly, and it’s ingenious in its simplicity: When the Audi starts up, its transmission engages a ‘low CO2' program, shifting gears in such a way as to keep engine revs and emissions artificially low. If the steering wheel is turned more than 15 degrees, the car deactivates the program and shifts in its normal, more pollutant fashion that burns more gas and produces more CO2. Audi figured that the only time the car would run with the steering wheel never moving would be in a lab, on a test bed. This is a similar philosophy to the classic ‘dyno mode’ cheat that kicked off Dieselgate. It’s so simple, and apparently it was enough to get Audis to pass emissions tests in lab situations they might have never passed in real world conditions. Advertisement The cheat was only implemented on cars with an automatic transmission with an internal designation AL 551. This appears to be a particular variant of the eight-speed unit Audi sources from transmission supplier ZF, set up for Quattro models. It apparently covers several hundred thousand vehicles under the cheat, according to Bild am Sonntag’s reporting. Diesel engines and gasoline engines are both affected here, and models involved include the Audi A8, the Audi Q5 as Forbes notes, as well as the Audi Q7 if my Wikipedia digging is correct. This does not seem to be an issue on brand-new Audis, as Bild am Sonntag reports that Audi stopped using the software a few months before CARB figured it out while testing an unnamed older model, as Reuters notes. This very much does not look good for Audi or for VW, which recently finished up its settlement with the U.S. Government and American VW owners. How this new wrinkle in the Dieselgate saga will play out is yet to be seen.
<commit_msg>Fix up rust example for 1.0 <commit_before>pub fn max_array(x: &mut[int, ..65536], y: &[int, ..65536]) { for i in range(0u, 65536) { if y[i] > x[i] { x[i] = y[i]; } } } <commit_after>pub fn max_array(x: &mut[i32; 65536], y: &[i32; 65536]) { for i in (0..65536) { if y[i] > x[i] { x[i] = y[i]; } } }
/** * World is extensible in dynamic. * use this class, if want world generate system like minecraft. */ class World : public IWorld { public: using Instance = std::shared_ptr<World>; using Reference = std::weak_ptr<World>; static Instance create(ofShader& shader, int worldYSize); void computeBrightness(); int getYSize() const; std::shared_ptr<Block> getBlock(int x, int y, int z) const; bool isFilled(int x, int y, int z) const; int getBrightness(int x, int y, int z) const; ofShader& getShader(); glm::vec3 getViewPosition() const; int getViewRange() const; ChunkLoadStyle getChunkLoadStyle() const; std::shared_ptr<Chunk> getCurrentChunk(); void invalidateBrightness(); void setViewPosition(const glm::vec3& viewPosition); void setBiome(std::shared_ptr<Biome> biome); std::shared_ptr<Biome> getBiome() const; void setLoadRange(int loadRange); int getLoadRange() const; std::shared_ptr<Chunk> findChunk(int x, int z) const; std::shared_ptr<Chunk> loadChunk(int x, int z); std::shared_ptr<Chunk> loadChunk(int x, int z, bool& isCreatedNewChunk); std::shared_ptr<Chunk> loadOrGenChunk(int x, int z); void draw(); private: World(ofShader& shader, int worldYSize); std::shared_ptr<Sector> findChunkImpl(int x, int z) const; std::shared_ptr<Sector> loadChunkImpl(int x, int z, bool & isCreatedNewChunk); std::shared_ptr<Chunk> loadOrGenChunkImpl(int x, int z, int xOffset, int zOffset); std::shared_ptr<Chunk> loadOrGenChunkRange(int x, int z, int xOffset, int zOffset); int computeChunkOffsetX(int x) const; int computeChunkOffsetZ(int z) const; void updateNeighborChunks(); int computeGridX(int x) const; int computeGridZ(int z) const; int worldYSize; int chunkXSize; int chunkZSize; int viewRange; int loadRange; glm::vec3 viewPosition; std::vector<std::shared_ptr<Sector> > chunkVec; ofShader& shader; std::shared_ptr<Chunk> currentChunk; std::shared_ptr<Biome> biome; }
/// Builds a context for creating, or building, the installer. pub fn build(&mut self) -> Execution { Execution { bin_path: self.bin_path.map(PathBuf::from), capture_output: self.capture_output, compiler_args: self .compiler_args .as_ref() .map(|c| c.iter().map(|s| (*s).to_string()).collect()), culture: self.culture.map(String::from), debug_build: self.debug_build, debug_name: self.debug_name, includes: self .includes .as_ref() .map(|v| v.iter().map(&PathBuf::from).collect()), input: self.input.map(PathBuf::from), linker_args: self .linker_args .as_ref() .map(|l| l.iter().map(|s| (*s).to_string()).collect()), locale: self.locale.map(PathBuf::from), name: self.name.map(String::from), no_build: self.no_build, output: self.output.map(String::from), package: self.package.map(String::from), version: self.version.map(String::from), target: self.target.map(String::from), } }
// Copyright (c) 2018-2020 MobileCoin Inc. //! Define DiscoveryHint buffer size, and serialization defs for it //! Also define `fake_onetime_hint` which samples the distribution that //! should be used for these hints when there is no discovery server. //! //! Note: Using generic array because rust has poor support for implementing //! builtin traits on arrays of size > 32. use alloc::{vec, vec::Vec}; use core::{convert::TryFrom, fmt}; use generic_array::{ typenum::{Diff, Unsigned, U128}, GenericArray, }; use mc_crypto_box::{CryptoBox, VersionedCryptoBox}; use mc_crypto_digestible::Digestible; use mc_util_from_random::FromRandom; use prost::{ bytes::{Buf, BufMut}, encoding::{bytes, skip_field, DecodeContext, WireType}, DecodeError, Message, }; use rand_core::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; // The length of the encrypted fog hint field in the ledger. // Must be at least as large as McRistrettoBox::FooterSize, or it can't hold a // Ristretto-Box encryption. pub type EncryptedFogHintSize = U128; pub const ENCRYPTED_FOG_HINT_LEN: usize = EncryptedFogHintSize::USIZE; type Bytes = GenericArray<u8, EncryptedFogHintSize>; #[derive( Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize, Default, Digestible, )] pub struct EncryptedFogHint { bytes: Bytes, } // AsRef and AsMut slice conversions impl AsRef<Bytes> for EncryptedFogHint { fn as_ref(&self) -> &Bytes { &self.bytes } } impl AsMut<Bytes> for EncryptedFogHint { fn as_mut(&mut self) -> &mut Bytes { &mut self.bytes } } impl From<Bytes> for EncryptedFogHint { fn from(bytes: Bytes) -> Self { Self { bytes } } } impl From<&[u8; ENCRYPTED_FOG_HINT_LEN]> for EncryptedFogHint { #[inline] fn from(a: &[u8; ENCRYPTED_FOG_HINT_LEN]) -> Self { Self { bytes: GenericArray::clone_from_slice(&a[..]), } } } impl<'bytes> TryFrom<&'bytes [u8]> for EncryptedFogHint { type Error = (); fn try_from(slice: &'bytes [u8]) -> Result<Self, ()> { if slice.len() == ENCRYPTED_FOG_HINT_LEN { Ok(Self { bytes: GenericArray::clone_from_slice(slice), }) } else { Err(()) } } } impl EncryptedFogHint { #[inline] pub fn new(a: &[u8; ENCRYPTED_FOG_HINT_LEN]) -> Self { Self { bytes: GenericArray::clone_from_slice(&a[..]), } } #[inline] pub fn to_bytes(&self) -> [u8; ENCRYPTED_FOG_HINT_LEN] { let mut result = [0u8; ENCRYPTED_FOG_HINT_LEN]; result.copy_from_slice(self.as_ref()); result } /// fake_onetime_hint /// To be used in prod when sending to a recipient with no known fog server /// This means it should be indistinguishable from an ecies encryption of a /// random plaintext. There are several ways we could sample that distribution /// but the simplest is to do exactly that. This is also future-proof if we later /// tweak the cryptobox implementation. pub fn fake_onetime_hint<T: RngCore + CryptoRng>(rng: &mut T) -> Self { // Make plaintext of the right size let plaintext = GenericArray::< u8, Diff<EncryptedFogHintSize, <VersionedCryptoBox as CryptoBox>::FooterSize>, >::default(); // Make a random key let key = mc_crypto_keys::RistrettoPublic::from_random(rng); // encrypt_in_place into the buffer let bytes = VersionedCryptoBox::default() .encrypt_fixed_length(rng, &key, &plaintext) .expect("Encryption error"); Self { bytes } } } impl Message for EncryptedFogHint { fn encode_raw<B>(&self, buf: &mut B) where B: BufMut, { bytes::encode(1, &self.to_bytes().to_vec(), buf) } fn merge_field<B>( &mut self, tag: u32, wire_type: WireType, buf: &mut B, ctx: DecodeContext, ) -> Result<(), DecodeError> where B: Buf, { if tag == 1 { let mut vbuf = Vec::new(); bytes::merge(wire_type, &mut vbuf, buf, ctx)?; if vbuf.len() != ENCRYPTED_FOG_HINT_LEN { return Err(DecodeError::new(alloc::format!( "EncryptedFogHint: expected {} bytes, got {}", ENCRYPTED_FOG_HINT_LEN, vbuf.len() ))); } let mut abuf: [u8; ENCRYPTED_FOG_HINT_LEN] = [0u8; ENCRYPTED_FOG_HINT_LEN]; abuf.copy_from_slice(&vbuf[0..ENCRYPTED_FOG_HINT_LEN]); *self = Self::new(&abuf); Ok(()) } else { skip_field(wire_type, tag, buf, ctx) } } fn encoded_len(&self) -> usize { bytes::encoded_len(1, &vec![0u8; ENCRYPTED_FOG_HINT_LEN]) } fn clear(&mut self) { *self = Self::default(); } } impl fmt::Debug for EncryptedFogHint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "EncryptedFogHint({})", hex_fmt::HexFmt(self.as_ref())) } } #[cfg(test)] mod testing { use super::*; #[test] fn test_fog_hint_serde() { let a = EncryptedFogHint::new(&[17u8; ENCRYPTED_FOG_HINT_LEN]); let a_ser = mc_util_serial::serialize(&a).unwrap(); let b: EncryptedFogHint = mc_util_serial::deserialize(&a_ser).unwrap(); assert_eq!(a.as_ref(), b.as_ref()); } }
import { createStyles } from "@material-ui/styles"; import Theme from "../../Theme"; const iconContainerSize = 200; const Styles = createStyles({ container: { position: "fixed", top: 0, right: 0, bottom: 0, left: 0, background: Theme.palette.background.default, }, hourglassContainer: { // display: "inline-block", position: "absolute", width: `${iconContainerSize}px`, height: `${iconContainerSize}px`, top: "50%", left: "50%", marginTop: `-${iconContainerSize / 2}px`, marginLeft: `-${iconContainerSize / 2}px`, display: "flex", justifyContent: "center", alignItems: "center", flexDirection: "column", textAlign: "center", }, hourglass: { display: "block", borderRadius: "50%", width: 0, height: 0, margin: 6, boxSizing: "border-box", border: `26px solid ${Theme.palette.background.default}`, borderColor: `${Theme.palette.primary.main} transparent ${Theme.palette.primary.main} transparent`, animationName: "hourglass-animation", animationDuration: "1s", animationTimingFunction: "linear", animationIterationCount: "infinite", }, factText: { marginTop: Theme.spacing(1), marginBottom: Theme.spacing(1), color: Theme.palette.text.primary, fontWeight: "bold", fontStyle: "italic", width: "100%", }, loadingText: { marginTop: Theme.spacing(1), marginBottom: Theme.spacing(1), color: Theme.palette.text.primary, }, }); export default Styles;
Evaluating the Robustness of Publish/Subscribe Systems In recent years, publish/subscribe (pub/sub) systems have evolved as serious candidates for the implementation of multicast communication. However, to date they have not been properly analysed with respect to the critical dimension of robustness. Indeed, the robustness evaluations found in the literature only cover a subset of the types of failure situations and generally lack a comprehensive architectural classification. In this context, this paper introduces the necessary foundations for systematic evaluation of the robustness of pub/sub system: a comprehensive classification scheme and a complete taxonomy of failures. We argue that both robustness evaluation of pub/sub systems and development methods of robust pub/sub systems should take rational behavior into account. We demonstrate this point through an experimental study.
Multilevel Fast Multipole Acceleration for Fast ISAR Imaging based on Compressive Sensing In this paper, compressive sensing (CS) is introduced into an efficient numerical method multilevel fast multipole acceleration (MLFMA) for the electromagnetic scattering problem over a wide incident angle. The resulted data from CS based MLFMA are processed to inverse synthetic aperture radar (ISAR) imaging. Simulation results in maritime surveillance for the classification of ships and aircrafts show the received data for ISAR imaging from MLFMA with CS can reach the outperforms of MLFMA and achieves a quality similar to that of classical ISAR imaging. Furthermore, the computational complexity is improved by CS obviously through the reduced matrix computation for the fewer incident waves. An illustration with Aircraft Model Imaging confirms the usefulness of CSMLFMA.
def IgnoreMask(self): return self._get_attribute('ignoreMask')
<reponame>xzyJohn/blog_backend package com.blog.modules.system.service; import com.blog.modules.system.entity.Permission; import com.blog.modules.base.service.MyService; /** * * @Description: * @author zeyi * @since 2020-06-12 */ public interface PermissionService extends MyService<Permission> { }
import * as types from './types'; export const INITIAL_STATE: types.GasState = { estimates: null, isEstimating: false }; function fetchGasEstimates(state: types.GasState): types.GasState { return { ...state, isEstimating: true }; } function setGasEstimates( state: types.GasState, action: types.SetGasEstimatesAction ): types.GasState { return { ...state, estimates: action.payload, isEstimating: false }; } export function gasReducer( state: types.GasState = INITIAL_STATE, action: types.GasAction ): types.GasState { switch (action.type) { case types.GasActions.FETCH_ESTIMATES: return fetchGasEstimates(state); case types.GasActions.SET_ESTIMATES: return setGasEstimates(state, action); default: return state; } }
Design and properties of a sensor network embedded in thin fiber-reinforced composites So far, embedded sensor networks in composites have mostly been used for structure health monitoring. In contrast to that, in the present work a new stand-alone embedded sensor network for load monitoring of a composite component is presented. Design considerations for the manufacturing of a demonstrator as well as measurement results for cyclic loading are discussed. The presented demonstrator comprises two textile manufactured carbon filament yarn strain sensors for measuring the average bending strain of a large area, embedded capacitive keys for manually controlling the load monitoring process, a sensor ASIC for the processing of the measured data as well as a transponder ASIC with an antenna for the wireless transmission of the measured strains to an external reading station.
import pytest from django.core.management import call_command @pytest.fixture() def tag(factory): return factory.tag() @pytest.fixture() def tags(factory): return factory.tags() @pytest.fixture() def create_tags_command_exec(): return call_command('create_tags')
<reponame>nkmakes/playgroundexpress_tft /************************************************************************** This is a test file for adafruit playground express accel and tft Displays a ball on the screen that moves depending on accel values Written by <EMAIL> **************************************************************************/ #include <Arduino.h> #include <Wire.h> #include <SdFat.h> #include <Adafruit_CircuitPlayground.h> #include <Adafruit_GFX.h> #include <Adafruit_ST7789.h> #include <SPI.h> #define TFT_CS 0 #define TFT_RST -1 // Or set to -1 and connect to Arduino RESET pin #define TFT_DC 1 #define TFT_BACKLIGHT PIN_A3 // Display backlight pin SPIClass* spi = &SPI1; Adafruit_ST7789 tft = Adafruit_ST7789(spi, TFT_CS, TFT_DC, TFT_RST); int xPos = 120; int yPos = 120; int motionX; int motionY; volatile uint16_t actualColor=ST77XX_RED; const uint16_t colorsCicle[6]= {ST77XX_RED, ST77XX_BLUE, ST77XX_GREEN, ST77XX_ORANGE, ST77XX_CYAN, ST77XX_YELLOW}; void chgColor() { actualColor=colorsCicle[random(5)]; return; } void clearScreen() { tft.fillScreen(ST77XX_BLACK); return; } void setup(void) { CircuitPlayground.begin(); Serial.begin(9600); Serial.print(F("Hello! ST77xx TFT Test")); tft.init(240, 240); tft.setRotation(2); pinMode(TFT_BACKLIGHT, OUTPUT); digitalWrite(TFT_BACKLIGHT, HIGH); Serial.println(F("Initialized")); uint16_t time = millis(); tft.fillScreen(ST77XX_BLACK); tft.setTextColor(ST77XX_GREEN); time = millis() - time; Serial.println(time, DEC); delay(500); tft.setTextSize(30); tft.fillScreen(ST77XX_BLACK); for (int i=3; i>=1; i--) { tft.fillScreen(ST77XX_BLACK); tft.setCursor(50, 20); tft.print(i); delay(1000); } tft.fillScreen(ST77XX_BLACK); pinMode(4, INPUT); pinMode(5, INPUT); attachInterrupt(digitalPinToInterrupt(5), chgColor, HIGH); attachInterrupt(digitalPinToInterrupt(4), clearScreen, HIGH); } void loop() { //tft.fillScreen(ST77XX_BLACK); tft.setCursor(xPos, yPos); tft.drawCircle(xPos, yPos, 10, actualColor); tft.fillCircle(xPos, yPos, 10, actualColor); delay(10); motionX=CircuitPlayground.motionX(); motionY=CircuitPlayground.motionY(); xPos+=motionX; yPos+=motionY; if (xPos >= 230) xPos=230; else if (xPos<=10) xPos=10; if (yPos >= 230) yPos=230; else if (yPos<=10) yPos=10; }
def select(self, token): return token['SUBTOKENS'][self._start:self._end]
<gh_stars>1-10 {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} module Insert.Venues ( insertMissingVenues ) where import Database -- import qualified Schema.Currency as Currency import qualified Schema.Venue as Venue import Database.Beam import qualified Data.Set as Set import Database.Beam.Backend.SQL.BeamExtensions (runInsertReturningList) -- TODO: generalize 'Query.Currencies' insertMissingVenues lst = do existingCurrencyRows <- runSelectReturningList $ select $ lookupExistingVenues lst let existingCurrencies = Set.fromList $ map Venue.venueName existingCurrencyRows missingCurrencies = Set.fromList lst Set.\\ existingCurrencies runInsert $ insert (venues liquidityDb) $ insertExpressions $ map (Venue.Venue . val_) (Set.toList missingCurrencies) lookupExistingVenues [] = do venue <- all_ $ venues liquidityDb guard_ (val_ False) pure venue lookupExistingVenues venueLst = do venue <- all_ $ venues liquidityDb guard_ $ Venue.venueName venue `in_` map val_ venueLst pure venue
<reponame>KennethDorji/CaesarCipher /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package swing; import java.util.Scanner; import java.util.Random; /** * * @author juice */ public class Home extends javax.swing.JFrame { /** * Creates new form Home */ public Home() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { encrypt = new java.awt.Button(); decrypt = new java.awt.Button(); jComboBox1 = new javax.swing.JComboBox<>(); key = new java.awt.TextField(); textField3 = new java.awt.TextField(); randomKey = new java.awt.Button(); clear = new java.awt.Button(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(0, 0, 0)); setPreferredSize(new java.awt.Dimension(1100, 650)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); encrypt.setActionCommand("Encrypt"); encrypt.setLabel("Encrypt"); encrypt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { encryptActionPerformed(evt); } }); getContentPane().add(encrypt, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 420, -1, -1)); decrypt.setLabel("Decrypt"); decrypt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decryptActionPerformed(evt); } }); getContentPane().add(decrypt, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 420, -1, -1)); jComboBox1.setBackground(new java.awt.Color(255, 255, 255)); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 280, -1, -1)); key.setBackground(new java.awt.Color(255, 255, 255)); key.setText("Key:"); getContentPane().add(key, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 280, -1, -1)); textField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField3ActionPerformed(evt); } }); getContentPane().add(textField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 310, 40, 25)); randomKey.setLabel("Random Key:"); randomKey.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { randomKeyActionPerformed(evt); } }); getContentPane().add(randomKey, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 310, -1, -1)); clear.setLabel("Clear"); clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearActionPerformed(evt); } }); getContentPane().add(clear, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 380, -1, -1)); jLabel1.setFont(new java.awt.Font("Noteworthy", 3, 48)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 255, 255)); jLabel1.setText("Caesar Cipher"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 70, -1, -1)); jTextArea1.setBackground(new java.awt.Color(0, 153, 153)); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 160, 260, 180)); jTextArea2.setBackground(new java.awt.Color(204, 204, 204)); jTextArea2.setColumns(20); jTextArea2.setRows(5); jScrollPane2.setViewportView(jTextArea2); getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 300, 260, 180)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/swing/background.jpg"))); // NOI18N getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(-190, -150, 1320, 900)); pack(); }// </editor-fold>//GEN-END:initComponents private void encryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_encryptActionPerformed // TODO add your handling code here: String userInput = jTextArea1.getText(); int key = 0; if (textField3.getText().equals("")) { String keyDrop = (String)jComboBox1.getSelectedItem(); key = Integer.parseInt(keyDrop); } else { String randomKey = textField3.getText(); int randKey = Integer.parseInt(randomKey); key = randKey; } String encryptedMessage = ""; char ch; for (int i = 0; i < userInput.length(); ++i) { ch = userInput.charAt(i); if (ch >= 'a' && ch <= 'z') { ch = (char) (ch + key); if (ch > 'z') { ch = (char) (ch - 'z' + 'a' - 1); } encryptedMessage += ch; } else if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + key); if (ch > 'Z') { ch = (char) (ch - 'Z' + 'A' - 1); } encryptedMessage += ch; } else { encryptedMessage += ch; } } jTextArea2.setText(encryptedMessage); }//GEN-LAST:event_encryptActionPerformed private void decryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decryptActionPerformed // TODO add your handling code here: String userInput = jTextArea1.getText(); int key = 0; if (textField3.getText().equals("")) { String keyDrop = (String)jComboBox1.getSelectedItem(); key = (Integer.parseInt(keyDrop)); } else { String randomKey = textField3.getText(); int randKey = Integer.parseInt(randomKey); key = randKey; } String decryptedMessage = ""; char ch; for (int i = 0; i < userInput.length(); ++i) { ch = userInput.charAt(i); if (ch >= 'a' && ch <= 'z') { ch = (char) (ch - key); if (ch < 'a') { ch = (char) (ch + 'z' - 'a' + 1); } decryptedMessage += ch; } else if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch - key); if (ch < 'A') { ch = (char) (ch + 'Z' - 'A' + 1); } decryptedMessage += ch; } else { decryptedMessage += ch; } } jTextArea2.setText(decryptedMessage); }//GEN-LAST:event_decryptActionPerformed private void textField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textField3ActionPerformed private void randomKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_randomKeyActionPerformed Random rand = new Random(); // Addding 1 Since we obtain a number between [0 - 49] when using random. int randomNum = 1 + (rand.nextInt(26)); // Parsing int to string to display the number in the Text Box. String randNum = Integer.toString(randomNum); textField3.setText(randNum); /* Resetting the value of a JComboBox. Since the user is using Random number */ jComboBox1.setSelectedIndex(0); }//GEN-LAST:event_randomKeyActionPerformed private void clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearActionPerformed // Resetting both the Random Text Feild and JComboBox. textField3.setText(""); jComboBox1.setSelectedIndex(0); }//GEN-LAST:event_clearActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // Resetting Random Text Feild since the user is using JComboBox. // if(jComboBox1.getItemCount() > 0){ // textField3.setText(""); // } }//GEN-LAST:event_jComboBox1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Home().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private java.awt.Button clear; private java.awt.Button decrypt; private java.awt.Button encrypt; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; private java.awt.TextField key; private java.awt.Button randomKey; private java.awt.TextField textField3; // End of variables declaration//GEN-END:variables }
Factor Analysis of Service Expectation of Farmer Producer Organization from Agribusiness Incubator This paper aimed to study the service expectation of Farmer Producer Organization from the Agribusiness incubator. The study was carried out with 60 FPO’s in Tamil Nadu. The data was collected through survey method using a well-structured online interview questionnaire. The exploratory factor analysis was carried out to reduce the data. The first factor named as which explained 25.37 percent of the variance, the second factor named as early stage business development services which explained 10.27 percent of the variance, the third factor named as business development services which explained 11.50 percent of the variance, the fourth factor named as physical infrastructural assistance which explained 2.21 percent of the variance. The obtained results of Exploratory Factor Analysis revealed that four factors such as market assistance services, early stage business development services, business development services and physical infrastructural assistance explained about 71.69 percent of the variance of factors with respect to service expectation of FPO's from the Business incubator.
Distribution of the Iowan Brood of Periodical Cicadas (Homoptera: Cicadidae: Magicicada spp.) in Illinois Abstract The distribution of the Iowan Brood of periodical cicadas in Illinois was determined in 1997 using a global positioning system receiver and mapping software. The area contained within the distribution derived from this survey was approximately twice the area bounded by a range map published in 1975. Periodical cicadas were found in many areas not included in the earlier range map, and were absent from several areas that had been included. Periodical cicadas were patchily distributed within the boundary, being most abundant in stream woodlands and protected areas and least abundant in agricultural and urban areas. Periodical cicadas were primarily found in a soil type associated with stream woodlands, and appeared to follow forests along waterways, but it is possible that these areas serve as refugia from human activity rather than preferred habitats.
Association between tau H2 haplotype and age at onset in frontotemporal dementia. BACKGROUND The frontotemporal dementia (FTD) syndromes have been associated with the microtubule-associated tau protein since tau gene mutations have been demonstrated to be the cause of FTD and parkinsonism linked to chromosome 17. In cases of FTD without tau gene mutations, however, it is unclear whether genetic variability in the tau gene is associated with the development or modulation of FTD. OBJECTIVE To determine whether genetic variability in tau and apolipoprotein E (ApoE) modulates and contributes to the development of FTD. Design and Patients The distribution of tau gene haplotypes and the ApoE genotype were investigated in 86 patients with well-characterized FTD and 50 control subjects. RESULTS No difference in the distribution of the tau H1 and H2 haplotypes between FTD cases and controls was observed, whereas the ApoE epsilon4 allele was more frequent in FTD cases. The presence of at least 1 tau H2 allele was found to be significantly associated with an earlier age of onset in patients with FTD. The association between the H2 allele and age at onset was not related to family history, clinical presentation, or ApoE genotype. CONCLUSION These findings support a role of tau protein in modulating disease phenotype by influencing the age at onset in these FTD cases.
#pragma once #include "G4VUserActionInitialization.hh" #include <map> #include <string> class ActionInitialization : public G4VUserActionInitialization { public: explicit ActionInitialization(const std::string& mode); void BuildForMaster() const override; void Build() const override; using RunActionCreator = G4UserRunAction* (*)(); using EventActionCreator = G4UserEventAction* (*)(); private: RunActionCreator fRunActionCreator; EventActionCreator fEventActionCreator; };
/* Class107_Sub1 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ final class Class107_Sub1 extends Class107 { private int[] anIntArray5086; private byte[][] aByteArrayArray5087; private int[] anIntArray5088; private int[] anIntArray5089; private int[] anIntArray5090; private Class163_Sub1 aClass163_Sub1_5091; Class107_Sub1(Class163_Sub1 class163_sub1, Class292 class292, Class80[] class80s, int[] is, int[] is_0_) { super(class163_sub1, class292); aClass163_Sub1_5091 = class163_sub1; aClass163_Sub1_5091 = class163_sub1; anIntArray5088 = is; anIntArray5086 = is_0_; aByteArrayArray5087 = new byte[class80s.length][]; anIntArray5090 = new int[class80s.length]; anIntArray5089 = new int[class80s.length]; for (int i = 0; i < class80s.length; i++) { Class80 class80 = class80s[i]; if (((Class80) class80).aByteArray1078 != null) aByteArrayArray5087[i] = ((Class80) class80).aByteArray1078; else { byte[] is_1_ = ((Class80) class80).aByteArray1079; byte[] is_2_ = aByteArrayArray5087[i] = new byte[is_1_.length]; for (int i_3_ = 0; i_3_ < is_1_.length; i_3_++) is_2_[i_3_] = (byte) (is_1_[i_3_] == 0 ? 0 : -1); } anIntArray5090[i] = ((Class80) class80).anInt1077; anIntArray5089[i] = ((Class80) class80).anInt1080; } } final void fa(char c, int i, int i_4_, int i_5_, boolean bool) { i += anIntArray5089[c]; i_4_ += anIntArray5090[c]; int i_6_ = anIntArray5088[c]; int i_7_ = anIntArray5086[c]; int i_8_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5206; int i_9_ = i + i_4_ * i_8_; int i_10_ = i_8_ - i_6_; int i_11_ = 0; int i_12_ = 0; if (i_4_ < ((Class163_Sub1) aClass163_Sub1_5091).anInt5177) { int i_13_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5177 - i_4_; i_7_ -= i_13_; i_4_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5177; i_12_ += i_13_ * i_6_; i_9_ += i_13_ * i_8_; } if (i_4_ + i_7_ > ((Class163_Sub1) aClass163_Sub1_5091).anInt5193) i_7_ -= (i_4_ + i_7_ - ((Class163_Sub1) aClass163_Sub1_5091).anInt5193); if (i < ((Class163_Sub1) aClass163_Sub1_5091).anInt5186) { int i_14_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5186 - i; i_6_ -= i_14_; i = ((Class163_Sub1) aClass163_Sub1_5091).anInt5186; i_12_ += i_14_; i_9_ += i_14_; i_11_ += i_14_; i_10_ += i_14_; } if (i + i_6_ > ((Class163_Sub1) aClass163_Sub1_5091).anInt5178) { int i_15_ = i + i_6_ - ((Class163_Sub1) aClass163_Sub1_5091).anInt5178; i_6_ -= i_15_; i_11_ += i_15_; i_10_ += i_15_; } if (i_6_ > 0 && i_7_ > 0) method2271(aByteArrayArray5087[c], ((Class163_Sub1) aClass163_Sub1_5091).anIntArray5214, i_5_, i_12_, i_9_, i_6_, i_7_, i_10_, i_11_); } private final void method2270(byte[] is, int[] is_16_, int i, int i_17_, int i_18_, int i_19_, int i_20_, int i_21_, int i_22_, int i_23_, int i_24_, int i_25_, Class72 class72, int i_26_, int i_27_) { Class72_Sub2 class72_sub2 = (Class72_Sub2) class72; int[] is_28_ = ((Class72_Sub2) class72_sub2).anIntArray6909; int[] is_29_ = ((Class72_Sub2) class72_sub2).anIntArray6911; int i_30_ = i_23_ - ((Class163_Sub1) aClass163_Sub1_5091).anInt5186; int i_31_ = i_24_; if (i_27_ > i_31_) { i_31_ = i_27_; i_18_ += ((i_27_ - i_24_) * ((Class163_Sub1) aClass163_Sub1_5091).anInt5206); i_17_ += (i_27_ - i_24_) * i_25_; } int i_32_ = (i_27_ + is_28_.length < i_24_ + i_20_ ? i_27_ + is_28_.length : i_24_ + i_20_); for (int i_33_ = i_31_; i_33_ < i_32_; i_33_++) { int i_34_ = is_28_[i_33_ - i_27_] + i_26_; int i_35_ = is_29_[i_33_ - i_27_]; int i_36_ = i_19_; if (i_30_ > i_34_) { int i_37_ = i_30_ - i_34_; if (i_37_ >= i_35_) { i_17_ += i_19_ + i_22_; i_18_ += i_19_ + i_21_; continue; } i_35_ -= i_37_; } else { int i_38_ = i_34_ - i_30_; if (i_38_ >= i_19_) { i_17_ += i_19_ + i_22_; i_18_ += i_19_ + i_21_; continue; } i_17_ += i_38_; i_36_ -= i_38_; i_18_ += i_38_; } int i_39_ = 0; if (i_36_ < i_35_) i_35_ = i_36_; else i_39_ = i_36_ - i_35_; for (int i_40_ = -i_35_; i_40_ < 0; i_40_++) { int i_41_ = is[i_17_++] & 0xff; if (i_41_ != 0) { int i_42_ = ((((i & 0xff00ff) * i_41_ & ~0xff00ff) + ((i & 0xff00) * i_41_ & 0xff0000)) >> 8); i_41_ = 256 - i_41_; int i_43_ = is_16_[i_18_]; is_16_[i_18_++] = ((((i_43_ & 0xff00ff) * i_41_ & ~0xff00ff) + ((i_43_ & 0xff00) * i_41_ & 0xff0000)) >> 8) + i_42_; } else i_18_++; } i_17_ += i_39_ + i_22_; i_18_ += i_39_ + i_21_; } } final void method703(char c, int i, int i_44_, int i_45_, boolean bool, Class72 class72, int i_46_, int i_47_) { if (class72 == null) fa(c, i, i_44_, i_45_, bool); else { i += anIntArray5089[c]; i_44_ += anIntArray5090[c]; int i_48_ = anIntArray5088[c]; int i_49_ = anIntArray5086[c]; int i_50_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5206; int i_51_ = i + i_44_ * i_50_; int i_52_ = i_50_ - i_48_; int i_53_ = 0; int i_54_ = 0; if (i_44_ < ((Class163_Sub1) aClass163_Sub1_5091).anInt5177) { int i_55_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5177 - i_44_; i_49_ -= i_55_; i_44_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5177; i_54_ += i_55_ * i_48_; i_51_ += i_55_ * i_50_; } if (i_44_ + i_49_ > ((Class163_Sub1) aClass163_Sub1_5091).anInt5193) i_49_ -= (i_44_ + i_49_ - ((Class163_Sub1) aClass163_Sub1_5091).anInt5193); if (i < ((Class163_Sub1) aClass163_Sub1_5091).anInt5186) { int i_56_ = ((Class163_Sub1) aClass163_Sub1_5091).anInt5186 - i; i_48_ -= i_56_; i = ((Class163_Sub1) aClass163_Sub1_5091).anInt5186; i_54_ += i_56_; i_51_ += i_56_; i_53_ += i_56_; i_52_ += i_56_; } if (i + i_48_ > ((Class163_Sub1) aClass163_Sub1_5091).anInt5178) { int i_57_ = (i + i_48_ - ((Class163_Sub1) aClass163_Sub1_5091).anInt5178); i_48_ -= i_57_; i_53_ += i_57_; i_52_ += i_57_; } if (i_48_ > 0 && i_49_ > 0) method2270(aByteArrayArray5087[c], (((Class163_Sub1) aClass163_Sub1_5091).anIntArray5214), i_45_, i_54_, i_51_, i_48_, i_49_, i_52_, i_53_, i, i_44_, anIntArray5088[c], class72, i_46_, i_47_); } } private final void method2271(byte[] is, int[] is_58_, int i, int i_59_, int i_60_, int i_61_, int i_62_, int i_63_, int i_64_) { for (int i_65_ = -i_62_; i_65_ < 0; i_65_++) { for (int i_66_ = -i_61_; i_66_ < 0; i_66_++) { int i_67_ = is[i_59_++] & 0xff; if (i_67_ != 0) { int i_68_ = ((((i & 0xff00ff) * i_67_ & ~0xff00ff) + ((i & 0xff00) * i_67_ & 0xff0000)) >> 8); i_67_ = 256 - i_67_; int i_69_ = is_58_[i_60_]; is_58_[i_60_++] = ((((i_69_ & 0xff00ff) * i_67_ & ~0xff00ff) + ((i_69_ & 0xff00) * i_67_ & 0xff0000)) >> 8) + i_68_; } else i_60_++; } i_60_ += i_63_; i_59_ += i_64_; } } }
Laine, who will play for Team Finland at the tournament, had knee surgery following the NHL Scouting Combine in June. He signed a three-year, entry-level contract on July 3. Winnipeg Jets forward prospect Patrik Laine, selected No. 2 in the 2016 NHL Draft, has been training daily in preparation for the World Cup of Hockey 2016, according to Jets coach Paul Maurice. "He was held out of (Jets) development camp for precautionary reasons, but he's back to full training and has been for quite some time," Maurice told NHL.com. "There will be zero repercussions moving forward." Maurice said he expects Laine, a right wing, to challenge for a spot on the Jets roster in training camp following his participation in the eight-team tournament, which will take place from Sept. 17 to Oct. 1 at Air Canada Centre in Toronto. "He's certainly going to be given the opportunity to excel right out of the gate," Maurice said. "I had another No. 2 overall pick when I was coach in Carolina in Eric Staal. In training camp and over the first half of the year, you could see the things Eric wanted to do, and you knew, because of who he was, that he would be able to do it. It was just a matter of time." Staal, the No. 2 pick in the 2003 NHL Draft by the Hurricanes, had 11 goals and 31 points in 81 games as a rookie in 2003-04. Laine had 33 points (17 goals, 16 assists) in 46 games for Tappara in Liiga, Finland's top league, last season. "Patrik is going to be able to do all those things he's always been able to do," Maurice said. "How long it takes him to do it, I don't know, but he's going to get a chance to play. He fits in to what we're trying to do as a hockey team, so you'll live with some mistakes that are youth-generated, but he's a very special talent and I would not be surprised if he comes in and is able to finish and put up numbers. "Of all the positions to join the NHL in, the wing is the most forgiving." Laine had seven goals and 12 points at the 2016 IIHF World Championship and was named tournament MVP for Finland, which won the silver medal. He was named MVP of the playoffs after helping Tappara win the championship. Laine also won a gold medal at the 2016 IIHF World Junior Championship. He could play against Jets teammate Blake Wheeler, who is a forward for Team USA. "We can all see his ability and the things he brings to the table," Wheeler told the Winnipeg Sun on Tuesday. "It creates a ton of excitement for us and obviously for the city. At the same time he's 18 years old and hasn't played a game in the NHL. You don't want to put too much on him too early, and have these high expectations that nobody can live up to. ... When he becomes the player he's going to be, he's going to be a huge piece for our organization." Maurice said the first piece of advice he'll give Laine when he arrives at training camp will be to get to know his teammates. "The hockey is going to come, the hockey is there, but all of these other things are also important," Maurice said. "I've coached a lot of good young players, I've coached a player who won the Calder Trophy as rookie of the year (Jeff Skinner, Carolina, 2010-11) and I've seen the ups and downs of those seasons they've had. If he has a great two weeks, I'm not going to get too excited about it; if he doesn't look right in the first two weeks, I'm not going to worry about it a bit. "This year for him is all about learning the League and becoming an NHL player and making lifelong friends. For him, there's a bunch of other guys on this team not far from his age and what we want to have happen is to have Patrik, Mark [Scheifele], Blake [Wheeler], Dustin Byfuglien and those young guys to start forming the bonds of a championship team. "Just the idea that you get to play here and play with them your whole career so get to know them, enjoy it, go out to lunch and enjoy being with each other." Laine is in Helsinki, Finland, preparing with Team Finland for the World Cup. Team Finland will remain in Helsinki from Sept. 5-9 before heading to Gothenburg, Sweden, for a pretournament game against Sweden on Sept. 10. Team Finland, Team Canada, Team Czech Republic, Team Europe, Team North America, Team Russia, Team Sweden and Team USA will compete in the two-week tournament. Team Finland plays its first game on Sept. 18 against Team North America (8 p.m. ET; ESPN2).
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import java.util.TimeZone; public class a{ public static long getQuot(String time1, String time2){ long quot = 0; SimpleDateFormat ft = new SimpleDateFormat("yyyy:MM:dd"); ft.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date date1 = ft.parse( time1 ); Date date2 = ft.parse( time2 ); quot = date1.getTime() - date2.getTime(); quot = quot / (1000 * 60 * 60 * 24); } catch (ParseException e) { e.printStackTrace(); } return quot; } public static void main(String[] args) throws Exception { Scanner r = new Scanner(System.in); String date1 = r.nextLine(); String date2 = r.nextLine(); long day = getQuot(date2,date1); System.out.println(Math.abs(day)); } }
. Vitamin D2 (160 000-240 000 IU/kg) produced during 5 days pronounced hypercalciemia and metastatic calcification of internal organs. Subcutaneous injection of sodium selenite (10 mg/kg) brought down the level of calcium in the blood plasma and decreased calcification of internal organs. Conjoint introduction of sodium selenite (30 gamma/kg) and of vitamin "E" (50 mg/kg) lowered the aortal calcinosis by 54 per cent, of the lung--by 93, of the heart--by 86 and of the kidney--by 96 per cent.
<gh_stars>1000+ import fs from "fs/promises"; import path from "path"; import { TransformStream } from "stream/web"; import { setImmediate, setTimeout } from "timers/promises"; import { useTmp } from "@miniflare/shared-test"; import { Watcher } from "@miniflare/watcher"; import anyTest, { ExecutionContext, Macro } from "ava"; // Only run watcher tests on macOS. The Watcher does work on Linux and Windows, // the tests are just very flaky. // TODO: make watcher tests more reliable :D const test = process.platform === "darwin" ? anyTest.serial : anyTest.skip; interface WatcherEvents { count: number; next: () => Promise<string>; } function useWatcher( t: ExecutionContext, forceRecursive?: boolean ): [watcher: Watcher, events: WatcherEvents] { const { readable, writable } = new TransformStream<string, string>(); const reader = readable.getReader(); const writer = writable.getWriter(); const events: WatcherEvents = { count: 0, next: async () => (await reader.read()).value ?? "", }; const watcher = new Watcher( (path) => { events.count++; void writer.write(path); }, { pollInterval: 50, createPollInterval: 50, forceRecursive } ); t.teardown(() => watcher.dispose()); return [watcher, events]; } test("PathWatcher: startCreatedWatcher: watches for file to be created", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testPath, "test"); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startCreatedWatcher: watches for directory to be created", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.mkdir(testPath); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startPollingWatcher: watches single files", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testPath, "test2"); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startPollingWatcher: watches for file to be created again if deleted", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.rm(testPath); t.is(await events.next(), testPath); t.is(events.count, 1); await fs.writeFile(testPath, "test"); t.is(await events.next(), testPath); t.is(events.count, 2); }); test("PathWatcher: startPollingWatcher: handles file being replaced by rename", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); const testTmpPath = testPath + "~"; await fs.writeFile(testPath, "0"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testTmpPath, "1"); await setTimeout(100); t.is(events.count, 0); await fs.rename(testTmpPath, testPath); t.is(await events.next(), testPath); t.is(events.count, 1); await fs.writeFile(testTmpPath, "2"); await setTimeout(100); t.is(events.count, 1); await fs.rename(testTmpPath, testPath); t.is(await events.next(), testPath); t.is(events.count, 2); }); const recursiveTitle = (title: string) => (providedTitle?: string, force?: boolean) => `PathWatcher: start${force ? "" : "Platform"}RecursiveWatcher: ${title}`; const recursiveRootMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await fs.writeFile(path.join(tmp, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(tmp, "test")); t.is(await events.next(), tmp); }; recursiveRootMacro.title = recursiveTitle("watches files in root directory"); test(recursiveRootMacro); test(recursiveRootMacro, true); const recursiveNestedMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); await fs.mkdir(nestedDir); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await fs.writeFile(path.join(nestedDir, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(nestedDir, "test")); t.is(await events.next(), tmp); }; recursiveNestedMacro.title = recursiveTitle( "watches files in nested directory" ); test(recursiveNestedMacro); test(recursiveNestedMacro, true); const recursiveNewMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await setImmediate(); await fs.mkdir(nestedDir); await fs.writeFile(path.join(nestedDir, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(nestedDir, "test")); t.is(await events.next(), tmp); }; recursiveNewMacro.title = recursiveTitle( "watches files in newly created directory" ); test(recursiveNewMacro); test(recursiveNewMacro, true); const recursiveNewNestedMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const tmp1 = path.join(tmp, "1"); const tmp2 = path.join(tmp, "2"); const tmp2Dir = path.join(tmp2, "dir"); const tmp2Nested = path.join(tmp2Dir, "nested"); const tmp2NestedFile = path.join(tmp2Nested, "test.txt"); await fs.mkdir(tmp1); await fs.mkdir(tmp2Nested, { recursive: true }); await fs.writeFile(tmp2NestedFile, "1"); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp1); await setImmediate(); // Move tmp2 to inside tmp1 const newTmp2 = path.join(tmp1, "tmp2"); await fs.rename(tmp2, newTmp2); t.is(await events.next(), tmp1); await setTimeout(100); t.is(events.count, 1); // Update tmp2NestedFile in tmp1 await fs.writeFile(path.join(newTmp2, "dir", "nested", "test.txt"), "2"); t.is(await events.next(), tmp1); t.is(events.count, 2); // Create new file in dir await fs.writeFile(path.join(newTmp2, "dir", "new1.txt"), "1"); t.is(await events.next(), tmp1); t.is(events.count, 3); // Create new file in nested dir await fs.writeFile(path.join(newTmp2, "dir", "nested", "new2.txt"), "2"); t.is(await events.next(), tmp1); t.is(events.count, 4); }; recursiveNewNestedMacro.title = recursiveTitle( "watches files in newly created nested directories" ); test(recursiveNewNestedMacro); test(recursiveNewNestedMacro, true); const recursiveNestedDeleteMacro: Macro<[force?: boolean]> = async ( t, force ) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); const nestedTestPath = path.join(nestedDir, "test.txt"); await fs.mkdir(nestedDir); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await setImmediate(); // Delete nested directory await fs.rmdir(nestedDir); t.is(await events.next(), tmp); await setTimeout(100); t.is(events.count, 1); // Recreate directory await fs.mkdir(nestedDir); t.is(await events.next(), tmp); t.is(events.count, 2); // Create file in directory await fs.writeFile(nestedTestPath, "2"); t.is(await events.next(), tmp); t.is(events.count, 3); }; recursiveNestedDeleteMacro.title = recursiveTitle( "handles nested directory being deleted and recreated again" ); test(recursiveNestedDeleteMacro); test(recursiveNestedDeleteMacro, true); const recursiveRootDeleteMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const root = path.join(tmp, "root"); const newRoot = path.join(tmp, "root2"); const newRootDir = path.join(newRoot, "dir"); const newRootDirNested = path.join(newRootDir, "nested"); const newRootDirNestedFile = path.join(newRootDirNested, "test.txt"); await fs.mkdir(root); await fs.mkdir(newRootDirNested, { recursive: true }); await fs.writeFile(newRootDirNestedFile, "1"); const [watcher, events] = useWatcher(t, force); watcher.watch(root); await setImmediate(); // Delete root directory and move new root in it's place await fs.rmdir(root); t.is(await events.next(), root); await setTimeout(100); t.is(events.count, 1); await fs.rename(newRoot, root); t.is(await events.next(), root); t.is(events.count, 2); // Update file in newly copied root await fs.writeFile(path.join(root, "dir", "nested", "test.txt"), "2"); t.is(await events.next(), root); t.is(events.count, 3); }; recursiveRootDeleteMacro.title = recursiveTitle( "handles root directory being deleted and recreated again" ); test(recursiveRootDeleteMacro); test(recursiveRootDeleteMacro, true); const recursiveRootReplaceFileMacro: Macro<[force?: boolean]> = async ( t, force ) => { const tmp = await useTmp(t); const root = path.join(tmp, "root"); await fs.mkdir(root); const [watcher, events] = useWatcher(t, force); watcher.watch(root); await setImmediate(); // Delete root directory and replace with file await fs.rmdir(root); t.is(await events.next(), root); await setTimeout(100); t.is(events.count, 1); await fs.writeFile(root, "1"); t.is(await events.next(), root); t.is(events.count, 2); await fs.writeFile(root, "2"); t.is(await events.next(), root); t.is(events.count, 3); }; recursiveRootReplaceFileMacro.title = recursiveTitle( "handles root directory being deleted and replaced with file of same name" ); test(recursiveRootReplaceFileMacro); test(recursiveRootReplaceFileMacro, true); test("PathWatcher: dispose: cleans up polling watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("PathWatcher: dispose: cleans up platform recursive watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t); watcher.watch(tmp); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("PathWatcher: dispose: cleans up recursive watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t, true); watcher.watch(tmp); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("Watcher: watches and un-watches files", async (t) => { const tmp = await useTmp(t); const test1Path = path.join(tmp, "test1.txt"); const test2Path = path.join(tmp, "test2.txt"); await fs.writeFile(test1Path, "test1 value1"); await fs.writeFile(test2Path, "test2 value1"); const [watcher, events] = useWatcher(t); watcher.watch([test1Path, test2Path]); // Check event emitted on change await fs.writeFile(test2Path, "test2 value2"); t.is(await events.next(), test2Path); // Unwatch file and check no longer watcher watcher.unwatch(test2Path); await fs.writeFile(test2Path, "test2 value2"); await setTimeout(100); await fs.writeFile(test1Path, "test1 value2"); t.is(await events.next(), test1Path); }); test("Watcher: watches files once", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "value1"); const [watcher, events] = useWatcher(t); watcher.watch([testPath, testPath]); watcher.watch(testPath); await fs.writeFile(testPath, "value2"); t.is(await events.next(), testPath); await setTimeout(100); t.is(events.count, 1); }); test("Watcher: dispose: cleans up watchers", async (t) => { const tmp = await useTmp(t); const test1Path = path.join(tmp, "test1.txt"); const test2Path = path.join(tmp, "test2.txt"); await fs.writeFile(test1Path, "test1 value1"); await fs.writeFile(test2Path, "test2 value1"); const [watcher, events] = useWatcher(t); watcher.watch([test1Path, test2Path]); watcher.dispose(); await fs.writeFile(test1Path, "test1 value2"); await fs.writeFile(test2Path, "test2 value2"); await setTimeout(100); t.is(events.count, 0); });
/******************************************************************************* * build_bin_img * create image in binary format and write it into output stream * INPUT: * opt user options * buf_in mmapped input file * OUTPUT: * none * RETURN: * 0 on success *******************************************************************************/ int build_bin_img(USER_OPTIONS *opt, char *buf_in) { FILE *f_ds = NULL; FILE *f_desc[4] = {NULL}; char *tmpImg = NULL; int hex_len = 0; int one_file_len = 0; int size_written = 0; int alignment = 0; int hex_unaligned_len = 0; unsigned char *hex8 = NULL; unsigned char tmp8; unsigned short *hex16 = NULL; unsigned short tmp16; unsigned long *hex32 = NULL; unsigned long tmp32; unsigned long tmp32low; int i; int fidx; int files_num = 1; int error = 1; hex_len = fs_stat.st_size; alignment = opt->hex_width >> 3; hex_unaligned_len = fs_stat.st_size & (alignment - 1); if (hex_unaligned_len) { hex_len -= hex_unaligned_len; hex_len += alignment; } if (opt->fname.romd) files_num = 4; else if (opt->fname.romc) files_num = 3; else if (opt->fname.hdr_out) files_num = 2; one_file_len = hex_len / files_num; for (i = 0; i < files_num; i++) { f_desc[i] = fopen(opt->fname_arr[i + 1], "w"); if (f_desc[i] == NULL) goto bin_image_end; } tmpImg = malloc(hex_len); if (tmpImg == NULL) goto bin_image_end; memset(tmpImg, 0, (hex_len)); memcpy(tmpImg, buf_in, fs_stat.st_size); switch (opt->hex_width) { case 8: hex8 = (unsigned char *)tmpImg; if (files_num != 2) { fprintf(stderr, "Must supply two output file names for this width!\n"); goto bin_image_end; } for (fidx = 1; (fidx >= 0) && (hex_len > 0); fidx--) { f_ds = f_desc[1 - fidx]; for (; hex_len > (fidx * one_file_len); hex_len--) { tmp8 = *hex8; for (i = 0; i < opt->hex_width; i++) { fprintf(f_ds, "%d", ((tmp8 & 0x80) >> 7)); tmp8 <<= 1; } fprintf(f_ds, "\n"); hex8++; size_written += 1; } } break; case 16: hex16 = (unsigned short *)tmpImg; for (; hex_len > 0; hex_len -= 2) { tmp16 = *hex16; for (i = 0; i < opt->hex_width; i++) { fprintf(f_desc[0], "%d", ((tmp16 & 0x8000) >> 15)); tmp16 <<= 1; } fprintf(f_desc[0], "\n"); hex16++; size_written += 2; } break; case 32: hex32 = (long *)tmpImg; for (fidx = files_num - 1; (fidx >= 0) && (hex_len > 0); fidx--) { f_ds = f_desc[files_num - 1 - fidx]; for (; hex_len > (fidx * one_file_len); hex_len -= 4) { tmp32 = *hex32; for (i = 0; i < opt->hex_width; i++) { fprintf(f_ds, "%ld", ((tmp32 & 0x80000000) >> 31)); tmp32 <<= 1; } fprintf(f_ds, "\n"); hex32++; size_written += 4; } } break; case 64: hex32 = (long *)tmpImg; for (; hex_len > 0; hex_len -= 8) { tmp32low = *hex32++; tmp32 = *hex32++; for (i = 0; i < 32; i++) { fprintf(f_desc[0], "%ld", ((tmp32 & 0x80000000) >> 31)); tmp32 <<= 1; } for (i = 0; i < 32; i++) { fprintf(f_desc[0], "%ld", ((tmp32low & 0x80000000) >> 31)); tmp32low <<= 1; } fprintf(f_desc[0], "\n"); size_written += 8; } break; } error = 0; bin_image_end: if (tmpImg) free(tmpImg); for (i = 0; i < files_num; i++) { if (f_desc[i] != NULL) fclose(f_desc[i]); } return error; }
def runner( play_file_path: Union[Lintable, str], default_rules_collection: RulesCollection ) -> Runner: return Runner(play_file_path, rules=default_rules_collection)
// Package filters contains implementations of unilog filters. package filters
<filename>cmd/ls.go package cmd import ( "github.com/applinh/elephant/commands" "github.com/spf13/cobra" ) var listCmd = &cobra.Command{ Use: "ls", Short: "List all running stacks", Long: `List all running stacks`, Run: func(cmd *cobra.Command, args []string) { commands.List(db) }, } func init() { rootCmd.AddCommand(listCmd) //walkCmd.Flags().StringP("file", "f", "", "compose file") }
Yes-Associated Protein Promotes Angiogenesis via Signal Transducer and Activator of Transcription 3 in Endothelial Cells Rationale: Angiogenesis is a complex process regulating endothelial cell (EC) functions. Emerging lines of evidence support that YAP (Yes-associated protein) plays an important role in regulating the angiogenic activity of ECs. Objective: The objective of this study was to specify the effect of EC YAP on angiogenesis and its underlying mechanisms. Method and Results: In ECs, vascular endothelial growth factor reduced YAP phosphorylation time and dose dependently and increased its nuclear accumulation. Using Tie2Cre-mediated YAP transgenic mice, we found that YAP promoted angiogenesis in the postnatal retina and tumor tissues. Mass spectrometry revealed signal transducer and activator of transcription 3 (STAT3) as a potential binding partner of YAP in ECs. Western blot and immunoprecipitation assays indicated that binding with YAP prolonged interleukin 6–induced STAT3 nuclear accumulation by blocking chromosomal maintenance 1–mediated STAT3 nuclear export without affecting its phosphorylation. Moreover, angiopoietin-2 expression induced by STAT3 was enhanced by YAP overexpression in ECs. Finally, a selective STAT3 inhibitor or angiopoietin-2 blockage partly attenuated retinal angiogenesis in Tie2Cre-mediated YAP transgenic mice. Conclusions: YAP binding sustained STAT3 in the nucleus to enhance the latter’s transcriptional activity and promote angiogenesis via regulation of angiopoietin-2.
/** * read a word from file * * @return the word we read * @throws IOException */ public String readWord() throws IOException { StringBuffer s = new StringBuffer(); char c; skipSpaces(); while (!Character.isWhitespace(c = get()) && !eol() && !eof()) { s.append(c); } putback(c); return s.toString(); }
/** * description: itext api client * * @author zhouxinlei */ @Slf4j public class ITextClient { public float top = 785; /** * 总宽度 */ public float totalWidth = 550; /** * 左边空白宽度 */ public float left = 55; /** * 当前左边距,随着文本的追加而增长 */ public float currLeft = 55; public float bindLeft = 35; public String fontPath = ""; public String fileName = ""; public String filePath = ""; public PdfWriter pdfWriter; public PdfDocument pdfDocument; public PdfDocumentInfo documentInfo; public PdfPage pdfPage; public Document document; public PdfCanvas pdfCanvas; public Canvas canvas; public PdfFont font; public int pageNum = 0; public PageSize pageSize = PageSize.A4; /** * html转pdf * * @param html html元素 * @return byte[] byte数组 * @throws IOException IO异常 */ public static byte[] html2Pdf(String html) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ConverterProperties props = new ConverterProperties(); // 提供解析用的字体 FontProvider fp = new FontProvider(); // 添加标准字体库、无中文 fp.addStandardPdfFonts(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 自定义字体路径、解决中文,可先用绝对路径测试。 fp.addDirectory(classLoader.getResource("font").getPath()); props.setFontProvider(fp); // props.setBaseUri(baseResource); // 设置html资源的相对路径 HtmlConverter.convertToPdf(html, outputStream, props); byte[] result = outputStream.toByteArray(); outputStream.close(); return result; } public void initPdfData() { try { String osName = System.getProperty("os.name"); String window = "Window"; if (osName.contains(window)) { fontPath = "C:/Windows/Fonts/simfang.ttf"; } else { fontPath = "/usr/share/fonts/chinese/simfang.ttf"; } File path = new File(ResourceUtils.getURL("classpath:").getPath()); File documentDirs = new File(path.getAbsolutePath(), "static/document/"); if (!documentDirs.exists()) { documentDirs.mkdirs(); } filePath = documentDirs.getPath() + "/"; File file = new File(filePath + fileName); File fileParent = file.getParentFile(); if (!fileParent.exists()) { fileParent.mkdirs(); } // 1、创建流对象 pdfWriter = new PdfWriter(file); // 2、创建文档对象 pdfDocument = new PdfDocument(pdfWriter); document = new Document(pdfDocument); pdfDocument.setTagged(); pdfDocument.getCatalog().setLang(new PdfString("zh-cn")); pdfDocument.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(false)); font = PdfFontFactory.createFont(fontPath, "Identity-H", false); documentInfo = pdfDocument.getDocumentInfo(); addNewPage(); } catch (IOException e) { log.error(e.getMessage()); } } /** * 新建页面 */ public void addNewPage() { pdfDocument.addNewPage(); pageNum++; pdfPage = pdfDocument.getPage(pageNum); pdfCanvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas = new Canvas(pdfCanvas, pdfDocument, pdfPage.getPageSize()); } /** * 页眉 * * @param data @ */ public void addHead(String data) { Paragraph paragraph = new Paragraph(); paragraph.add(data); paragraph.setFont(font).setFontSize(20); paragraph.setBold(); paragraph.setMarginTop(50); paragraph.setTextAlignment(TextAlignment.CENTER); canvas.add(paragraph); pdfCanvas.setStrokeColor(DeviceCmyk.BLACK).setLineWidth(0.7f).moveTo(left, top - 40).lineTo(totalWidth, top - 40) .stroke(); pdfCanvas.moveTo(left, top - 43).lineTo(totalWidth, top - 43).stroke(); } /** * 页尾 * * @param data 字符串 * @param top 上边距 */ public void addFooter(String data, float top) { pdfCanvas.setStrokeColor(DeviceCmyk.BLACK).setLineWidth(1.5f).moveTo(left, top).lineTo(totalWidth, top).stroke(); } /** * 整横线 * * @param lineWidth 线条粗细 * @param left x坐标 * @param top y坐标 */ public void addFullLine(float lineWidth, float left, float top) { PdfCanvas canvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas.setStrokeColor(DeviceCmyk.BLACK).setLineWidth(lineWidth).moveTo(left, top).lineTo(totalWidth, top).stroke(); } /** * 装订线 */ public void addBindingLine() { PdfCanvas canvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas.setStrokeColor(DeviceCmyk.BLACK); canvas.setLineDash(3, 3, 10); canvas.setLineWidth(0.5f).moveTo(bindLeft, 680).lineTo(bindLeft, 552).stroke(); addPrintText(537, bindLeft - 6, 13, "装"); canvas.setLineWidth(0.5f).moveTo(bindLeft, 532).lineTo(bindLeft, 404).stroke(); addPrintText(389, bindLeft - 6, 13, "订"); canvas.setLineWidth(0.5f).moveTo(bindLeft, 384).lineTo(bindLeft, 256).stroke(); addPrintText(241, bindLeft - 6, 13, "线"); canvas.setLineWidth(0.5f).moveTo(bindLeft, 236).lineTo(bindLeft, 100).stroke(); } /** * 指定竖线长度 * * @param lineWidth 线条粗细 * @param left x坐标 * @param topStart y坐标 * @param topEnd 结束坐标 */ public void addVerticalLine(float lineWidth, float left, float topStart, float topEnd) { PdfCanvas canvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas.setStrokeColor(DeviceCmyk.BLACK); canvas.setLineWidth(lineWidth).moveTo(left, topStart).lineTo(left, topEnd).stroke(); } /** * 指定横线长度 * * @param lineWidth 线条粗细 * @param left x坐标 * @param right y坐标 * @param top 结束坐标 */ public void addLine(float lineWidth, float left, float right, float top) { PdfCanvas canvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas.setStrokeColor(DeviceCmyk.BLACK).setLineWidth(lineWidth).moveTo(left, top).lineTo(right, top).stroke(); } /** * 增加矩形线 * * @param lineWidth 线条粗细 * @param left 左边距 * @param right 右边距 * @param top 上边距 * @param height 高度 */ public void addRectLine(float lineWidth, float left, float right, float top, float height) { float topEnd = top - height; PdfCanvas canvas = new PdfCanvas(pdfDocument.getPage(pageNum)); canvas.setStrokeColor(DeviceCmyk.BLACK); canvas.setLineWidth(lineWidth); canvas.moveTo(left, top).lineTo(right, top).stroke(); canvas.moveTo(left, topEnd).lineTo(right, topEnd).stroke(); canvas.setLineWidth(lineWidth).moveTo(left, top).lineTo(left, topEnd).stroke(); canvas.setLineWidth(lineWidth).moveTo(right, top).lineTo(right, topEnd).stroke(); } /** * 添加一个段落 exemple 比如一段文字或者少于一行的可以使用 * * @param data 文本 * @param fontSize 字体大小 * @param left 左边距 * @param top 上边距 * @param isBlod 是否加粗 * @param isCenter 是否居中 * @param lineIndent @ */ public void addParagraphText(String data, float fontSize, float left, float top, boolean isBlod, boolean isCenter, boolean lineIndent) { Paragraph paragraph = new Paragraph(); paragraph.add(data); paragraph.setWidth(510); paragraph.setFont(font).setFontSize(fontSize); paragraph.setMarginTop(top); setParagraphStyle(left, isBlod, isCenter, lineIndent, paragraph); } private void setParagraphStyle(float left, boolean isBlod, boolean isCenter, boolean lineIndent, Paragraph paragraph) { if (isBlod) { paragraph.setBold(); } if (left == 0) { paragraph.setMarginLeft(45); } else { paragraph.setMarginLeft(left); } if (isCenter) { paragraph.setTextAlignment(TextAlignment.CENTER); } if (lineIndent) { paragraph.setFirstLineIndent(50); } canvas.add(paragraph); } /** * 指定位置添加文本内容 * * @param data 文本 * @param fontSize 字体大小 * @param left 左边距 * @param top 上边距 * @param isBlod 是否加粗 * @param isCenter 是否居中 * @param lineIndent @ */ public void addFixedPositionText(String data, float fontSize, float left, float top, boolean isBlod, boolean isCenter, boolean lineIndent) { Paragraph paragraph = new Paragraph(); paragraph.add(data); paragraph.setWidth(500); paragraph.setFont(font).setFontSize(fontSize); paragraph.setFixedPosition(left, top, 500); setParagraphStyle(left, isBlod, isCenter, lineIndent, paragraph); } /** * 可控文本位置填充(适合短文本) * * @param top 上边距 * @param left 左边距 * @param fontSize 字体大小 * @param str 文本 */ public void addPrintText(float top, float left, float fontSize, Object str) { pdfCanvas.beginText().setFontAndSize(font, fontSize).moveText(left, top).showText(String.valueOf(str)) .endText(); } /** * 垂直文本添加 * * @param top 上边距 * @param left 左边距 * @param fontSize 字体大小 * @param str 文本 */ public void addVerticalText(float top, float left, float fontSize, String str) { Paragraph paragraph = new Paragraph(); paragraph.add(str); paragraph.setWidth(15); paragraph.setFont(font).setFontSize(fontSize); paragraph.setFixedPosition(left, top, 15); canvas.add(paragraph); canvas.flush(); } /** * 添加图片 * * @param left 左边距 * @param top 上边距 * @param width 宽度 * @param imagePath 图片路径 * @throws MalformedURLException 异常 */ public void addImage(float left, float top, float width, String imagePath) throws MalformedURLException { Image fox = new Image(ImageDataFactory.create(imagePath)); fox.setFixedPosition(left, top, width); document.add(fox); } public void addImageByBase64(float left, float top, float width, String base64) throws MalformedURLException { String imgBase64 = base64.replaceAll("data:image/png;base64,", ""); byte[] data = Base64Utils.decodeFromString(imgBase64); Image fox = new Image(ImageDataFactory.create(data)); fox.setFixedPosition(left, top, width); canvas.add(fox); } public String pdfToImg(String pdfPath) { File file = new File(pdfPath); PDDocument pdDocument; try { String orderPath = file.getParent(); String fileName = file.getName(); int index = fileName.indexOf("."); fileName = fileName.substring(0, index); String imgPath = orderPath + File.separator + fileName + ".png"; List<BufferedImage> pnglist = new ArrayList<>(); pdDocument = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(pdDocument); for (int i = 0; i < pdDocument.getNumberOfPages(); i++) { BufferedImage image = renderer.renderImageWithDPI(i, 100); pnglist.add(image); } imageMerging(pnglist, imgPath); pdDocument.close(); return imgPath; } catch (IOException e) { log.error(e.getMessage()); return null; } } public void imageMerging(List<BufferedImage> pngList, String outPath) throws IOException { int height = 0, extWidth = 0, maxWidth = 0, extHeight, extHeight1, picNum = pngList.size(); int[] heightArray = new int[picNum]; int[] widthArray = new int[picNum]; BufferedImage buffer; List<int[]> imgRgb = new ArrayList<>(); int[] extImgRgb; for (BufferedImage bufferedImage : pngList) { buffer = bufferedImage; if (buffer.getWidth() > maxWidth) { maxWidth = buffer.getWidth(); } } for (int i = 0; i < picNum; i++) { buffer = pngList.get(i); heightArray[i] = extHeight = buffer.getHeight(); widthArray[i] = extWidth = buffer.getWidth(); height += extHeight; extImgRgb = new int[extWidth * extHeight]; extImgRgb = buffer.getRGB(0, 0, extWidth, extHeight, extImgRgb, 0, extWidth); imgRgb.add(extImgRgb); } extHeight = 0; BufferedImage imageResult = new BufferedImage(extWidth, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < picNum; i++) { extHeight1 = heightArray[i]; extWidth = widthArray[i]; if (i != 0) { extHeight += heightArray[i - 1]; } imageResult.setRGB((maxWidth - extWidth) / 2, extHeight, extWidth, extHeight1, imgRgb.get(i), 0, extWidth); } File outFile = new File(outPath); ImageIO.write(imageResult, "png", outFile); } }
/* * Predicate returning @c true if this SedSurface's "xDataReference" attribute * is set. */ bool SedSurface::isSetXDataReference() const { return (mXDataReference.empty() == false); }
Use of the resuscitation room for trauma. This study was designed to assess the use of the resuscitation room for trauma cases, the information being used to identify particular problem areas and put forward possible solutions. One hundred and fifty consecutive resuscitation room trauma patients were studied prospectively, with details being obtained both at the time of admission and 48 h later. The results have highlighted the importance of all patients with major trauma being assessed and treated by senior medical staff. In addition, the presence of more than one doctor when managing any resuscitation room trauma patient was shown to be beneficial. Many cases were seen by SHO only, and there is a need for more senior medical staff to be informed of every trauma patient entering the resuscitation room. Recording of vital signs was found to be less than satisfactory and there is a necessity for a departmental policy on this.
/* break an abstraction and copy some code for performance purposes */ static int local_book_besterror(codebook *book,float *a){ int dim=book->dim,i,k,o; int best=0; encode_aux_threshmatch *tt=book->c->thresh_tree; for(k=0,o=dim;k<dim;++k){ float val=a[--o]; i=tt->threshvals>>1; if(val<tt->quantthresh[i]){ if(val<tt->quantthresh[i-1]){ for(--i;i>0;--i) if(val>=tt->quantthresh[i-1]) break; } }else{ for(++i;i<tt->threshvals-1;++i) if(val<tt->quantthresh[i])break; } best=(best*tt->quantvals)+tt->quantmap[i]; } if(book->c->lengthlist[best]<=0){ const static_codebook *c=book->c; int i,j; float bestf=0.f; float *e=book->valuelist; best=-1; for(i=0;i<book->entries;i++){ if(c->lengthlist[i]>0){ float This=0.f; for(j=0;j<dim;j++){ float val=(e[j]-a[j]); This+=val*val; } if(best==-1 || This<bestf){ bestf=This; best=i; } } e+=dim; } } { float *ptr=book->valuelist+best*dim; for(i=0;i<dim;i++) *a++ -= *ptr++; } return(best); }
mat=[[1,2,3,4,5,6,7,8,9], [2,4,6,8,0,2,4,6,8,0], [3,6,9,2,5,8,1,4,7,0], [4,8,2,6,0,4,8,2,6,0], [5,0,5,0,5,0,5,0,5,0], [6,2,8,4,0,6,2,8,4,0], [7,4,1,8,5,2,9,6,3,0], [8,6,4,2,0,8,6,4,2,0], [9,8,7,6,5,4,3,2,1,0]] k,r=map(int,input().split()) k=k%10 if(k==0): print(1) else: ans=-1 for i in range(10): if(r==mat[k-1][i] or mat[k-1][i]==0): ans=i+1 break if(ans==-1): ans=10 print(ans)
/** * Remove already registered values for the specified HTTP parameter, if any. * * @param sName * Parameter name * @return this */ @Nonnull public MockHttpServletRequest removeParameter (@Nonnull final String sName) { ValueEnforcer.notNull (sName, "Name"); m_aParameters.remove (sName); return this; }
/** * Set the state of the app to editing * the feature on the map. */ public void editOnMap(){ ArbiterState.getArbiterState().editingFeature(feature, layerId); mapListener.getMapChangeHelper().setEditMode(GeometryEditor.Mode.EDIT); dismiss(); }
export * from './Main'; export * from './NewDocument' export * from './PdfViewer' export * from './Products'
/* Copyright 2021 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.rulemanager; import static java.lang.String.format; public enum OfVersion { OF_12, OF_13, OF_14, OF_15; /** * Converts String value to enum value. */ public static OfVersion of(String version) { switch (version) { case "OF_12": return OF_12; case "OF_13": return OF_13; case "OF_14": return OF_14; case "OF_15": return OF_15; default: throw new IllegalStateException(format("Can't parse OpenFlow Version %s", version)); } } }
#include <QtGui/QApplication> #include "GUI/windowcontroller.h" #include "GuiServices/AccessControl.h" #include "GuiServices/PatientData.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { QApplication a(argc, argv); AccessControl *ac = new AccessControl(); PatientData *pd = new PatientData(); WindowController *wc = new WindowController(ac, pd); try { //Pre-added users since there is no sysadmin interface ClientData cd = ClientData::getInstance(); if(NULL == cd.getAdminAssistant(1)) { AdminAssistant user; user.setUsername("AdminAssistant"); cd.create(&user); } if(NULL == cd.getPhysician(2)) { Physician user; user.setUsername("Physician"); user.setFirstName("Bob"); user.setLastName("Loblaw"); user.setPhysicianId(1); cd.create(&user); } if(NULL == cd.getPhysician(3)) { Physician user; user.setUsername("OtherPhysician"); user.setFirstName("Whirling"); user.setLastName("Dervish"); user.setPhysicianId(2); cd.create(&user); } wc->start(); } catch(string err) { cout << "FATAL EXCEPTION: " << err << endl; } catch(char const * err) { cout << "FATAL EXCEPTION: " << err << endl; } return 0; }
/** * @author Rudenko, Latushkin * @created 24/09/2021 * @project Task24_09 */ public class Task24_09 { public static void main(String[] args) { Integer[] arrayOfInts = new Integer[6]; for (int i = 0; i < arrayOfInts.length; i++) { // генерация рандомных чисел от -15 до 15 arrayOfInts[i] = (int) Math.round((Math.random() * 30) - 15); } Set<Integer> mySet = new HashSet<Integer>(); Collections.addAll(mySet, arrayOfInts); if (arrayOfInts.length > mySet.size()) { System.out.println("В массиве есть дубликаты"); } else { System.out.println("В массиве нет дубликатов"); } } }
import networkx as nx import uuid from clang.cindex import CursorKind, TokenKind def is_namespace(node): if node.kind in [CursorKind.NAMESPACE]: return True return False def is_function(node): if node.kind in [CursorKind.FUNCTION_DECL, CursorKind.FUNCTION_TEMPLATE, CursorKind.CXX_METHOD, CursorKind.DESTRUCTOR, CursorKind.CONSTRUCTOR]: if node.is_definition(): not_empty = False for _ in node.get_children(): not_empty = True break return not_empty return False def is_class(node): return node.kind in [CursorKind.CLASS_TEMPLATE, CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION, CursorKind.CLASS_DECL] def is_literal(node): return node.kind in [CursorKind.INTEGER_LITERAL, CursorKind.FLOATING_LITERAL, CursorKind.IMAGINARY_LITERAL, CursorKind.STRING_LITERAL, CursorKind.CHARACTER_LITERAL] def is_template_parameter(node): return node.kind in [CursorKind.TEMPLATE_TYPE_PARAMETER, CursorKind.TEMPLATE_TEMPLATE_PARAMETER] def is_reference(node): return node.kind in [CursorKind.DECL_REF_EXPR, CursorKind.MEMBER_REF_EXPR] def is_operator(node): return node.kind in [CursorKind.BINARY_OPERATOR, CursorKind.UNARY_OPERATOR, CursorKind.COMPOUND_ASSIGNMENT_OPERATOR] def is_call_expr(node): return node.kind == CursorKind.CALL_EXPR binary_operators = ['+', '-', '*', '/', '%', '&', '|'] unary_operators = ['++', '--'] comparison_operators = ['==', '<=', '>=', '<', '>', '!=', '&&', '||'] unary_assignment_operators = [op + '=' for op in binary_operators] assignment_operators = ['='] + unary_assignment_operators def is_operator_token(token): if token in binary_operators: return True if token in unary_operators: return True if token in comparison_operators: return True if token in unary_assignment_operators: return True if token in assignment_operators: return True def get_id(): node_id = uuid.uuid1() return node_id.int def add_node(ast_node, graph): try: node_id = ast_node.hash kind = ast_node.kind.name graph.add_node(node_id, label=kind) # print("Cursor kind : {0}".format(kind)) if ast_node.kind.is_declaration(): add_declaration(node_id, ast_node, graph) elif is_literal(ast_node): add_literal(node_id, ast_node, graph) elif is_reference(ast_node): add_reference(node_id, ast_node, graph) elif is_operator(ast_node): add_operator(node_id, ast_node, graph) elif is_call_expr(ast_node): add_call_expr(node_id, ast_node, graph) except Exception as e: msg = 'Error: {0} in:\n'.format(str(e)) msg += 'Filename : {0}\n'.format(ast_node.location.file.name) msg += 'Start {0}:{1}'.format(ast_node.extent.start.line, ast_node.extent.start.column) msg += 'End {0}:{1}'.format(ast_node.extent.end.line, ast_node.extent.end.column) raise Exception(msg) def add_child(graph, parent_id, name): child_id = get_id() assert len(name) > 0, "Missing node name" graph.add_node(child_id, label=name) graph.add_edge(parent_id, child_id) def add_call_expr(parent_id, ast_node, graph): expr_type = ast_node.type.spelling add_child(graph, parent_id, expr_type) def fix_cpp_operator_spelling(op_name): if op_name == '|': return 'OPERATOR_BINARY_OR' elif op_name == '||': return 'OPERATOR_LOGICAL_OR' elif op_name == '|=': return 'OPERATOR_ASSIGN_OR' elif op_name == ',': return 'OPERATOR_COMMA' else: return op_name def add_operator(parent_id, ast_node, graph): name_token = None for token in ast_node.get_tokens(): if is_operator_token(token.spelling): name_token = token break if not name_token: filename = ast_node.location.file.name with open(filename, 'r') as fh: contents = fh.read() code_str = contents[ast_node.extent.start.offset: ast_node.extent.end.offset] for ch in code_str: if ch in binary_operators: add_child(graph, parent_id, fix_cpp_operator_spelling(ch)) else: name = name_token.spelling add_child(graph, parent_id, fix_cpp_operator_spelling(name)) # print("\tName : {0}".format(name)) def add_reference(parent_id, ast_node, graph): if ast_node.kind in [CursorKind.DECL_REF_EXPR, CursorKind.MEMBER_REF_EXPR]: name = "unknown" for token in ast_node.get_tokens(): if token.kind == TokenKind.IDENTIFIER: name = token.spelling break else: name = ast_node.spelling add_child(graph, parent_id, name) # print("\tName : {0}".format(name)) def add_literal(parent_id, ast_node, graph): if ast_node.kind in [CursorKind.STRING_LITERAL, CursorKind.CHARACTER_LITERAL]: add_child(graph, parent_id, 'STRING_VALUE') else: token = next(ast_node.get_tokens(), None) if token: value = token.spelling add_child(graph, parent_id, value) # print("\tValue : {0}".format(value)) def add_declaration(parent_id, ast_node, graph): is_func = False if is_function(ast_node): is_func = True return_type = ast_node.type.get_result().spelling if len(return_type) > 0: add_child(graph, parent_id, return_type) else: declaration_type = ast_node.type.spelling if len(declaration_type) > 0: add_child(graph, parent_id, declaration_type) # print("\tDecl type : {0}".format(declaration_type)) # we skip function names to prevent over-fitting in the code2seq learning tasks if not is_template_parameter(ast_node) and not is_func: name = ast_node.spelling # handle unnamed declarations if len(name) == 0: name = ast_node.kind.name + "_UNNAMED" add_child(graph, parent_id, name) # print("\tName : {0}".format(name)) def ast_to_graph(ast_start_node, max_depth): g = nx.Graph() stack = [(ast_start_node, 0)] parent_map = {ast_start_node.hash: None} while stack: ast_node, depth = stack.pop() node_id = ast_node.hash if not g.has_node(node_id): add_node(ast_node, g) parent_id = parent_map[node_id] if parent_id is not None: g.add_edge(parent_id, node_id) # Ignore too deep trees if max_depth == 0 or depth <= max_depth: for child_node in ast_node.get_children(): stack.append((child_node, depth + 1)) parent_map[child_node.hash] = node_id return g
words, time = [int(i) for i in input().split()] seconds = [int(i) for i in input().split()] wordsOnDispl = 1 for i in range(1, words): if seconds[i]-seconds[i-1] <= time: # Same as b-a <= time wordsOnDispl += 1 else: wordsOnDispl = 0 wordsOnDispl += 1 print(wordsOnDispl)
Gold has been discovered in an Irish county and we want some of it Patience is a virtue. If you have a friend that always told you that there's good land in Monaghan then they've just been proven right. After years of soil sampling, trenching and core drilling the company Conroy Gold have finally struck a gold-in-soil substance in a relatively high quantity estimated to the value of €150 million. The experts claim the valuable mineral is scattered around the area in a region of 300m by 700m with likelihood of further gold in the surrounding area of Monaghan and into Cavan and Armagh. The company is now looking at setting up its first Gold mine in Clay Lake, Clontibret and potentially Glenish and to the south of Slieve Glah. Unfortunately, before you head out into the river with a net hoping to catch your own bit of the lucky stuff, a spokesperson has said due to the way the gold is lodged you could spend the rest of your life in a river and never find a piece. So maybe leave it to the experts. Still, if you know anyone from the Farney County then it's probably no harm in asking them for a fiver. Hat-Tip to UTV Ireland
<reponame>VirtEngine/whmcs_go /* ** Copyright [2013-2016] [Megam Systems] ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package whmcs import ( "bytes" "encoding/json" "fmt" "net" "net/http" "strings" "strconv" "gopkg.in/check.v1" ) func (s *S) TestBillableItem_marshall(c *check.C) { o := &BillableItem{ ClientId: String("tom"), Description: String("walker.wheesy.com billed"), Hours: String("10"), Amount: String("100"), InvoiceAction: String("noinvoice"), } want := `{ "clientid" : "tom", "description" : "walker.wheesy.com billed", "hours" : "10", "amount" : "100", "invoiceaction" : "noinvoice" }` j, err := json.Marshal(o) c.Assert(err, check.IsNil) w := new(bytes.Buffer) err = json.Compact(w, []byte(want)) c.Assert(err, check.IsNil) c.Assert(w.String(), check.Equals, string(j)) } func (s *S) TestBillableService_Create_specifiedOrder_error(c *check.C) { s.mux.HandleFunc("/bi", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"email": "<EMAIL>"}`) }) user, _, err := s.client.Billables.Create(map[string]string{"clientemail": "<EMAIL>"}) c.Assert(err, check.NotNil) c.Assert(user, check.IsNil) } func (s *S) TestBillableService_Create_specifiedOrder(c *check.C) { s.mux.HandleFunc("/includes/api.php", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"clientid": "<EMAIL>"}`) }) user, _, err := s.client.Billables.Create(map[string]string{"clientid": "<EMAIL>", "username": "testing", "password": "<PASSWORD>"}) c.Assert(err, check.IsNil) want := &BillableItem{ClientId: String("<EMAIL>")} c.Assert(user, check.DeepEquals, want) } func (s *S) TestBillableService_Create_invalidOrder(c *check.C) { _, _, err := s.client.Billables.Create(map[string]string{"clientid": "%"}) c.Assert(err, check.NotNil) } func (s *S) TestBillableService_Create(c *check.C) { addr := strings.Join([]string{"192.168.0.133", strconv.Itoa(80)}, ":") _, err := net.Dial("tcp", addr) c.Assert(err, check.IsNil) // if err == nil { // c.Skip("WHMCS isn't running. You can't rest it live.") // } // defer conn.Close() client := NewClient(nil, "http://192.168.0.133/whmcs/") a := map[string]string{ "username": "Megam", "password": <PASSWORD>5Hash("team4megam"), "clientid": "67", "description": "testing billableitems", "hours": "1", "amount": "0.3", "invoiceaction": "nextcron", } fmt.Println(client) _, _, err = client.Billables.Create(a) c.Assert(err, check.IsNil) }
/** * Tests shutting down the proxy. */ @Test @DisplayName("Tests shutting down the proxy.") void testShutdown() { JobExecution jobExecution = new JobExecution(); actionProxy.shutdown(jobExecution); verify(actionMock, times(1)).shutdown(jobExecution); }
def symmetryTable(self): fullPathName = self.fullPathName() if not mc.attributeQuery('symmetryTable', node=fullPathName, exists=True): mc.addAttr(fullPathName, longName='symmetryTable', dataType="string") mc.setAttr('%s.symmetryTable' % fullPathName, '{}', type="string") Evaluate string attribute value = mc.getAttr('%s.symmetryTable' % fullPathName) symmetryTable = eval(value) return symmetryTable
<reponame>ruanmirandac/Python #Exercício Python 008: Escreva um programa que leia um valor em metros # e o exiba convertido em centímetros e milímetros. print(5*'=','VAMOS CONVERTER AS UNIDADES MÉTRICAS',5*'=') metro = float(input('Qual valor em metros? ')) dc = metro * 10 cm = metro * 100 mm = metro * 1000 print(f'{metro:.2f} metros representa {cm:.2f} centimetros') print(f'{metro:.2f} metros representa {mm:.2f} milimetros') print(f'{metro:.2f} metros representa {dc:.2f} decimetros')
<gh_stars>1-10 """ ===================================== Plot the support vectors in LinearSVC ===================================== Unlike SVC (based on LIBSVM), LinearSVC (based on LIBLINEAR) does not provide the support vectors. This example demonstrates how to obtain the support vectors in LinearSVC. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.svm import LinearSVC from sklearn.inspection import DecisionBoundaryDisplay X, y = make_blobs(n_samples=40, centers=2, random_state=0) plt.figure(figsize=(10, 5)) for i, C in enumerate([1, 100]): # "hinge" is the standard SVM loss clf = LinearSVC(C=C, loss="hinge", random_state=42).fit(X, y) # obtain the support vectors through the decision function decision_function = clf.decision_function(X) # we can also calculate the decision function manually # decision_function = np.dot(X, clf.coef_[0]) + clf.intercept_[0] # The support vectors are the samples that lie within the margin # boundaries, whose size is conventionally constrained to 1 support_vector_indices = np.where(np.abs(decision_function) <= 1 + 1e-15)[0] support_vectors = X[support_vector_indices] plt.subplot(1, 2, i + 1) plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired) ax = plt.gca() DecisionBoundaryDisplay.from_estimator( clf, X, ax=ax, grid_resolution=50, plot_method="contour", colors="k", levels=[-1, 0, 1], alpha=0.5, linestyles=["--", "-", "--"], ) plt.scatter( support_vectors[:, 0], support_vectors[:, 1], s=100, linewidth=1, facecolors="none", edgecolors="k", ) plt.title("C=" + str(C)) plt.tight_layout() plt.show()
<filename>src/main/java/io/github/talelin/latticy/common/util/IpParseUtil.java package io.github.talelin.latticy.common.util; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import lombok.extern.slf4j.Slf4j; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * <p> * IP 地址解析工具类 * </p> * * @author 踏雪彡寻梅 * @version 1.0 * @date 2020/8/9 - 13:51 * @since JDK1.8 */ @Slf4j @Component public class IpParseUtil { private static String dbFilePath; @Value("${sky-blog.ip2-path}") public void setDbFilePath(String dbFilePath) { IpParseUtil.dbFilePath = dbFilePath; } /** * 解析 ip 地址获取地理位置信息 * * @param ip 解析的 ip 地址 * @return 返回 ip 地址解析之后的地理位置 */ public static String getAddressByIp(String ip) { try { if (StringUtils.isBlank(ip)) { return "中国"; } DbConfig config = new DbConfig(); DbSearcher searcher = new DbSearcher(config, dbFilePath); DataBlock block = searcher.btreeSearch(ip); // 解析的地理位置格式: 国家|大区|省份|城市|运营商 String region = block.getRegion(); // 拆分后: [国家, 大区, 省份, 城市, 运营商] String[] split = region.split("\\|"); // 处理之后返回的地理位置 String address; // 城市可能会出现解析不到的情况,解析不到时会为 0,例如: 中国|0|xx省|0|移动,需要处理一下 // 本地测试时也可能会出现 0|0|0|内网IP|内网IP 的情况,也需要处理一下 String country = split[0]; String province = split[2]; String city = split[3]; String operator = split[4]; if ("内网IP".equals(city) || "内网IP".equals(operator)) { address = "中国"; return address; } if (!"0".equals(country) && !"0".equals(province) && !"0".equals(city)) { address = country + province + city; return address; } if (!"0".equals(country) && !"0".equals(province)) { address = country + province; return address; } address = "中国"; return address; } catch (Exception e) { log.error("IpParseUtil 解析 IP 地址时出现异常: ", e); return "中国"; } } }
''' Non-parametric computation of entropy and mutual-information Adapted by G Varoquaux for code created by R Brette, itself from several papers (see in the code). These computations rely on nearest-neighbor statistics ''' import numpy as np from scipy.special import gamma,psi from scipy import ndimage from scipy.linalg import det from numpy import pi from sklearn.neighbors import NearestNeighbors __all__=['entropy', 'mutual_information', 'entropy_gaussian'] EPS = np.finfo(float).eps def nearest_distances(X, k=1): ''' X = array(N,M) N = number of points M = number of dimensions returns the distance to the kth nearest neighbor for every point in X ''' knn = NearestNeighbors(n_neighbors=k) knn.fit(X) d, _ = knn.kneighbors(X) # the first nearest neighbor is itself return d[:, -1] # returns the distance to the kth nearest neighbor def entropy_gaussian(C): ''' Entropy of a gaussian variable with covariance matrix C ''' if np.isscalar(C): # C is the variance return .5*(1 + np.log(2*pi)) + .5*np.log(C) else: n = C.shape[0] # dimension return .5*n*(1 + np.log(2*pi)) + .5*np.log(abs(det(C))) def entropy(X, k=1): ''' Returns the entropy of the X. Parameters =========== X : array-like, shape (n_samples, n_features) The data the entropy of which is computed k : int, optional number of nearest neighbors for density estimation Notes ====== Kozachenko, L. F. & Leonenko, N. N. 1987 Sample estimate of entropy of a random vector. Probl. Inf. Transm. 23, 95-101. See also: Evans, D. 2008 A computationally efficient estimator for mutual information, Proc. R. Soc. A 464 (2093), 1203-1215. and: Kraskov A, Stogbauer H, Grassberger P. (2004). Estimating mutual information. Phys Rev E 69(6 Pt 2):066138. ''' # Distance to kth nearest neighbor r = nearest_distances(X, k) # squared distances n, d = X.shape volume_unit_ball = (pi**(.5*d)) / gamma(.5*d + 1) ''' F. Perez-Cruz, (2008). Estimation of Information Theoretic Measures for Continuous Random Variables. Advances in Neural Information Processing Systems 21 (NIPS). Vancouver (Canada), December. return d*mean(log(r))+log(volume_unit_ball)+log(n-1)-log(k) ''' return (d*np.mean(np.log(r + np.finfo(X.dtype).eps)) + np.log(volume_unit_ball) + psi(n) - psi(k)) def mutual_information(variables, k=1): ''' Returns the mutual information between any number of variables. Each variable is a matrix X = array(n_samples, n_features) where n = number of samples dx,dy = number of dimensions Optionally, the following keyword argument can be specified: k = number of nearest neighbors for density estimation Example: mutual_information((X, Y)), mutual_information((X, Y, Z), k=5) ''' if len(variables) < 2: raise AttributeError( "Mutual information must involve at least 2 variables") all_vars = np.hstack(variables) return (sum([entropy(X, k=k) for X in variables]) - entropy(all_vars, k=k)) def mutual_information_2d(x, y, sigma=1, normalized=False): """ Computes (normalized) mutual information between two 1D variate from a joint histogram. Parameters ---------- x : 1D array first variable y : 1D array second variable sigma: float sigma for Gaussian smoothing of the joint histogram Returns ------- nmi: float the computed similariy measure """ bins = (256, 256) jh = np.histogram2d(x, y, bins=bins)[0] # smooth the jh with a gaussian filter of given sigma ndimage.gaussian_filter(jh, sigma=sigma, mode='constant', output=jh) # compute marginal histograms jh = jh + EPS sh = np.sum(jh) jh = jh / sh s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0])) s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1)) # Normalised Mutual Information of: # Studholme, jhill & jhawkes (1998). # "A normalized entropy measure of 3-D medical image alignment". # in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143. if normalized: mi = ((np.sum(s1 * np.log(s1)) + np.sum(s2 * np.log(s2))) / np.sum(jh * np.log(jh))) - 1 else: mi = ( np.sum(jh * np.log(jh)) - np.sum(s1 * np.log(s1)) - np.sum(s2 * np.log(s2))) return mi ############################################################################### # Tests def test_entropy(): # Testing against correlated Gaussian variables # (analytical results are known) # Entropy of a 3-dimensional gaussian variable rng = np.random.RandomState(0) n = 50000 d = 3 P = np.array([[1, 0, 0], [0, 1, .5], [0, 0, 1]]) C = np.dot(P, P.T) Y = rng.randn(d, n) X = np.dot(P, Y) H_th = entropy_gaussian(C) H_est = entropy(X.T, k=5) # Our estimated entropy should always be less that the actual one # (entropy estimation undershoots) but not too much np.testing.assert_array_less(H_est, H_th) np.testing.assert_array_less(.9*H_th, H_est) def test_mutual_information(): # Mutual information between two correlated gaussian variables # Entropy of a 2-dimensional gaussian variable n = 50000 rng = np.random.RandomState(0) #P = np.random.randn(2, 2) P = np.array([[1, 0], [0.5, 1]]) C = np.dot(P, P.T) U = rng.randn(2, n) Z = np.dot(P, U).T X = Z[:, 0] X = X.reshape(len(X), 1) Y = Z[:, 1] Y = Y.reshape(len(Y), 1) # in bits MI_est = mutual_information((X, Y), k=5) MI_th = (entropy_gaussian(C[0, 0]) + entropy_gaussian(C[1, 1]) - entropy_gaussian(C) ) # Our estimator should undershoot once again: it will undershoot more # for the 2D estimation that for the 1D estimation print MI_est, MI_th np.testing.assert_array_less(MI_est, MI_th) np.testing.assert_array_less(MI_th, MI_est + .3) def test_degenerate(): # Test that our estimators are well-behaved with regards to # degenerate solutions rng = np.random.RandomState(0) x = rng.randn(50000) X = np.c_[x, x] assert np.isfinite(entropy(X)) assert np.isfinite(mutual_information((x[:, np.newaxis], x[:, np.newaxis]))) assert 2.9 < mutual_information_2d(x, x) < 3.1 def test_mutual_information_2d(): # Mutual information between two correlated gaussian variables # Entropy of a 2-dimensional gaussian variable n = 50000 rng = np.random.RandomState(0) #P = np.random.randn(2, 2) P = np.array([[1, 0], [.9, .1]]) C = np.dot(P, P.T) U = rng.randn(2, n) Z = np.dot(P, U).T X = Z[:, 0] X = X.reshape(len(X), 1) Y = Z[:, 1] Y = Y.reshape(len(Y), 1) # in bits MI_est = mutual_information_2d(X.ravel(), Y.ravel()) MI_th = (entropy_gaussian(C[0, 0]) + entropy_gaussian(C[1, 1]) - entropy_gaussian(C) ) print MI_est, MI_th # Our estimator should undershoot once again: it will undershoot more # for the 2D estimation that for the 1D estimation np.testing.assert_array_less(MI_est, MI_th) np.testing.assert_array_less(MI_th, MI_est + .2) if __name__ == '__main__': # Run our tests test_entropy() test_mutual_information() test_degenerate() test_mutual_information_2d()
// Clone the store with a cloned session func (mong *MongoStore) Clone() Store { nStore := NewMongoStore(mong.Server, mong.Database) nStore.Session = mong.Session.Clone() return nStore }
package com.example.myfavoritemovies.model; import androidx.annotation.NonNull; import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import androidx.databinding.library.baseAdapters.BR; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; @Entity(tableName = "genres_table") public class Genre extends BaseObservable { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "genre_name") private String genreName; @Ignore public Genre() { } public Genre(int id, String genreName) { this.id = id; this.genreName = genreName; } @Bindable public int getId() { return id; } public void setId(int id) { this.id = id; notifyPropertyChanged(BR.id); } @Bindable public String getGenreName() { return genreName; } public void setGenreName(String genreName) { this.genreName = genreName; notifyPropertyChanged(BR.genreName); } @NonNull @Override public String toString() { return this.genreName; } }