content
stringlengths
7
2.61M
LymanKutcherBurman NTCP model parameters for radiation pneumonitis and xerostomia based on combined analysis of published clinical data Knowledge of accurate parameter estimates is essential for incorporating normal tissue complication probability (NTCP) models into biologically based treatment planning. The purpose of this work is to derive parameter estimates for the LymanKutcherBurman (LKB) NTCP model using a combined analysis of multi-institutional toxicity data for the lung (radiation pneumonitis) and parotid gland (xerostomia). A series of published clinical datasets describing dose response for radiation pneumonitis (RP) and xerostomia were identified for this analysis. The data support the notion of large volume effect for the lung and parotid gland with the estimates of the n parameter being close to unity. Assuming that n = 1, the m and TD50 parameters of the LKB model were estimated by the maximum likelihood method from plots of complication rate as a function of mean organ dose. Ninety five percent confidence intervals for parameter estimates were obtained by the profile likelihood method. If daily fractions other than 2 Gy had been used in a published report, mean organ doses were converted to 2 Gy/fraction-equivalent doses using the linear-quadratic (LQ) formula with / = 3 Gy. The following parameter estimates were obtained for the endpoint of symptomatic RP when the lung is considered a paired organ: m = 0.41 (95% CI 0.38, 0.45) and TD50 = 29.9 Gy (95% CI 28.2, 31.8). When RP incidence was evaluated as a function of dose to the ipsilateral lung rather than total lung, estimates were m = 0.35 (95% CI 0.29, 0.43) and TD50 = 37.6 Gy (95% CI 34.6, 41.4). For xerostomia expressed as reduction in stimulated salivary flow below 25% within six months after radiotherapy, the following values were obtained: m = 0.53 (95% CI 0.45, 0.65) and TD50 = 31.4 Gy (95% CI 29.1, 34.0). Although a large number of parameter estimates for different NTCP models and critical structures exist and continue to appear in the literature, it is hard to justify the use of any single parameter set obtained at a selected institution for the purposes of biologically based treatment planning. Our expectation is that the proposed model parameters based on cumulative experience at various institutions are more representative of the overall practice of radiation therapy than any single-institution data, and could be more readily incorporated into clinical use.
A high prevalence of Dupuytren's disease in Flanders. Dupuytren's disease has been the subject of numerous epidemiological surveys attempting to expand our knowledge on its origin and spread. In Flanders, although numerous studies on surgical outcome have been reported, information on prevalence of Dupuytren's disease is lacking. Therefore, Flanders' population in a non-hospital environment was studied by a clinical evaluation performed by a single hand specialist. Five different market places spread geographically in the 5 Flemish provinces of Belgium were visited to examine the hands of randomly chosen individuals over 50 years old visiting the market. In all, 500 people were examined; Dupuytren's disease was found to be present in 32% of the population. Nodules without finger contractures (stage 1) were seen in 24% of the population, in comparable proportions in males (28%) and females (20%). However, finger contractures (stage 2) were seen in 8%, significantly more often in males (11%) than in females (4%). The prevalence of stage 1 is somewhat lower in individuals over 80 years old. In men, the incidence of stage 2 was found to increase with age. These findings were compared with literature data on the prevalence of Dupuytren's disease in other countries and populations. It appears that, similar to northern Europe, Dupuytren's disease is also a common disease in Flanders.
According to new data recently released by the Census Bureau, 14.3 percent of Americans were living in poverty in 2009. In September of 2009 we performed an analysis in which we simulated what would happen to the poverty rate over the next several years based on projections of the unemployment rate and the estimated relationship between the poverty rate and the unemployment rate. We provide a brief update to that analysis here. The bottom line of this analysis is that the recession is likely to have a dramatic impact on poverty over the next several years. Our simulations suggest that the overall poverty rate will increase from 12.5 percent in 2007 to nearly 16 percent by 2014 and that the child poverty rate will increase from 18 percent in 2007 to nearly 26 percent in 2014, adding about 10 million people total and 6 million children to the ranks of the poor by the middle of the current decade. Despite the fact that our simulation accurately predicted the poverty rate for 2009, we emphasize that there is a strong possibility that the estimates we present here are conservative, given that we do not know how dramatic of an effect the current recession will have on structural unemployment in the future. In light of these increases we believe that programs such as Food Stamps and TANF that can help to buffer the effects of the recession on lower-income families should be maintained or increased in these difficult economic times. With the economic recovery stagnating, projections of the unemployment rate over the next 5 to 10 years tell a story of lingering high unemployment (see Table A). The Congressional Budget Office, the Office of Management and Budget (OMB), and the Economist Intelligence Unit (EIU) all project an average annual rate of 9 percent or above for 2010 and 2011 and above 8 percent for 2012. Both CBO and OMB project that the rate will drop relatively quickly afterward, settling near 5 percent by the middle of the decade. However, more recent data suggest these longer-term projections may be overly optimistic and may not adequately incorporate the effects of a prolonged period of high unemployment on the level of structural unemployment. Indeed, the latest EIU projections, released on September 8, 2010, see the unemployment rate remaining well above 8 percent through 2014 (the latest year for which EIU provides projections). Taking these projections at face value, how will these elevated levels of unemployment affect poverty? Isabel Sawhill has written more on this topic in the Brookings UpFront blog, where she discusses the need to strengthen the safety net in light of the depth of the recession and recent poverty increases.
//@@author kohjunkiat package seedu.address.model.statistic; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_EXPENSE_JUNE; import static seedu.address.logic.commands.CommandTestUtil.VALID_INVENTORY_JUNE; import static seedu.address.logic.commands.CommandTestUtil.VALID_MONTH_JUNE; import static seedu.address.logic.commands.CommandTestUtil.VALID_REVENUE_JUNE; import static seedu.address.logic.commands.CommandTestUtil.VALID_YEAR_JUNE; import static seedu.address.testutil.TypicalStatistic.JAN; import static seedu.address.testutil.TypicalStatistic.MAY; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.testutil.StatisticBuilder; public class StatisticTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void isSameStatistic() { // same object -> returns true assertTrue(JAN.isSameStatistic(JAN)); // null -> returns false assertFalse(JAN.isSameStatistic(null)); // different month and year -> returns false Statistic editedStatistic = new StatisticBuilder(JAN).withYear(VALID_YEAR_JUNE) .withMonth(VALID_MONTH_JUNE).build(); assertFalse(JAN.isSameStatistic(editedStatistic)); // different month -> returns false editedStatistic = new StatisticBuilder(JAN).withMonth(VALID_MONTH_JUNE).build(); assertFalse(JAN.isSameStatistic(editedStatistic)); // same month, same year , same inventory, different attributes -> returns true editedStatistic = new StatisticBuilder(JAN).withExpense(VALID_EXPENSE_JUNE) .withRevenue(VALID_REVENUE_JUNE).build(); assertTrue(JAN.isSameStatistic(editedStatistic)); // same month, same year, same revenue, different attributes -> returns true editedStatistic = new StatisticBuilder(JAN).withInventory(VALID_INVENTORY_JUNE) .withExpense(VALID_EXPENSE_JUNE).build(); assertTrue(JAN.isSameStatistic(editedStatistic)); // same month, same year, same expense, different attributes -> returns true editedStatistic = new StatisticBuilder(JAN).withRevenue(VALID_REVENUE_JUNE) .withInventory(VALID_INVENTORY_JUNE).build(); assertTrue(JAN.isSameStatistic(editedStatistic)); } @Test public void equals() { // same values -> returns true Statistic janCopy = new StatisticBuilder(JAN).build(); assertTrue(JAN.equals(janCopy)); // same object -> returns true assertTrue(JAN.equals(JAN)); // null -> returns false assertFalse(JAN.equals(null)); // different type -> returns false assertFalse(JAN.equals(5)); // different statistic -> returns false assertFalse(JAN.equals(MAY)); // different inventory -> returns false Statistic editedStatistic = new StatisticBuilder(JAN).withInventory(VALID_INVENTORY_JUNE).build(); assertFalse(JAN.equals(editedStatistic)); // different revenue -> returns false editedStatistic = new StatisticBuilder(JAN).withRevenue(VALID_REVENUE_JUNE).build(); assertFalse(JAN.equals(editedStatistic)); // different expense -> returns false editedStatistic = new StatisticBuilder(JAN).withExpense(VALID_EXPENSE_JUNE).build(); assertFalse(JAN.equals(editedStatistic)); // different month -> returns false editedStatistic = new StatisticBuilder(JAN).withMonth(VALID_MONTH_JUNE).build(); assertFalse(JAN.equals(editedStatistic)); // different year -> returns false editedStatistic = new StatisticBuilder(JAN).withYear(VALID_YEAR_JUNE).build(); assertFalse(JAN.equals(editedStatistic)); } }
/// <reference path="../_references.d.ts" /> angular.module('dotjem.directives.code').directive('dxCode', [ <any>'$syntax', function($syntax: ISyntaxService){ return { restrict: 'ECA', link: function (scope, element) { $syntax(element); } }; } ]);
The cells of benign and malignant hemangiopericytomas in aspiration biopsy Samples obtained by fineneedle biopsy of two benign and one malignant hemangiopericytoma revealed tumor cells with round, oval, or spindleshaped nuclei, with variable and illdefined filmy cytoplasm. The nuclei had a finely granular chromatin pattern with or without inconspicuous nucleoli. They were seen singly or in loose or dense cellular clusters. Focal glandlike arrangement of tumor cells was noted in some cellular clusters. Benign endothelial cells were seen among tumor cells and were not cohesive to the latter. The benign and malignant nature of hemangiopericytoma cannot be predicted by examination of the cells present in the aspirates. Also, a specific diagnosis of hemangiopericytoma could not be made on cytologic basis alone as cells of hemangiopericytoma were difficult to differentiate from those of other spindlecell mesenchymal tumors.
<filename>pull-issues.py ''' Pulls all issues for a certain github repository that have been raised by members of specified organization ''' import os import sys from github import Github from dotenv import load_dotenv if not os.path.exists('.env'): print("no file named .env found", file=sys.stderr) sys.exit(1) elif len(sys.argv) != 3: print("Usage: ./pull_issues.sh <repository name> <organization name>\nExample: ./pull_issues.sh DataDog/Gello DataDog") sys.exit(0) gh = None load_dotenv(verbose=True) if 'GITHUB_USERNAME' in os.environ and 'GITHUB_PASSWORD' in os.environ: gh = Github(os.getenv("GITHUB_USERNAME"), os.getenv("GITHUB_PASSWORD")) elif 'GITHUB_ACCESS_TOKEN' in os.environ: gh = Github(os.getenv("GITHUB_ACCESS_TOKEN")) else: print(".env file does not have enough information", file=sys.stderr) sys.exit(1) repo_name = sys.argv[1] repo_issues = gh.get_repo(repo_name).get_issues(state='open') org_name = sys.argv[2] org_members = gh.get_organization(org_name).get_members() # Pagination making this really slow, can try to pull all at once and internally buffer later members = set() for member in org_members: members.add(member.login) for issue in repo_issues: if issue.user.login in members: print(issue)
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you 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 net.sf.farrago.namespace.mock; import org.eigenbase.rel.*; import org.eigenbase.relopt.*; /** * MockTableModificationRule is a rule for converting an abstract {@link * TableModificationRel} into a corresponding local mock table update (always * returning rowcount 0, since local mock tables never store any data). * * @author <NAME> * @version $Id$ */ class MedMockTableModificationRule extends RelOptRule { //~ Constructors ----------------------------------------------------------- /** * Creates a new MockTableModificationRule object. */ public MedMockTableModificationRule() { super( new RelOptRuleOperand( TableModificationRel.class, ANY)); } //~ Methods ---------------------------------------------------------------- // implement RelOptRule public CallingConvention getOutConvention() { return CallingConvention.ITERATOR; } // implement RelOptRule public void onMatch(RelOptRuleCall call) { TableModificationRel tableModification = (TableModificationRel) call.rels[0]; // TODO jvs 13-Sept-2004: disallow updates to mock foreign tables if (!(tableModification.getTable() instanceof MedMockColumnSet)) { return; } MedMockColumnSet targetColumnSet = (MedMockColumnSet) tableModification.getTable(); // create a 1-row column set with the correct type for rowcount; // single value returned will be 0, which is what we want MedMockColumnSet rowCountColumnSet = new MedMockColumnSet( targetColumnSet.server, targetColumnSet.getLocalName(), tableModification.getRowType(), 1, targetColumnSet.executorImpl, null); call.transformTo( rowCountColumnSet.toRel( tableModification.getCluster(), tableModification.getConnection())); } } // End MedMockTableModificationRule.java
<gh_stars>0 import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {AisRoutingModule} from './ais-routing.module'; import {LoginComponent} from './login/login.component'; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {GrantConsentComponent} from './grant-consent/grant-consent.component'; import {AccountDetailsComponent} from './account-details/account-details.component'; import {SelectScaComponent} from './select-sca/select-sca.component'; import {ResultPageComponent} from './result-page/result-page.component'; import {TanConfirmationComponent} from './tan-confirmation/tan-confirmation.component'; import { NotFoundModule } from '../not-found/not-found.module'; @NgModule({ declarations: [ LoginComponent, GrantConsentComponent, AccountDetailsComponent, SelectScaComponent, ResultPageComponent, TanConfirmationComponent ], imports: [ CommonModule, ReactiveFormsModule, FormsModule, AisRoutingModule, NotFoundModule ] }) export class AisModule { }
Identification of normal hearing carriers of genes for deafness. The dominant and sex-linked forms of hereditary hearing loss, which have long been recognized, are readily identified on the basis of the family history and routine hearing tests. The mode of inheritance of the recessive forms of hereditary deafness, on the other hand, has been extremely difficult to determine. The research of the last few years, however, has disclosed that carriers of genes for recessive deafness can be identified by audiometric recording of certain peculiarities in the hearing function. This is an important advance, not only as regards diagnositc work, but also in the research into the genetics of deafness.
While the appearances by and references to the retired cadres may seem awkward, comical or just downright dull, analysts say they serve a purpose: They’re telegraphing that these old-timers are alive, well and trying to play a role in shaping policy and determining appointments ahead of the 18th Party Congress. As China prepares to begin a major Communist Party leadership transition next week, hardly a day goes by without a fresh TV or newspaper report highlighting the recent activities of a former leader, many of whom have been out of the limelight for years. “This beautiful romantic song, for it to be able to reappear, to be restored, and for us to be able to remember it, all the credit should go to our comrade Jiang Zemin,” Chen said on the program. This spring, he said, he received a call from Li Lanqing, who served as vice premier under President Jiang Zemin from 1998 to 2003. The former president, now 86, was urgently looking for the sheet music for the song, which he had enjoyed as a young man in his revolutionary days, Li said. Chen helped a composer notate the melody and words. (Sample lyric: “Even in shadows, I feel no alarm, while I hold you tight, in the jungle light, my dear ...”) BEIJING –- Apropos of seemingly nothing, the TV program “Music World Today” on China’s state-run channel 15 launched into a 30-minute segment Friday about a schmaltzy, obscure tune, “Moonlight and Shadows,” from the 1936 American film “The Jungle Princess.” But invited guest Chen Lin, a 90-year-old professor from Beijing Foreign Studies University, quickly clued viewers in to its significance. “Such stories serve to demonstrate that Jiang is still active, still healthy and maintains a strong influence,” said Zhan Jiang, a journalism professor at Beijing Foreign Studies University. Besides the 86-year-old Jiang’s contributions to preserving musical history (“Moonlight and Shadows” also was featured in a People’s Daily story Wednesday), former Premier Li Peng made headlines with a recent $476,000 donation to a scholarship fund and a letter congratulating Jilin province on a new hydropower dam. Li Ruihuan, 78, former head of the Chinese People’s Political Consultative Conference, and Wu Yi, 74, a former vice premier, made news when they took in a tennis match at the China Open last month. Some observers saw a more direct message when former Premier Zhu Rongji, 84, turned up at Tsinghua University recently with his protégé and current Vice Premier Wang Qishan, a front-runner for promotion to the Politburo Standing Committee, China’s top decision-making body. Also present was the only female in contention for the Standing Committee, Liu Yandong. But it is Jiang’s appearances that are drawing the most attention. First he popped up at Beijing's National Center for the Performing Arts with his wife. Next, the People’s Daily wrote a front page story about him sending condolences to Cambodia’s queen mother on the death of her husband (current President Hu Jintao’s extension of sympathies got secondary billing). Jiang was photographed Oct. 9 meeting with the president of Shanghai Ocean University; two weeks ago he was busy making an inscription for the 110th anniversary of his high school. “Among all these personalities, Jiang is the most important, and he’s the most adamant about refusing to fade into the sunset. So he’s still playing a role in the personnel arrangements for the Party Congress,” said Willy Lam, a China scholar at the Chinese University of Hong Kong. “If one [retired official] sees others becoming active, they become a bit jealous, they want a share of the limelight. So the major factor was Jiang’s series of reappearances after an absence of at least one year.” The weeklong Party Congress kicks off next Nov. 8, and the new Politburo Standing Committee will be unveiled at the end of the gathering. The panel has nine members; seven are expected to retire. The two holdovers are Xi Jinping and Li Keqiang; Xi is slated to assume the top position of party secretary from Hu, while Li may take on the role held by Premier Wen Jiabao. Most observers expect the new Standing Committee will have a total of seven, not nine, members, which means jockeying for the five available slots has been particularly intense. Lam said Wednesday that he believed one slot might still be undecided. “The fact remains, this is a political system that’s ruled by personality rather than rule of law. It’s up to the whims and machinations of strongmen," Lam said. "Though Hu has been talking about increasing democracy within the party, nothing substantial has been achieved in terms of reform.” “This unfortunate state of affairs gets magnified because Hu Jintao is a very timid person," Lam added. "Even though he’s been in power 10 years, he still prefers to defer to Jiang Zemin.” Jiang stepped down as party secretary in 2002, turning the position over to Hu. But in an effort to keep a substantial hand in national affairs, Jiang remained for two more years as chair of the party’s Central Military Commission before ceding that role to Hu. As Hu prepares to wind down his decade as party secretary, though, he may follow the example set by Jiang and refuse to immediately give up the military commission chairmanship to Xi. That may leave Xi with not one, but two, ex-leaders looking over his shoulder. “Xi is going to have to deal with Hu Jintao and Jiang Zemin,” Lam said. “He will face hurdles in terms of consolidating his position and coming into his own.” ALSO: Arrest in Mexican reporter's killing met with doubt Japan politicians play 'game of chicken' over financial cliff Clinton discloses West's effort to help reshape Syria opposition -- Julie Makinen. Tommy Yang in the Times Beijing bureau contributed. Photo: This file photo dated March 10, 2003, shows then–Chinese President Jiang Zemin, left, listening to his successor Vice President Hu Jintao during a session of the National People's Congress in Beijing. Credit: Goh Chai Hin / Agence France-Presse.
Study of Prescribing Pattern of Antimicrobial Agents in Medicine Intensive Care Unit of a Tertiary Care Hospital in Bihar Introduction: Medical Intensive Care Unit (MICU) is a setup where very serious patients are admitted and large numbers of drugs are administered to these patients. Usually, cost of these prescribed drugs is very high. The aim of the current study was to assess the pattern of prescriptions being made for antimicrobial agents in MICU of a tertiary care hospital of Bihar. Methods: This prospective study was under taken in MICU of Indira Gandhi institute of Medical Sciences, Patna, Bihar over a period of six months from January 2018 to June 2018. Patients records, prescription and treatment charts were reviewed. Rationality of different drugs used in MICU patients were also evaluated. Results: In MICU, meropenem was most commonly prescribed antimicrobial agent. It was seen among 24% patients, closely followed by clindamycin (22%), ceftriaxone (20%), piperacillin + tazobactam (18%) and metronidazole (12%). Majority (92%) of the patients admitted in MICU were given 2-3 antimicrobial agents and rest were given 4-7 such drugs. Most common indication for prescription was infection with septicemia. Conclusion: Management of critically ill patients in MICU should be focused not only on control of infection but also on proper use of antibiotic. This will help to minimize emergence of drugs resistance, unnecessary cost burden to the patients and adverse drug reactions. INTRODUCTION ntimicrobial resistance is a global public health challenge which has been accelerated over the past decade by overuse of antibiotics worldwide. Increase in antimicrobial resistance is the cause of severe infections, complication; longer hospital stays and increase morbidity and mortality. Over prescription of antibiotics is associated with an increased risk of adverse effects. Antibiotics are most commonly used drugs especially among the inpatients of medicine department and that too among the critically ill patients in MICU of any hospital. A variety of modalities and developments have been achieved by the medical science to control infections and hence reduce related morbidity and mortality, but still such infection poses a significant core of patient care till today. This huge burden of infections among hospitalized patients in any health care facility led to increased number of prescriptions of antimicrobial agents being made. The rate of such prescriptions is 10 times higher among patients in MICU than in other general medical wards. 1 This scenario makes it inevitable to rationalize the use of such antimicrobial agents. This would in turn help to enhance treatment success rate and reduce emergence of resistant micro-organisms. Hence, the clinical lifespan of these drugs would be prolonged. 2 However, management of critically ill patients in MICU is a massive challenge to the medical fraternity as extreme pharmacokinetics (PK) variability has been encountered among these patients. 3 The conventional dosing of antimicrobial agents often is seen to result in clinical failure among patients in MICU, the prominent reason being that most of the clinical studies to calibrate the dosing of such drugs include patients from general wards as their study population. This discrepancy in the literature indeed is the most prominent cause of low drug dosing leading to therapeutic failure along with emergence of antimicrobial resistance 4, or excess drug dosing exposing these patients to more risk of toxicity. With this background, the current study was designed to encourage appropriate and proper use of antibiotics prescriptions in MICU of a tertiary care hospital as this is an important element in patient Study of Prescribing Pattern of Antimicrobial Agents in Medicine Intensive Care Unit of a Tertiary Care Hospital in Bihar A treatment, infection control and cost containment. 5, 6 Many of the previous authors in this field 7, 8 have already expressed their concern on this invariable, indiscriminate and unjustified use of antimicrobial agents that in turn lead to emergence of resistant organisms in the ecosystem. To combat this emerging problem, it is inevitable to procure correct knowledge of using antimicrobial agents along a healthy prescription practice. Increase antimicrobial resistance is the cause of severe infection, complication, longer hospital stays, health care cost and increased patients' morbidity and mortality. The ICARE study provided evidence that the huge burden of antibiotic resistance is noted among critically ill patient as compared to their control population. 9 This study showed that treatment given by any specialist of the field rather than a comparatively less competent medical practitioner help to bring down the expenses on the antibiotics by at least 45%. 9 Available literatures on antimicrobial use abroad and in India bears testimony to the widespread concern about appropriate use of these agents. 10 Hence, in this prospect, proper skill and competence in prescribing drugs should be reinforced time and again with continuous assessment and required corrections. The area of concern should not be limited to knowledge of drug pharmacology and pathophysiology of the disease but must also envisages diagnostic acumen and judicial prescription attitude, keeping patients' well-being and expenses in mind. 11 The study to assess the prescribing patterns of antimicrobial agents are aimed to evaluate and make necessary corrections if any discrepancy in practice is noted. The ultimate goal is to rationalize the treatment at all levels to benefit the patients for their own wellbeing and to minimize the cost of treatment. Correct skill and practice of prescription is inevitable to combat the global problem of emerging antibiotic resistance. 6 Multiple studies from Indian authors have been documented on antibiotic utilization pattern at an institutional level. The current study was planned to evaluate the prescription practice of various antimicrobial agents among patients admitted in medical ICU of Indira Gandhi Institute of Medical Sciences, Patna which is a tertiary health care center of the state. MATERIALS AND METHODS An observational study was conducted by the Department of General Medicine of Indira Gandhi Institute of Medical Sciences, Patna. The study included randomly selected prescriptions of patients from Medical ICU of the hospital over a period of six months from January 2018 to June 2018. The study was approved by the Institutional Ethics Committee. Inclusion criteria considered for the study were: 1) Adult patients of both genders, 2) Prescriptions with at least one antibiotic. While prescription of pregnant and lactating women was excluded. The demographic and clinical treatment data were collected that included age and gender of the patient, diagnosis, number of AMA prescribed, dose and route of administration of these AMA and rationality of use of prescribed AMA. Indication of use Drug therapies were categorized according to indication for prescribing AMA. Broadly, three groups were defined to categorize the patients for treatment: 1. Group A included patients for whom the indication for use of AMA was underlying infections that was confirmed clinically or by laboratory data. 2. Group B included patients for whom AMA were prescribed as prophylaxis to prevent emergence of any super-added infections. 3. Group C included cases where no symptomatic indication or no evidence of prophylaxis could be established, but patients were being treated with AMA for the treatment of the same symptoms e.g., prescribing drugs for fever without evidence of any infection. Rationality of use 1. The therapy was considered rational if the prescription of AMA was appropriate according to the type of infection identified. This included the type of AMA prescribed, route of administration, dose, frequency and duration 2. Therapy was considered irrational if the AMA was used without any without indication of either infection or prophylaxis or was administered through inappropriate route, dose or preparation. 3. Therapy was considered questionable if insufficient clinical or laboratory data were found to classify the treatment as rational or to start the particular therapy like a patient of congestive heart failure was prescribed AMA for cough in lack of evidence that cough was due to CHF or infection. Data analysis Relevant information from the collected data was entered and analyzed using Statistical Package for Social Sciences ver 21.0 (IBM, Chicago). Descriptive statistics was performed. Proportion of patients in various categories has been expressed as absolute number and percentage. Result has been expressed as test, tables or figures, as appropriate. RESULTS In this study, a total of prescription of 100 patients admitted in MICU were collected to obtain required information for the study. The male to female ratio was almost 1 (1.04). The mean age of patients was 51.6 years with a SD of 12.8 years. Patient characteristics has been given in details in table 1. The most common cause of admission in MICU was septicemia, acute kidney injury, multi-organ dysfunction, followed by COPD with acute exacerbation and LRTI, CKD, type 2 diabetic mellitus. . It was found that meropenam was most common prescribed AMA among these patients followed by clindamycin, ceftriaxone, piperacillin + tazobactum. Others antibiotics used were injection of cefoperazone, linezolid, moxifloxacin, amoxicillin + clavulanic acid, amikacin, levofloxacin, tigecycline, colistin, streptomycin and tablets of rifaximin, doxycycline and Anti-tubercular drugs. As for the number of AMA prescribed, 18% of MICU patients received 1 AMA, 42% patients were given 2AMAs, 23% received 3 AMAS, and 17% received 4 and more than 4 AMAs. Indication and rationality of use of AMA has been distributed as discussed in the methodology section. Septicemic infections were the most common indication (58%) for AMAs followed by prophylactic use (23%). As for rationality, 46% prescription for AMAs were considered rational, 51% were irrational and 13% use were questionable. DISCUSSION An observational study was conducted among patients admitted in Medical Intensive Care Unit of a literary care hospital of Bihar. The study tried to highlight the prescription practice regarding Anti-microbial Agents in this hospital. The purpose of the study was to evaluate this practice and find any prevailing problem in the prescription practice. The most common indication of admission was infections/septicemia with multi organ dysfunction. Patients had been administered variety of drugs and AMAs. In our study the commonest AMA prescribed was meropenem (24%), followed by clindamycin (22%), ceftriaxone (20%), piperacillin +tazobactam (18%) and metronidazole (18%). Similar study done by Vandana A Badar et al showed that in ICU, cefotaxime was most commonly used AMA (32%). 9 Similarly, Hanssens et al 10 concluded in their study that in MICU, almost three-fourth of the patients were started on AMAs. A survey to analyze the utilization of AMA was performed at two different health care facility and revealed that 35.3% and 39% of the patients who were admitted at these centers were given single AMA or in various combination. 11 Ceftriaxone was most commonly prescribed for patients (57%) as initial therapy, 10 whereas another study by Shankar et al found that ampicillin, amoxicillin, metronidazole, ciprofloxacin and crystalline penicillin were among the most common prescriptions. 12 Patients admitted in intensive care units are almost always in critical condition, so they receive parental route for treatment and prevention of any life-threatening situation. In our study infection/septicemia were the common indication for antimicrobial therapy; this supported by similar study where 76% patients were treated for presumed or proven infections and received antibiotics. 10 Majority of the patients (83%) were given at least one antibiotic; this is similar to findings of Hanssens Yet al (76%) 10 In our center, majority of the patients suffered from mixed infections, hence, they were given AMA in various combinations as per their bacteriological profile. So many times, antibiotics are kept on changing from one class to another class of drugs when the first one is not effective or patients not responding till culture reports were available. In this study, 46% of AMAs were rational, 51% irrational and 13% questionable. Using a different set-up, it has been demonstrated that the intervention of a physician specialist in Clinical Pharmacology was effective in reducing antibiotic costs by 51% when a prescription-point prevalence analysis was performed for comparison between two internal medical departments. 11 The common indication for use of antibiotic was infection (48%) followed by symptomatic 32%, prophylactic 20%. The percent of patients treated for infections was 48% which less than reported by other studies. 16 The percent of prophylactic treatment prescribed is 32% which is in accordance with 13% and 10.3% reported in previous studies. 14, 15 We found that the average number of drugs prescribed in the MICU was 8-10. In another study the number was 12.1 ± 7.6. 17 The average number of drugs in our study was less than or comparable to that reported in other studies. This is an important surrogate marker for ethical and rational drug use in any prescription audit. It is advised to retain the average number of drugs per prescription to the lowest possible number, as more the drugs mean more drug interaction. Also, this may predispose emergence of bacterial resistance and hence, increased hospital cost. 18 So, measures should be taken care to avoid the inappropriate use of antibiotics. Physicians must have a good knowledge and clear understanding of therapeutic use of antibiotics and their cost burden to the patients. They must be aware about the prevalence of various pathogens and resistance patterns in their hospital and exercise good judgment in selection empirical antimicrobial agents. 1 CONCLUSION Antibiotics are the widely used drugs in MICU patients. Many innovations have been achieved in the field of medicine, but still, antibiotics resistance is at alarming rate leading to increase morbidity, mortality and cost burden to the patients. All clinician must follow standard antimicrobials prescription protocol in clinical practice to minimize the antimicrobial resistance and cost burden to the patients. Rampant use of newer AMAs such as meropenem, clindamycin, ceftriaxone and piperacillin +tazobactam have been noticed, which creates a huge out of pocket expenditure for the patients which is comparable to other published data.
Books|What Sat on Trump’s Nightstand This Year? What Sat on Trump’s Nightstand This Year? A year into the Trump administration, Americans have a pretty good idea what the president has been watching on TV during his time in office, largely thanks to his active Twitter feed. But if you look closely, Twitter gives us a sense of what President Trump may be reading as well. Indeed, here are the books that seem to have sat on the White House nightstand this year. Forty-five days later at 5:13 in the morning, he called “Reasons to Vote for Democrats: A Comprehensive Guide,” by Michael J. Knowles, an American actor and conservative columnist, “a great book for your reading enjoyment.” The book consists entirely of blank pages. In November, Democratic political strategist Donna Brazile’s “Hacks: The Inside Story of the Break-ins and Breakdowns That Put Donald Trump in the White House” was on the president’s mind. He said the “real story on Collusion” during the 2016 presidential race was in this book. Clearly the “Trump bump” has an effect on book sales as well. Follow Susan Ellingwood on Twitter: @ellingwood.
Polycystic kidney disease induced by corticoids. A quantitative and qualitative analysis of cell populations in the tubular cysts. The sequential changes of cell morphology and the ratio distribution of the different types of cells which exist in tubular cysts induced by methylprednisolone acetate have been studied by light, transmission and scanning electron microscopy. We have also studied the blood levels of sodium and potassium by flame photometry. In both control and cystic ducts, at the level of the outer cortex, the first intercalated cells (IC) were not observed until the 4th postnatal day. Some intermediate cell configurations were observed during the 3rd postnatal day, suggesting that some primitive principal cells (PC) are transformed into IC. Development of IC seems to be independent of both the effects of corticoids and the blood levels of potassium. The ratio distribution and the types of IC observed throughout the period studied was similar in both normal and cystic ducts. The type of IC characterized by the presence of a huge apical process, which has gone previously undescribed with either TEM or SEM, was observed in both control and cystic ducts. We propose to name these cells as cells with surface pattern type V. During the period of regression of the tubular cysts dead and migrating cells were observed closely associated with cilia of the PC. Both types of cells do not seem to represent, based in their localization and frequency, abnormal cell types of the cyst wall. Our results support the hypothesis that renal cysts are giant collecting ducts which conserve both the morphology and the function of the epithelium.
import HTMLContent from '@comps/HTMLContent' import type { Changelog } from '@core/changelog' import { defineVFC } from '@core/helper' const toId = (str: string) => encodeURIComponent(str.replaceAll(/\s+/ig, '_').toLowerCase()) const ChangeLogCell = defineVFC<Changelog & { bottomLine?: false }>( ({ content, date, title, className, bottomLine }) => { const showLine = bottomLine === undefined ? true : bottomLine const formattedDate = new Date(date).toLocaleDateString(undefined, { day: 'numeric', year: 'numeric', month: 'short' }) const id = toId(title) return ( <article className={`${className ?? ''} py-6 ${showLine ? 'border-b-1' : ''} flex flex-col relative md:(grid grid-cols-12 py-12) `} id={id} > <aside className=' <md:(mb-6) md:(mr-4 mb-4 col-span-3)'> <div className='md:(sticky top-12)'> <a className='text-xl mb-2 block hover:text-red-800' href={`#${id}`}>{title}</a> <span className='block text-sm text-warm-gray-500 block'> {formattedDate} </span> </div> </aside> <HTMLContent html={content} className='md:(col-span-9)' /> </article> ) } ) export default ChangeLogCell
import threading from flask_server import * if __name__ == '__main__': server_thread = threading.Thread(target=start_server) server_thread.start()
Peripheral Pro Llc can be found at Lackawanna Ave 560. The following is offered: Resume Services. The entry is present with us since Sep 8, 2010 and was last updated on Nov 14, 2013. In Little Falls there are 1 other Resume Services. An overview can be found here.
Q: cooking time and cooking temperature The recipe calls for my food to bake for 35 minutes at 425 degrees F, But if I have another dish baking at 325 degrees F, how long should I bake the first dish at the lower temperature so it will turn out correctly? A: Baking the two together is unlikely to work. Generally speaking, dishes that cook for a short time at 425F are meant to get crispy and/or browned, or (in the case of yeast or egg-risen baked goods) are meant to have strong "oven spring" from the intense heat. None of these things will happen at 325 degrees; depending on the dish, it will be soggy, greasy, or flat. I would suggest, instead, cooking the 325 degree dish first, taking it out of the oven and wrapping it in foil and and thick towel to keep it warm, turning the oven up to 425, and baking the second dish. When the second dish is done, you can put the first dish back in the oven for 5 minutes to heat it back up, should it need it. Of course, a lot of that depends on what exactly those two dishes are, but you should get the general idea.
@PeridexisErrant: Sweet. That editing blueprints page is exactly what I needed. It looks like multilevel designations will be pretty trivial, it's just a matter of figuring out how to do the UI, which is probably the opposite of trivial. But I'm sure I can work something out. @Astarch: It's an arbitrary limit. I noticed a slowdown in the UI with unlimited colors. Also, 24 bit images are supported. It's just that when you have less than a full 8 bytes per color (ie. 16 bit and lower images), you have to change the algorithm for the color selection of each pixel, which IMO is more effort than its worth to implement, because seriously, who is really going to need the space savings of creating a 16 bit image vs 24 bits? IIRC (I don't have the source handy, as I mentioned before I'm still on vacation) .NET has a pixelcopy function which stores the image as a byte array with each pixel as 4 bytes of RGBA (or ARGB I don't recall which) or if there is no alpha channel 3 bytes of RGB -- which are converted to a hexadecimal value which is used for doing all the heavy lifting. Additionally there is a function which automagically creates a list of colors from the image palette which dynamically generates the designation inputs. In retrospect the color limit is a poor workaround for the actual problem. I was trying to protect people from loading jpgs of millions of colors and freezing the program. While testing I opened up some random .jpg of blood soaked icebergs and polar bears and figured someone out there would accidentally do something similar with their pictures of cats or boobies or whatever else they may have handy. I can probably increase the limit on colors, and also add a limit for the image dimensions, 2 or 3k square pixels maybe? edit: also, thanks for the link. I actually just saw your program while searching for more information about quickfort earlier today on the forums, and I've added it to my list of things to look at when I get back home.
Effects of meditation on physiological and metabolic parameters in patients with type 2 diabetes mellitus MindDM: study protocol for a randomized controlled trial Background Sri Lanka is faced with the challenge of managing a large population with diabetes mellitus by 2030. Psychological stress plays a major role in disease outcome by exerting physiological, psychological and social effects on individuals with chronic disorders. Meditation-based interventions have positive effects on the management of stress and diabetes, which are mediated via modulation of neuro-humoral mechanisms and autonomic functions, among others. Mechanisms of bio-physiological effects of meditation are considered to be through reduction of stress hormones, improvement of insulin resistance and improvement of autonomic dysfunction. Methods This study will be conducted as an open-label, randomized controlled clinical trial in the Faculty of Medicine, University of Colombo. The aim is to investigate the effects of meditation on glycaemic control and possible mechanisms of how meditation affects glycaemic control in patients with type 2 diabetes. The study was approved by the Ethics Review Committee of the Faculty of Medicine, University of Colombo (ERC/2019/094). Patients who are attending the professorial unit medical clinic with type 2 diabetes (172 in total) will be recruited based on inclusion-exclusion criteria. Patients who have never meditated or rarely meditated (less than once every three months) will be randomized using block randomization to meditation and waitlisted arms (1:1 allocation ratio). The meditation arm will undergo a mindfulness meditation program (selected after studying several meditation methods) conducted by a qualified instructor weekly for a period of 12 weeks in addition to usual care, while the waitlisted arm will only receive usual care. Daily meditation practices will be recorded in a diary. The primary outcome measure is HbA1c. Secondary outcome measures are fasting blood sugar, fructosamine, insulin resistance (calculated using fasting serum insulin), 24-h urinary cortisol, body mass index, cardiac autonomic reflex testing (Ewings battery of tests) and orocecal transit time using hydrogen breath analysis. All these will be done prior to commencement of the intervention and after 3 months in both arms. Data will be analysed using SPSS V-23. Discussion This study aims to identify the effect of mindfulness meditation on glycaemic control and the possible mechanisms (neuro humoral and autonomic functions) by which beneficial effects are mediated. Trial registration Registered under Sri Lanka Clinical Trial Registry: SLCTR/2021/015 The Universal Trial Number (UTN) U1111-1266-8640 Supplementary Information The online version contains supplementary material available at 10.1186/s13063-022-06771-2. Background and rationale{6a} The prevalence of diabetes mellitus is rising worldwide, especially in the Southeast Asian region and in Sri Lanka it has been projected to rise up to 13.9% by 2030. In both health and disease, psychological stress plays a major role in determining the well-being of an individual. It affects the individual's behaviour pattern, biophysical parameters and how the individual copes with disease. It has been postulated that physiological processes are affected by stress through the neuro-endocrine response system. Stress stimulates both the hypothalamic-pituitary-adrenocortical axis and the sympatheticadrenal-medullary system, which in turn affects a wide range of physiological processes. Chronic stress leads to elevated cortisol levels and results in poor glycaemic control It also indirectly affects glycaemic control through changes in behaviour patterns such as diet and exercise. It has been recognized that stress has a negative effect on quality of life and psychosocial wellbeing in patients with diabetes. Meditation can be defined as the intentional self-regulation of attention from moment to moment. The roots of most meditation practices have evolved from Buddhism. There are two major areas in meditation: concentration meditation and insightful meditation. Concentration meditation is known as "Samatha" in Theravada Buddhism and involves focussing attention to one thing. Insightful or awareness meditation, which is known as "vipassana" in Theravada Buddhism, does not restrict attention to one thing but emphasizes detached selfobservation from one moment to another. However, these two areas are not mutually exclusive and can be described as two aspects of the same meditative state. It has also been viewed as "Samatha" meditation practices leading to stability of the mind, whereas "Vipassana" meditation practices leading to clarity of the mind. Furthermore, a state of stability of the mind is needed to achieve clarity of mind. It is important to understand that Buddhist meditation is not merely a method of relaxation but is aimed at achieving a balance between stability and clarity of mind through practice. The meditative state thus reached is said to be present not only during meditation but also after meditation. The modern term of mindfulness or "Sati" in Buddhist literature, is described as a state of mind achieved through focussing the attention on one thing and being in the present moment. Keywords: Mindfulness meditation, Diabetes mellitus, Mechanisms of metabolic control This paves the pathway to achieve a higher state of mind through meditation. The aim is to have focused attention as well as to identify when the attention is deviated and regained. One example is "Anapanasathi" meditation which has been described as keeping the focused attention on breathing and being at the present moment (breath awareness). In clinical psychology, meditation is defined as "A family of self-regulation practices that focus on training attention and awareness in order to bring mental processes under greater voluntary control and thereby foster general mental well-being and development and/or specific capacities such as calm, clarity, and concentration". Thus, the core components of meditation practices include focused attention, self-regulation and self-awareness. There is evidence to suggest that meditation-based interventions have positive effects on the management of stress and diabetes. The beneficial effect of meditation on the management of diabetes includes; (a) modulation of neuro-humoral mechanisms that are involved in the management of stress, (b) improvement of overall coping ability with a chronic illness and (c) favourable impact on behaviours such as compliance with diet control, exercise regimen and medications. The development of present moment awareness promotes non-judgmental acceptance of the present status and encourages individuals not to indulge in ruminative thoughts on previous or anticipated events. This aspect of meditation helps the individual to come to terms with chronic illnesses such as diabetes. Therefore, mindfulness meditation practices can be viewed as techniques that sharpen the awareness and bring peace and tranquility. These can also be viewed as mindfulnessbased intervention or mind-body therapy. It has been revealed that walking meditation, a form of concentration meditation, produces multiple favourable effects, such as a reduction in cortisol levels, better glycaemic control and reduced arterial stiffness in patients with type 2 diabetes. Rosenzweig et al. analysed the effects of mindfulness-based stress reduction therapy (MBST) on measures of HbA1c, blood pressure, body weight, and psychological symptoms in patients with diabetes. This pilot study found a reduction in HbA1c of 0.5%, reduction in mean arterial pressure of 6 mmHg, and reduction in depression and anxiety scores. Researchers have identified the regions of the brain involved during various aspects of meditation. For example, the anterior cingulate cortex and striatum in attention control, multiple prefrontal regions, limbic regions and striatum in emotion regulation and insula, medial prefrontal cortex posterior cingulate cortex and precuneus in self-awareness. The metabolic effects of meditation are through neuro-humoral modulation and stress reduction. Even short-term meditation has been shown to increase the activity of the prefrontal cortex, which is involved in stress regulation. Meditation suppresses the activity of the amygdala and anterior cingulate cortex, which are involved in flight or fight reaction thus reducing stress hormone levels. In a study that assessed neural activity associated with "Anapanasathi" meditation and love and kindness meditation (Metta), it was noted that after 30 min of meditation, significant changes in functional MRI signals were observed in the right middle frontal gyrus, left inferior parietal lobe, bilateral middle temporal gyrus, bilateral superior temporal gyrus, right inferior temporal gyrus, and left middle occipital gyrus both in novices and experienced meditators. These findings are similar to the other studies performed in long-term meditators. Thus, it can be hypothesized that the relaxation response thus brought about through meditation leads to beneficial effects such as improvement of glycaemic control through mechanisms such as reduction of stress hormone levels. Furthermore, it has been found that mind body therapies such as yoga, tai chi, qigong, and meditation may supplement the conventional care and management of metabolic syndrome. Meditation exerts changes in autonomic functions as well. In an Indian study, it was shown that parasympathetic tone was significantly higher in the meditators than in the control group. As autonomic neuronal dysfunction is related to diabetes control and many complications of diabetes (gastrointestinal dysfunction and cardiac autonomic dysfunction), it will be useful to investigate the changes in autonomic functions, in patients with diabetes when meditation is practised. Intestinal dysmotility due to diabetic autonomic neuropathy and diabetic enteric neuropathy has been implicated as the main reason for gastrointestinal complications such as small intestinal bacterial overgrowth, gastro-paresis, slow-transit constipation and diabetic diarrhoea. These complications lead to poor glycaemic control owing to erratic absorption of glucose. Stress has been shown to increase gastric emptying time, increase distal colonic motility and accelerate small intestinal transit. It is possible to hypothesize that psychological stress-induced changes in intestinal motility have a negative impact on glycaemic control due to erratic glucose absorption even in the absence of diabetes-related autonomic neuropathy and enteric neuropathy. The effects of cardiac autonomic neuropathy, such as reduced heart rate variability during deep breathing, decreased baroreflex sensitivity, and orthostatic hypotension, can be assessed noninvasively, by 5 simple tests (Ewing et al.) ; cardiac autonomic reflex testing (CART). However, the heart rate response to deep breathing is the test that is most frequently utilized because of its high reproducibility and specificity. There is evidence from a small study involving healthy adults that meditation causes an increase in heart rate variability and causes a decrease in the low-frequency to high-frequency ratio (more predominant vagal tone), which indicates improved autonomic function. Furthermore, it has been shown that, in diabetic cardiac autonomic neuropathy, stress decreases high-frequency heart rate variations. Thus, it can be hypothesized that the stress-relieving effect of meditation will have an effect on reduction of low-frequency to high-frequency heart rate variations, indicating better autonomic function. Improvement of cardiac autonomic testing can be taken as a marker of improvement of overall autonomic functions, which might have beneficial effects on the sympathetic-adrenal medullary system, thus improving the glycaemic control. Thus, it can be hypothesized that the mechanisms underlying the bio-physiological effects of meditation would be through reduction of stress hormones (cortisol), improvement of insulin resistance and improvement of autonomic dysfunction. Therefore, we report the original protocol of the study aiming to identify the impact of meditation on glycaemic control and the possible mechanisms, such as modulation of the autonomic nervous system, reduction of cortisol levels, improvement in gut transit time and improvement in insulin resistance. To date, there had not been any clinical trial conducted in Sri Lanka studying the effects of meditation in patients with diabetes. The acceptability of meditation is likely to be high in Sri Lanka, with a population of over 70% Buddhists (Department of Senses and Statistics 2012). With the growing population of diabetes in Sri Lanka, exploration of the effects of mind-body therapies such as meditation is timely, as it is cost-effective, non-invasive and has minimal negative effects. If proven effective, in the future, meditation can be successfully incorporated into the comprehensive management of patients with diabetes to improve physical-psychological and social health in the Sri Lankan setup with minimal resources. Objectives {7} We hypothesize that improvement occurs in selected metabolic and physiological parameters in patients with type 2 diabetes following meditation, independent of standard care. We also hypothesize that these effects occur due to the reduction of stress hormones (cortisol), improvement of insulin resistance and improvement of autonomic dysfunction. The general objective is to determine the effects of meditation on selected metabolic and physiological parameters in patients with type 2 diabetes by conducting an open-label randomized controlled clinical trial and investigating the possible mechanisms by which meditation affects these parameters. Specific objectives are to determine the effects of meditation on glycaemic control, lipid profile and blood pressure, insulin resistance, 24 urinary cortisol, orocecal transit time using lactulose hydrogen breath test and cardiac autonomic functions. This will be done using standard cardiac autonomic reflex testing (CART), and further analysis of ECG recording in order to analyse heart rate variations(HRV) using Power Lab-8 Pro software. Trial design {8} Open-label randomized control parallel group explanatory clinical trial. It will be conducted on patients with type 2 DM who are attending the professorial medical unit clinic at the National Hospital of Sri Lanka (NHSL). Patients will be randomized to meditation and waitlisted arms after an interview and obtaining informed consent. Meditation intervention and all investigations will be carried out in the Department of Physiology, Faculty of Medicine, University of Colombo. Study setting{9} The study will be conducted in a single centre; the National Hospital of Sri Lanka (NHSL), which is a tertiary care hospital. Patients with type 2 diabetes who are attending the professorial unit (academic unit) medical clinic at NHSL are invited to participate in this study. All physiological testing will be carried out in the Department of Physiology, Faculty of Medicine, University of Colombo. Eligibility criteria{10} Adult patients diagnosed with type 2 diabetes within the past 3-5 years who have never meditated before or rarely meditated (less than once in three months) will be recruited to meditation and waitlisted arms, according to the following inclusion and exclusion criteria. i. Age between 18 and 75 years ii. Willingness to participate in a meditation program iii. Commitment to adhere to the program for 3 months. iv. Patients taking ≤ 2 anti-diabetic medications v. HbA1c between 7 and 8% vi. Education level secondary level and above (grade 8 and above) Who will take informed consent? {26a} Informed written consent will be obtained from the participants by the investigators using a consent form after explaining and providing the information sheet. Additional consent provisions for the collection and use of participant data and biological specimens {26b} On the consent form, participants will be asked if they agree to give biological specimens (blood) for the investigations that are explicitly mentioned. Should they choose to withdraw from the trial, data will be used for analysis only if they give permission. Participants will also be asked for permission for the research team to share relevant data, excluding any personal data when publishing the results. Explanation for the choice of comparators {6b} The meditation technique for the study was selected after observation and discussions held on several different meditation techniques used by long-term meditators. Planned intervention is a simple technique that can be grasped by the absolute novice. It is acceptable to patients of any religion and leads to tranquility of mind through techniques such as awareness of one's own respiration. Meditation intervention includes mindful walking meditation and mindful breathing. This meditation technique has been used by the consultant psychiatrist (meditation instructor of our study) among his patients for a long time. Intervention description {11a} The meditation arm will undergo a mindfulness meditation program aiming to achieve calmness and tranquility of mind under the guidance of an experienced instructor for a period of 12 weeks (protocol of intervention-Additional file 1) in addition to usual care. This is a complex intervention and follows the 2006 updated Medical Research Council guidelines. The waitlisted arm will only receive the usual care provided by the clinic. The waitlisted arm will undergo the intervention in the second 3 months, while the meditation arm will be followed up without active meditation intervention. The adherence to the meditation routine while the patient is not actively monitored will be recorded. Ethical aspects of the intervention used Although mindfulness meditation is related to Buddhist philosophy, the techniques used in this clinical trial do not involve any Buddhist teaching. However, when non-Buddhist patients are recruited even after their consent, there may be consequences such as pressure from their religious leaders, family members and peers. This may result in higher rates of dropouts, which is a drawback in these types of studies where the invention does have a religious background. If such instances occur, investigators are dedicated to support their decision to leave the study if desired and to maintain confidentiality at all times. Criteria for discontinuing or modifying allocated interventions {11b} The study will be terminated if there are more psychological/behavioural adverse events reported in the meditation group than in the control group or if there is more than 60% drop-out rate from the meditation program. A strong request from participants will be another reason for termination. Strategies to improve adherence to interventions {11c} Participants will be given a diary to record the meditation practices done at home, which will be checked at each session, and instructions will be given. This will include a record of time spent meditating, problems that occurred, doubts, reasons for distraction, etc. Participants are expected to record their meditation practice daily on most days of the week between weekly sessions. The diary will be used as the tool to check compliance with the intervention. Relevant concomitant care permitted or prohibited during the trial {11d} Concomitant care apart from meditation intervention in both arms will be routine care during monthly clinic visits, which includes medication review and advice, dietary advice, referral to a dietician, and screening for neuropathy and retinopathy. All participants are prohibited from practising in any other form of mind-body therapies, such as yoga. Provisions for posttrial care {30} Patients will have the ability to contact the investigators for any clarifications throughout the study and after the completion of the intervention for a period of one year. Patients will be followed up in their monthly clinic with routine care after the trial. In addition, during the period of the meditation program, they can contact the instructor. They are free to contact either the investigators or the ERC to lodge complaints regarding the study. Any change in the protocol will be communicated to the participants after ethical clearance and consent will be retaken for the study. Outcomes {12} The primary outcome is to study the effect of meditation on glycaemic control in patients with type 2 diabetes as measured by HbA1c. Secondary outcomes The effect on short-term and intermediate blood sugar control as measured by FBS and fructosamine The effect of meditation on lipid profile. The effect of meditation on blood pressure. Analysis of the following possible mechanisms leading to changes in glycaemic and metabolic control in each arm (insulin resistance, autonomic functions, gut transit and 24-h urinary cortisol) Participant timeline {13} Each investigation will be carried out at baseline and postintervention after 12 weeks in all patients in both the intervention and waitlisted arms. Details of the study schedule are given in Table 1. Sample size {14} Patients with type 2 DM will be randomized to meditation and waitlisted arms. The number of patients required was 86 in each arm, which was calculated on the basis of determining a 0.5% reduction in HbA1c in the meditation arm in comparison to the waitlisted arm. The basis of 0.5% reduction is derived from looking at several randomized controlled trials (RCT) which have shown a significant reduction of HbA1c in the meditation arm compared to control arm.. According to a meta-analysis, most of the oral hypoglycaemic drugs lowered HbA1c by 0.5% as well. Therefore, the effect size was taken as a 0.5% difference in the reduction of HbA1c indicating that the lowest significant reduction of HbA1c is 0.5%. A power of 70% and a 95% confidence interval with a drop-out rate of 20% were considered. The following formula was used for sample size calculation: where N = Sample size q1 = Proportion of subjects in the meditation group q2 = Proportion of subjects that are in the waitlisted group Z = Critical value of the normal distribution at ( is 0.05 and the critical value is 1.96) Z = Critical value of the normal distribution at ( is 0.3) E = Effect size (0.5% difference in HbA1c between the two groups) S = Standard deviation of HbA1c in the population (0.8%). Recruitment{15} Patients with type 2 diabetes who are attending the professorial unit medical clinic at the National Hospital of Sri Lanka (NHSL) will be invited to the study. An eligibility screen and a Montreal cognitive assessment (MOCA) will be performed in participants who volunteer. They will be randomized to meditation and waitlisted arms after obtaining informed written consent. Sequence generation {16a} Patients will be randomized to meditation and waitlisted arms with a one-to-one allocation ratio using block randomization of 10 according to an online random number generation program. Concealment mechanism {16b} Sealed envelopes will be prepared in advance, indicating the allocation of each patient according to the recruitment number. At the time of recruitment, the envelopes indicating the allocation will be provided to the researchers who will enrol patients. Thereafter, those who satisfy inclusion and exclusion criteria and give informed consent, will be assigned a unique patient recruitment number in chronological order. The sealed envelope with the allocation for the given recruitment number is opened, and accordingly patients will then either start the meditation programme or be allocated to the waitlisted arm. Implementation {16c} A member of the study team not involved in patient recruitment will generate the allocation sequence for assigning participants according to generated random numbers. Who will be blinded {17a} Data analysts and laboratory staff analysing samples and performing tests will be blinded to the allocation. The trial participant and the investigators will not be blinded due to the nature of the intervention. Procedure for unblinding if needed {17b} Unbinding will only be done if there is a need to further analyse blood samples in case of erroneous results. Plan of assessment and collection of outcomes{18a} The study will be conducted for a period of 6 months. Assessments will be conducted in the following manner at recruitment: screening (baseline), 3 months, and 6 months in both the intervention and waitlisted groups. Measurement tools Anthropometric measurements BMI: Height is measured to the nearest 0.1 cm (maximum distance from heels to uppermost position on head while standing barefoot in full inspiration using a stadiometer). Body weight is measured to the nearest 0.1 kg using a digital scale (Secca) while wearing indoor light clothing. BMI is calculated as weight in kg/height in m 2. Clinical examination Blood pressure: blood pressure in the seated position will be measured after 10 min of rest using a Riester digital blood pressure monitor (Rudolf Riester, Germany). Blood pressure will be checked twice. Laboratory investigations FBS, HbA1c, lipid profile, fructosamine, fasting serum insulin and 24-h urinary free cortisol will be measured in an accredited laboratory. Fasting plasma glucose will be measured in a fully automated biochemistry analyser (hexokinase method), and the lipid profile will be measured by an enzymatic method. HbA1c will be analysed using a high-performance liquid chromatography (HPLC) method. Insulin resistance will be calculated with the homeostasis model assessment (HOMA) equation: fasting glucose (mg/ dL)insulin level (uU/mL)/405. Orocecal transit time The gold standard method to assess gastric emptying is radioisotope scintigraphy. However, due to the noninvasive and simple technique involved, we opted for the orocecal transit time(OCTT) assessment using a hydrogen breath analyzer. Furthermore, by using OCTT, in addition to gastric emptying we can assess small bowel motility, which has an impact on glucose absorption and thus glycaemic control. Although there are more advanced newer techniques, such as MRI scans and capsular endoscopy, to assess OCTT, due to the high cost, these tests cannot be used in our study. Lactulose hydrogen breath test The time interval between ingestion of test meal containing 10 ml of lactulose after overnight fast and rise in breath hydrogen 10 ppm above basal using hydrogen breath analyser (Gastrolyzer, Bedfont Scientific Ltd, UK) is a measure of orocecal transit time (OCTT). A solution including 10 g of lactulose in 100 mL of water will be administered. The breath test is performed at 10-min intervals, and a rise in hydrogen concentrations ≥10 ppm (particles per million) compared to baseline followed by at least two other subsequent rises are taken as OCTT. The OCTT in healthy subjects is between 40 and 170 min for a liquid diet. Cardiac autonomic reflex assessment: CART Autonomic functions will be assessed using Human Physiology AFT equipment (PL2604 by AD Instruments Pvt. Ltd, Australia) Heart rate response to deep breathing, which assesses beat-to-beat R-R variation during six breaths per minute paced slow deep breathing . Heart rate response to standing is expressed as the ratio between the longest R-R interval (between the 20th and 40th beats) to the shortest R-R interval (between the 5th and 25th) after standing from the lying position. Valsalva manoeuvre and calculate the Valsalva ratio (maximum heart rate in phase II: minimal heart rate in phase IV) The blood pressure response after 3 min of standing The blood pressure response to sustained hand grip We will be recording a 15-min of resting ECG before the standard CART protocol. From which a 5-min recording after the patient stabilizes, will be used for subsequent heart rate variation (HRV) analysis. Spectral analysis of HRV, both time domain analysis and frequency domain analysis of the 5-min resting ECG tracing, will be performed using a Power Lab 8 data acquisition system. The following parameters will be assessed according to the Task Force of the European Society of Cardiology and the North American Society of Pacing and Electrophysiology guidelines. In time domain analysis, SDNN (standard deviation of normal-to-normal RR intervals), SDANN (standard deviation of the average normal-to-normal intervals for each 5-min segment of the ECG recording), SDNNI (mean of the standard deviation of all the normal-to-normal intervals for each 5-min segment of the recording), and RMSSD (root mean square of successive RR interval differences) will be analysed. In frequency-domain analysis, VLF (absolute power of the very-low-frequency band: 0.0033-0.04 Hz), LF (absolute power of the lowfrequency band: 0.04-0.15 Hz), HF (absolute power of the high-frequency band: 0.15-0.4 Hz) and LF:HF (ratio of LF-to-HF power) will be analysed. Pre-and post-meditation HRV analysis as well as any difference between the intervention and control arms will be compared. Furthermore, it has been shown that the cardiac vagal tone assessed using 5-min resting electrocardiogram recording has a good correlation with HRV analysis performed with 24-h recording in detecting subclinical cardiac autonomic neuropathy in patients with type 1 diabetes. Plans to promote participant retention and complete follow-up {18b} Patients are given access to contact the meditation trainer and the investigators throughout the trial period to clarify doubts. Primary outcome data will be collected in patients who discontinue or deviate from the intervention protocol if consent is granted. Participants will be contacted by the investigators periodically and encouraged daily practice of meditation and documentation in the diary. Data management {19} Data will be entered by a dedicated person who is blinded to the patient allocation. Double data entry will be performed and will be stored under password protection in a dedicated computer. Confidentiality{27} All interviews will take place in a confidential room. Personal information is only gathered to ensure the correct identification of patients when issuing the investigation reports. It will not be shared with a third party without their consent, and all data gathered will be securely kept under the direct supervision of the investigators. All data gathered will be stored securely for 5 years and then destroyed. Only the principal investigator and supervisors will have the authority to access the data. Plans for collection, laboratory evaluation and storage of biological specimens for genetic or molecular analysis in this trial/future use {33} All the blood samples taken will only be used for the intended test, and no genetic studies will be performed. Blood samples will not be sent abroad or given to a third party. All samples will be stored for a period of one month for the completion of the tests and securely destroyed. All the reports of the blood tests will be given to the patient with a copy kept with the investigators. Statistical methods for primary and secondary outcomes {20a} Statistical analysis will be performed using SPSS v-23. Intention to treat analysis will be carried out. Data will be analysed using descriptive statistics (frequency distribution, mean) to demonstrate the distribution of data for each parameter. Comparative statistics will be used to compare the findings between the sample groups, within the sample and control. Correlation analysis will be conducted to assess the correlation between related parameters. Each of the outcomes will be analysed using multiple regression analysis to ascertain the differences between trial arms. A linear regression model for continuous variables and logistic regression for binary variables will be used. Data monitoring committee{21a} An independent data safety monitoring committee was appointed comprising senior researchers who have no competing interests. Any adverse events occurring will be reported to the committee by investigators and will be independently assessed. Interim analyses {21b} If serious adverse events related to the intervention are reported in the meditation arm, the data safety monitoring committee and the investigators will discuss and decide to terminate the trial. Thereafter, an interim analysis will be conducted from the available data. The ethics review committee and the Sri Lanka Clinical trial registry will have access to interim results. Methods for additional analyses (e.g., subgroup analyses) {20b} Subgroup analysis of the primary and secondary outcomes will be performed according to the age, gender, duration of diabetes and baseline HbA1c. Methods in analysis to handle protocol nonadherence and any statistical methods to handle missing data {20c} We are planning to conduct an intention-to-treat analysis. Therefore, primary outcome data of the participants randomized to the intervention but who did not adhere to the intervention will be imputed using multiple imputation methods available in SPSS. Plans to give access to the full protocol, participant-level data and statistical code {31c} The datasets analysed during the current study and statistical codes are available from the corresponding author on reasonable request, as is the full protocol. Oversight and monitoring Composition of the coordinating centre and trial steering committee {5d} The coordinating centre will be the Department of Physiology, Faculty of Medicine, University of Colombo, led by the Head of the department. The trial steering committee will comprise of investigators and medically qualified research assistants. The role and responsibility of the coordinating centre and trial steering committee will be, to coordinate patient recruitment, provide support with coordinating appointments for investigations, provide day-to-day liaison service and solve technical issues. The steering committee will closely monitor technical officers regarding maintenance of equipment and supply of consumables. The research promotion and facilitation centre (RPFC) of the Faculty of Medicine, University of Colombo, will provide oversight. The trial steering committee will meet once a month over the course of the trial to discuss the progress. The progress report will be submitted periodically to the ethics review committee and research and higher degrees committees. Adverse event reporting and harms {22} Patients will also be monitored throughout the study for any adverse events related or unrelated to meditation (e.g., adverse effects of anti-diabetic drugs). Their health and well-being will be assessed through clinical assessment and monitoring of investigations. Serious adverse events will be monitored by the data safety monitoring board and reported to the ethics committee and the treating physician. The necessary actions will be taken, including further investigations and management steps. Patients who suffer any serious adverse events will be monitored and followed up for an extended period of 2 years, regardless of whether they continue to be part of the study. Frequency and plans for auditing trial conduct {23} The Project Management Group, comprising both the members from the coordinating centre and trial steering committee, will meet monthly to review the trial conduct. The trial Steering committee and the independent data safety monitoring board will meet monthly and if there are any issues reported to the Ethics Review Committee of the Faculty of Medicine, University of Colombo, throughout the trial period. Any protocol amendments will be duly notified to the Ethics Review Committee, and approval will be taken prior to implementation. Plans for communicating important protocol amendments to relevant parties(e.g., trial participants, ethical committees) {25} Any amendments to the protocol will be communicated in writing to all participants, and consent will be taken from them prior to conduct. Approval for any protocol amendments will be taken from the Ethics review committee of the Faculty of Medicine Colombo and Sri Lanka Clinical trial registry. Dissemination plans{31a} The individual results of the investigations will be shared with the relevant participant. The overall results of the trial will be published in peer review local and international journals and will be presented in scientific conferences. All investigators will be authors, and professional writers will not be involved. Discussion We believe that this will be the first randomized controlled trial in Sri Lanka to assess the effectiveness of mindfulness meditation on the glycaemic control of type 2 diabetes. Although similar studies have been performed in other parts of the world, data from randomized control trials involving South Asians are lacking. As meditation intervention may have different outcomes in different populations, the results from our study will benefit the management of a growing population of patients with diabetes mellitus in our region. Furthermore, some of the possible mechanisms of how meditation brings about glycaemic control, such as its effect on autonomic function and gut transit time, will be studied for the first time in this trial. However, it is difficult to assess the generalizability and fidelity of the intervention across all patients as meditation is a highly individualised intervention which depends on multitude of factors. This is a shortcoming of this type of a clinical trial.
The Kirschner operation in unresectable esophageal cancer: current application. HYPOTHESIS With the introduction of safe, effective nonoperative alternatives, bypass surgery for unresectable esophageal cancer is infrequently performed, but it has a limited role in palliation of esophageal cancer that needs to be defined. DESIGN Retrospective cohort study. SETTING Department of Surgery at Queen Mary Hospital in Hong Kong. PATIENTS Patients who had unresectable esophageal cancer and underwent bypass surgery between January 1, 1991, and December 31, 1998. INTERVENTION Bypass procedures were performed using a gastric or colonic conduit to the neck. MAIN OUTCOME MEASURES Morbidity and mortality and quality of palliation. RESULTS Thirty-eight patients underwent retrosternal bypass to the neck using a gastric (n = 27) or colonic (n = 11) conduit. Ten patients (26%) underwent unplanned bypass at the time of exploration for resection because of unexpected findings of T4 disease (n = 2) or technical difficulties in addition to advanced disease (n = 8). Between 1991 and 1994, 1 of 26 bypasses was unplanned and the hospital mortality was 42% (11/26), while between 1995 and 1998, 9 of 12 bypasses were unplanned and the hospital mortality was 8% (1/12). There were 12 hospital deaths in the planned bypass group (n = 28) and none in the unplanned bypass (n = 10) group (43% vs 0%, P =.01). The median survival in patients who underwent unplanned bypass was 6.9 months, compared with 1.9 months in patients who underwent planned bypass (P =.004). All patients were discharged from the hospital on at least a semisolid diet. CONCLUSIONS The Kirschner operation is largely obsolete as a planned procedure because of high morbidity and mortality. Bypass surgery, however, is a reasonable option as an unplanned procedure when resection is precluded at the time of exploration because of unexpected adverse operative findings.
#!/usr/bin/env python3 """ run.py: run ocrevaluation-docker usage: run.py code source: https://github.com/nlppln/ocrevaluation-docker 20181127 erikt(at)xs4all.nl """ from nlppln import WorkflowGenerator with WorkflowGenerator() as wf: wf.load(step_file='https://raw.githubusercontent.com/nlppln/ocrevaluation-docker/master/ocrevaluation.cwl') # add workflow inputs gt = wf.add_input(gt="File") ocr = wf.add_input(ocr="File") # add data processing steps # to run the ocrevalUAtion tool for a single file: out_file = wf.ocrevaluation(gt=gt, ocr=ocr) # or for a list of gt and ocr files: # out_files = wf.ocrevaluation(gt=gt_files, ocr=ocr_files, scatter=['gt', 'ocr'], scatter_method='dotproduct') # add more processing tools # add workflow outputs wf.add_outputs(result=out_file) # save workflow to file wf.save("run.cwl",mode="rel")
Democrat Wendy Davis has star power and a growing following, but can she get elected governor of Texas, a Republican stronghold? A rising Democratic star will seek office in a state where Republicans hold every statewide office and her party's candidate hasn't been elected governor since 1990. Democrat Wendy Davis has star power and a growing following from San Francisco to New York City. But can she translate the fame she achieved from her epic filibuster of a bill restricting abortion into a successful race for Texas governor? That's the unknown as Davis begins her quest to succeed Rick Perry, governor of Texas for nearly 13 years and the Republican who helped make the state one of the reddest in the nation. She announced her candidacy Thursday at her suburban Fort Worth high school by denouncing a political culture in Austin that she says caters to special interests instead of the middle class. "Texas has waited too long for a governor who knows that quid pro quo shouldn't be the status quo," Davis said. "It's time for a governor who believes that you don't have to buy a place in Texas' future." Davis, a second-term state senator, became a national sensation in June when she stood for nearly 11 hours in her pink running shoes and railed against a bill that would ban most abortions after 20 weeks and impose strict requirements on clinics. Her filibuster stopped the bill initially, but it eventually passed a special session of the GOP-controlled Legislature and was signed into law by Perry. On paper, the challenges for any Democrat in Texas are daunting. The last Democrat elected governor of Texas was Ann Richards in 1990. None of Perry's rivals in his three campaigns for governor mustered more than 42% of the vote. Davis' opponent next year will probably be state Attorney General Greg Abbott, the favorite to win the Republican nomination. Abbott did not mention Davis by name in a video he released hours before her announcement, casting himself as a pro-gun, business-friendly candidate. He vowed to preserve Texas "as the land of liberty and freedom against Obama and his allies as they attempt to turn Texas blue." Though Davis' post-filibuster fundraising added $1 million to her campaign account, Abbott has more than $20 million socked away. Political experts say it could take $40 million to compete and win in Texas, where advertising in expensive media markets such as Dallas and Houston is as important as retail politics in the Rio Grande Valley and Panhandle. "Ultimately, you only raise money if people think you can win," said Matt Mackowiak, a Republican political consultant and co-founder of the Must Read Texas political website. "The sugar high of her getting in will wear off because it's going to come down to is this a winnable race and is it worth the investment." Matt Angle, director of the Lone Star Project that helps elect Democrats, says victory is possible. "Wendy Davis has the ability to build the type of coalition that a Democrat has to build to win in Texas, one with Democrats, independents and fair-minded Republicans of all races," Angle said. "She projects strength and energy and a positive vision." Angle dismissed Abbott's fundraising advantage, saying Davis will be able to raise the money necessary "to tell her story." Davis' up-from-the-bootstraps narrative will be told repeatedly as she introduces herself to Texas voters in her first statewide race. She married young, got divorced, then became a single mother at the age of 19. Davis struggled to make ends meet and lived in a trailer park but eventually went to community college, then Texas Christian University before going on to Harvard Law School and a career as a lawyer. Support from women voters will be key for Davis, who has stressed issues such as education since she won a Texas Senate seat in 2008 that was previously held by a Republican. EMILY's List, the political group that helps elect Democrats who support abortion rights, has been an early supporter and will be with Davis in this campaign. "The EMILY's List community has known for years that Wendy Davis is a powerhouse who stands up for Texas women and families," said Stephanie Schriock, president of the group. "Wendy can win because she believes in Texas, not politics." Democrats in Texas have long believed the changing demographics of the state are in their favor, even though the GOP holds every statewide office. The governor's race will be one of the first tests of whether more Hispanics, who make up nearly 40% of the state's population, will register to vote and go to the polls. In the 2012 presidential election, 1.4 million more Hispanic voters cast ballots than in 2008, according to U.S. Census Bureau figures, while the number of non-Hispanic white voters shrank by more than 2 million. "For a Democrat to win in Texas in 2014, there would have to be an unprecedented mobilization and enthusiasm among Latino voters," said Matthew Wilson, a political scientist at Southern Methodist University in Dallas. "An Anglo woman best known as an abortion champion doesn't seem well positioned to achieve that." Texas Right to Life is airing radio ads in English and Spanish in South Texas about Davis, aimed at Hispanics and socially conservative voters. The narrator in the spot says Davis is an "abortion zealot" who cast her filibuster as a stance being made on "sacred ground."
Parenting Intervention for Psychological Flexibility and Emotion Regulation: Clinical Protocol and an Evidence-Based Case Study Psychological flexibility has been found as a protective factor for several psychological problems, including the field of parenting. The present study aims to illustrate a clinical protocol, session by session, for the promotion of parental psychological flexibility and emotion regulation in a case study. The clinical protocol is based on third-wave behavior therapy in a brief intervention of four sessions. The intervention is presented in a clinical case of a mother with a child diagnosed with Oppositional Defiant Disorder. Both mother and child experienced problems with emotional regulation and psychological flexibility. The results show clinically significant improvements in psychological flexibility, emotional regulation, and stress parenting in the mother both after the intervention and at follow-up. In the child, emotional perspective-taking skills, acceptance, and valued actions improved. The case illustrates in detail the application of different strategies of acceptance, mindfulness, emotion regulation, and emotional defusion applicable to parenting. Clinical implications are discussed. Introduction Psychological flexibility is defined as the disposition to remain in contact with unpleasant experiences and private events, fully and consciously, in the direction of values. This skill has been explored as a positive factor in mental health, anxiety, or depression. Specifically, psychological flexibility allows individuals to adapt for greater personal functioning, both cognitively and behaviorally. This makes psychological flexibility a protective factor with respect to mental health. Psychological flexibility is a response and a coping style for distressing situations in life. In contrast to other perspectives in which cognitive or behavioral avoidance is a valid strategy, psychological flexibility aims to enhance functional patterns with acceptance-based coping strategies. Previous studies have shown that emotional suppression and avoidance coping strategies have paradoxical effects. It is therefore not surprising that psychological flexibility is involved in parenting and bringing up children, and this is called parental psychological flexibility. In fact, several studies relate psychological flexibility as a protective factor with respect to the stress that parenting may entail. It is also a mediating factor in parenting styles in parent-child interactions. A flexible pattern in parenting has been shown to be related to fewer externalized and internalized problems, better parenting practices, personal and family adjustment, and reactivity. Parenting focused on the present moment is related to better adaptive emotion regulation and attachment in children, as well as more emotion regulation, compassion, and psychological flexibility in adolescents. Parenting styles in turn affect the development of psychological flexibility in their children, and authoritarian styles are related with less psychological flexibility in children. Regardless of psychological flexibility, parenting practices have an influence on the psychological well-being of children. Specifically, it has been found that authoritarian or permissive styles are directly related to aggressive behaviors in children. Similarly, authoritarian and neglectful parenting styles are related to antisocial behaviors and irritability or defiant disorders. This relationship is also found with the academic performance of the children. Acceptance and Commitment Therapy (ACT; ) aims to enhance psychological flexibility. In this sense, the training in this skill in ACT is supported by six interconnected skills: acceptance, defusion, mindfulness, self as context, actions, and values. These skills can be understood as three flexible response styles: a response style that is willing to be in contact with their uncomfortable feelings (open), focused on the present moment (aware), and engaged in their actions in the direction of values (active). ACT is part of a group of therapies called third-wave behavior therapies that emphasize the contextual and functional value of behavior. The strategies of this therapy are based on the behavioral principles of learning and language analysis through the Relational Frame Theory (RFT; ). Psychological flexibility, when included in parenting, is a way to relate with private events (emotions, thoughts, feelings, etc.). It can therefore be understood as an adaptive strategy for regulating emotions focused on acceptance for a value-driven purpose. ACT has not been developed as a parenting intervention as such, but it has made use of strategies and components to intervene with parents. A review by Byrne et al. noted that the application of ACT in parents has shown positive effects in children with ASD, chronic pain, in medical problems (such as acquired brain injury, cerebral palsy, asthma, diabetes, deafness, etc.), and anxiety. In addition, mindfulness training programs for mothers have shown reduction in aggressive behaviors in their children with autism spectrum disorders (ASD). From an ACT perspective, Blackledge and Hayes suggested that emotions per se do not cause maladaptive emotion regulation, but are the consequence of attempts at regulating these emotions and interference of these actions in one's life, within the social, cultural, and verbal context. In this regard, the concept of flexible emotion regulation emphasizes the use of emotion regulation strategies adapted to contextual demands, and considers the coherence of the strategy with the direction of personal goals. A study by Seligowski and Orcutt found that in Gross's model, emotional distancing strategies are a factor in proneness to emotion. Emotion regulation of parents in terms of frequency, duration, and valence affects the emotional development of their children and family dynamics. Emotion regulation by parents with children with or without a psychological disorder also differ. It should be considered that emotion regulation styles are not only learned by children following parental models, but that those of children also affect their parents. Similarly, parenting styles affect the emotional development of children and family interaction. Thus, the response of parents to the emotional reactions of their children is important to their development. Parental response to their children's behavior based on emotional acceptance and validation positively affects emotion regulation and reactivity, whereas responses such as invalidation can favor the development of psychological problems in their children. That is the reason why the intervention in families must consider the parents' abilities, not only of parenting, but also their abilities to face their emotions, thoughts, or sensations in situations of managing their children's behavior or emotions. The aim of this study is to illustrate the application of a clinical protocol for the promotion of parental psychological flexibility and emotional regulation through third-wave behavior therapy (or contextual therapy) strategies in parents of children with psychological diagnosis in a secondary analysis. This clinical protocol has been shown to be effective in improving psychological flexibility, emotional regulation, and parental stress in different formats. Specifically, this study addresses this clinical protocol in the case of a mother with a child with Opposi-tional Defiant Disorder, as well as explores the effects of the intervention on children. Considering evidence-based treatments for adolescents with behavioral disorders, level one treatments (working well) are those that combine behavioral therapy, cognitive-behavioral therapy, and family therapy. Likewise, Division 53 of the APA indicates as experimental phase treatments some intervention programs with third-wave therapies, such as mindfulness or Dialectical Behavioral Therapy. The role of parenting skills, the parent-child relationship, social support, and parental emotional regulation are shown to be potential factors (risk/protective factor) that may influence the development of Oppositional Defiant Disorder. Therefore, it is relevant to provide parental interventions in emotional issues such as acceptance or emotional distancing that promote functional and constructive parenting skills. This paper illustrates the application of an intervention, mainly based on ACT strategies, due to the difficulties related to the mother's rumination and cognitive fusion, which are hypothesized to be the basis of the family interaction problems. It is expected that the effects of the intervention with the mother will also improve the child's behavior, even if no intervention was made directly with the child, as observed in previous studies. Patient Presentation David's parents sought help worried about the problems they were experiencing with their son. Over the prior year, David's coexistence and behavior problems were becoming worse, and his parents were looking for a solution so that David "learns to control his emotions". The parents felt they had tried many parenting strategies and had no more resources to deal with their child's behavior problems. David is a 12-year-old Spanish boy with Oppositional Defiant Disorder, diagnosed at age 8. This disorder is characterized by a pattern of anger, defiance, or vengefulness that affects the person individually or their social environment (family, school, etc.), persisting for at least six months. In the year before David's parents decided to seek help, David's behavioral problems worsened. His symptoms were mainly explosive and aggressive behavior associated with frustration tolerance, especially at home (e.g., losing in video games or not being able to leave home). Those behaviors led his parents to use strategies of control of stimulus and punishment, but those strategies were not efficient. His parents felt discomfort associated with their family problem that made coexistence and family dynamics increasingly complex. All participants gave their informed consent before starting the study and they did not receive any financial incentive for study participation. This study received the ethical approval of the Andalusian Health Service's Almeria Research Committee (reference: PI-REFLEX-ESFA-19, approved: 24 June 2020). Clinical Case History David lives with his mother (45 years old), his father (45 years old), and his older sister (13 years old) in a single-family house in a municipality near to the provincial capital. They are a middle-class family. The mother is an independent worker as a support teacher and has higher education. She has been diagnosed with fibromyalgia and asthma. The father has basic education and works as a freelancer with a music studio at home. Both consider that they have received little support to face the problem of their son. David was officially diagnosed with Oppositional Defiant Disorder at age 8, without having history or comorbidities of other disorders. Aripiprazol was prescribed from the beginning, which with psychological support can stabilize behavioral problems. However, these problems reappeared at age 11, mainly in the family context with defiant attitude, irritability, impulsiveness, and vengeful behavior with their relatives. The pregnancy proceeded normally, and he was born with branchial paralysis. There is no history of medical illness. In the family there is a history of impulse control problems on the maternal side (the father of the mother), with strong attacks of anger and aggressiveness, aggravated by alcohol abuse. David has always been a contentious boy, with low academic motivation. He has some basic housework responsibilities, although his mother ends up fulfilling his responsibilities. At times he has been saturated with activities that he did not choose himself (e.g., playing the piano). The parents describe a family environment in which each is doing their own things and sharing little family time. The parents tried to control David's behavior by repeating the rules and even insulting him, yelling at him, and punishing him by withdrawing privileges. Before starting the intervention, the parents signed the informed consent. All the data presented in this case study are masked to safeguard confidentiality. Parent Outcome and Family Functioning The information reported in the clinical history section was obtained in an initial interview attended by both parents. After that, the following instruments were applied. Parental Acceptance Questionnaire (6-PAQ) was applied to assess parental psychological flexibility and three related behavioral styles: open, aware, and active. The Spanish version of the scale consists of 16 items on a four-point Likert scale. The overall scale scores are between 4 and 64. The Spanish version of the instrument has a Cronbach's alpha of 0.81 (RCI total score: 6.83). (To estimate the clinical efficacy of the intervention, the Reliable Change Index (RCI) was calculated using the method of Jacobson and Truax for all variables (see baseline results section for more details.) Acceptance and Action Questionnaire-II (AAQ-II) measures experiential avoidance in 7 items on a 7-point Likert scale. The overall scale scores are between 7 and 49. The Spanish version of the instrument has a Cronbach's alpha of 0.88 (RCI total score: 10.63). Difficulties in Emotion Regulation Scale (DERS) was used to evaluate treatment effects on emotion regulation. This scale measures a total score and 5 emotion regulation processes in 28 items on a 5-point Likert scale. The overall scale scores are between 5 and 140. The total score for the Spanish version of the instrument has a Cronbach's alpha of 0.91 (RCI total score: 12.91). Parenting Stress Scale (PSS) was used to asses stress related to parenting. This scale consists of two dimensions in 12 items rated on a 5-point Likert-type scale: baby rewards and parent stressors. The overall scale scores are between 5 and 60. The Spanish version of the instrument has a Cronbach's alpha of 0.77 (RCI total score: 7.98). Satisfaction with Life Scale (SWLS) was used to assess general satisfaction with life. It consists of 5 items on a 5-point Likert scale. The overall scale scores are between 5 and 25. The Spanish version of the instrument has a Cronbach's alpha of 0.88 (RCI total score: 5.7). Finally, the Parenting Style Questionnaire (CEEP) was used to assess parenting difficulties at pre-test. This scale consists of five dimensions in 110 items: family dynamics, emotional competences, parent role, parenting style, and parenting practices. The Spanish version of the instrument has a Cronbach's alpha of 0.92. Parent Process Outcome To evaluate the progress of the intervention, at the beginning and at the end of each session mood, coping and consistency in valued actions were assessed. Mood was measured by asking "How do you feel right now?" followed by a 5-face visual scale that has been used in previous studies. Coping perception was assessed using the question "How able do you feel to address your concerns about your children right now?". At pre-session, the implication in valued direction action was assessed on a 10-point Likert scale (we transformed this score to a 5-point scale to make it comparable to the other process outcomes). These questions were developed ad hoc for a momentary assessment of the person's progress in the intervention. Child Outcomes Strengths and Difficulties Questionnaire (SDQ) was used to assess treatment effects in David. This scale consists of a total score and 5 factors: emotion symptoms, behavioral problems, hyperactivity, problems with peers, and prosocial behavior. The overall scale scores are between 0 and 50. The Spanish version of the instrument has a Cronbach's alpha of 0.77 (RCI total score: 8.77). David's psychological flexibility was assessed using the Avoidance and Fusion Questionnaire for Youth that measures avoidance and cognitive fusion; it has a Cronbach's alpha of 0.87. The overall scale scores are between 0 and 68 (RCI total score: 0.76). The Willingness and Action Measure was used to assess acceptance and valuedoriented actions. The overall scale scores are between 5 and 70. The Spanish version of the instrument has a Cronbach's alpha of 0.78 (RCI total score: 11.65). Measure of Intervention Satisfaction Client Satisfaction Questionnaire was used to assess general satisfaction with the treatment. It consists of 8 items on a 4-point Likert scale. Acceptability, usability, and interest of the clinical protocol were evaluated with 3 questions on a 4-point Likert scale, developed ex post facto. Baseline Assessment Results The Jacobson and Truax method was used to assess the clinical changes of the intervention. Specifically, the Reliable Change Index (RCI) was calculated following the "c" criteria. To obtain the cut-off score, the mean and standard deviation of the normative sample (of the instrument validation population) and of the mother were used. A score was considered "recovered" if its score on the post-test changed with respect to the RCI value and if it was lower than the cut-off score. It was classified as "improved" if it was a change in the RCI value but not in the cut-off score. At pre-test, we found that the mother has difficulties to maintaining a parenting style with psychological flexibility, especially in her abilities to behave in an open and aware response style. That is, high scores were obtained on the 6-PAQ scale. For the AAQ-II score we observed high experiential avoidance. We found high scores in difficulties to regulate her emotions, especially for using acceptance, interference with goal-oriented behaviors, and limited access to emotion regulation strategies. Furthermore, a high score was found in parenting stress, both stressors and rewards. Satisfaction with life level was low compared to the normative mean score of the instrument. Regarding the mother's parenting style, difficulties focused mainly on an excessive parental role and emotional competences. That is, high scores were obtained in these competences of parenting in relation to the mean score of the instrument. At a qualitative level, these difficulties were found as excessive burden, impulsivity, lack of perception, and management of emotions. On the other hand, we found problematic scores in terms of how she interacts with her child to manage disruptive behaviors and uses adaptive corrective strategies in her son. As for family dynamics, the presence of conflicts in family environment stands out. The predominant educational style in the mother is permissive. The father's pre-test assessment showed high scores of parental psychological inflexibility. In addition, scores above the normative mean in emotional regulation difficulties (DERS) were found, especially in his attention to emotions and access to strategies for emotion regulation. Like the mother, above-average scores on parental stress were found. Finally, concerning David's problem assessment through the SDQ, we found that the mother reported higher scores (clinical scores) of emotional symptoms than the father, while the father reported higher levels (clinical scores) of behavioral problems. Both parents reported hyperactivity and problems with peers at a normal level. Additionally, David's self-report questionnaires showed high scores of cognitive fusion, experiential avoidance, and action difficulties in distress situations. Case Conceptualization Due to of all the above, we considered that it was necessary to carry out an intervention with David's parents to improve their parenting skills and emotion regulation strategies to face distress situations with their son. David's last episodes of impulsive and aggressive behaviors were generating a coercive system in family dynamics. Based on the parents' difficulties, a parenting intervention was proposed for both, although for work reasons the father only went to the first session. On the one hand, the mother was acting in a rigid and fused way, following her beliefs and thoughts of: "my son is ill and cannot control himself", "all my son's actions are revengeful", "my son's problem is an inheritance from my father", or "he doesn't care about everything". All these private events were maintaining her coherence to explain the beginning and maintenance of the problem, locating the locus of control externally. When David's behavior problems happened, the parents impulsively described all these thoughts, leading to some emotional invalidation. On the other hand, David showed ruminative responses in situations of frustration. The most frequent thoughts were "everything sucks!" and "what a disgusting life!". Given the literature reviewed of the effects of parents' emotion regulation and psychological flexibility skills in their children, we hypothesized that the proposed intervention would foster parenting skills and, similarly, improve David's emotional well-being. Treatment The intervention took place in a public healthcare context, specifically in the infant's and children's mental health unit in the province of Almeria (Andalusia, Spain). Group treatment was administered in four two-hour weekly sessions (total of eight hours over one month) and was attended by four more mothers. Although the intervention was carried out as a group, the initial interview and follow-up were conducted individually. The goal of the clinical protocol was developed following third-wave strategies to promote parental psychological flexibility and emotion regulation for coping with situations or contexts related to bringing up children who can generate stress. Specifically, this clinical protocol makes use mainly of ACT strategies. The clinical protocol was developed by the authors of this article. The intervention was applied by a psychology Ph.D. student with training and experience in the application of these therapies in children, adolescents, and families. The protocol was supervised by two psychology department heads and controlled with a checklist to ensure all the exercises were performed. The clinical protocol was framed within a metaphor written for the purpose called "the Parenting Forest", based on which a series of exercises were performed for improving parental emotion regulation strategies with acceptance, focusing on the present and directed at actions in the direction of their values. Table 1 shows the clinical protocol contents and exercises. The treatment program was introduced with a presentation and ice-breaker exercise memorizing the names and some characteristics of the members of the group. In general, the participants did not remember the characteristics of the others and we made use of this to make an analogy with the concept of mindfulness. Then, the "Forest road" metaphor was told. In this metaphor, they were asked to imagine that they were walking through a forest and at the end of the road they would find "what was most important in their lives". While they were walking, the forest became dark, and things appeared that upset them. Then, we asked the mothers whether they should go back to the beginning of the forest or keep on to the end of the road. Later, we discussed what everyday things they do with their children to get them closer to or farther away from the end of the road. In this exercise, it was intended to identify what emotions, thoughts, feelings, or stimuli cause them to become upset. Thus, the parents were able to identify the main sources of distress in bringing up their children and what they were doing to palliate it, by working from creative hopelessness. Attempts at avoidance maintained by negative reinforcement have paradoxical effects in raising children. If it does not appear, it is important to introduce the concept of acceptance in this metaphor and differentiate it from resignation. Then, some pebbles were distributed to the participants and they were told that they represented thoughts and emotions that appear in complicated situations or that cause them distress, and then they performed the "The mind is a lake" exercise (inspired by "The mind is a jar" exercise by ). In this exercise, the parents were asked to put the pebbles in a jar of water and name emotions and thoughts as they did so. Then they shook up all the stones causing a whirlpool, and they could see that this way they could not distinguish or see thoughts and/or feelings clearly, and it is harder to regulate behavior. This exercise emphasizes that the thoughts and emotions form part of the mind, that they are there and are part of our nature. Strategies directed at eliminating or diminishing these private events may be counterproductive. In continuation, the strategies the parents used to regulate their emotions were explored, and the "mindfulness to breathing" exercise was performed as a useful strategy for identifying emotions and paying attention to them. Finally, values were clarified and general goals posed based on those values using "The garden" metaphor. Valued aspects are presented in this metaphor (children and two chosen by the mother herself) as plants that must be cared for by a gardener (the mother). Thus, goals were differentiated from the values as the basis for concrete actions to achieve the goals proposed. The work on committed actions and values is ideographic and guides the treatment. For homework, they were asked to practice full attention with their children for at least 30 min, avoiding distractions and thinking about what specific actions would meet their goals toward values. Session 2 The purpose of the second session was to provide the families with emotion regulation skills related to acceptance, mindfulness, and decision-making (problem-solving). It began by reviewing "the garden" metaphor in which the difficulties that could come up while practicing full attention were discussed, and a series of specific actions for achieving the goals were set (among them trying to include practicing full attention in the time they devoted to their children). Then, the "Body scan" mindfulness exercise was practiced. This exercise was intended to expand the parents' mindfulness skills by helping them to identify their physical sensations related to emotions. It was explained that these physical sensations can help identify the emotions that drive behavior and can be a "warning signal" to make space. Based on the barriers found in completing the homework assigned in the previous session, the difficulties in regulating emotions and balancing actions carried out were discussed. Then, the "wise mind" exercise was presented. In this exercise, mental states or mindsets were distinguished: the rational mind, which is guided by logical thought, and the emotional mind, where mood and feelings at the moment guide behavior. At this point, some example behaviors were suggested which use each of these two minds, and their usefulness was discussed, always validating both mindsets depending on the context. If they did not arrive at the conclusion of an intermediate approach on their own, we presented the "wise mind" as a state in which the emotional and rational mind are balanced, and personal values take the lead in guiding actions. From that moment on we reminded them to use the wise mind to promote actions based on values with acceptance (see Appendix A for a clinical dialogue with the mother). Finally, a defusion exercise which we call "The star observatory" was practiced. Its purpose is to strengthen perspective-taking in private events. The mother was asked to imagine a thought or an emotion that generated distress in parenting. Then, she should imagine this emotion in a starry night sky, like a constellation on which she should concentrate all her attention. She was asked to imagine different physical characteristics of this constellation (shape, color, luminosity, etc.) and locate it from different perspectives. To finish, she was supposed to distance herself from this constellation while observing that it was part of a whole heaven of constellations. This was intended to show the participant how to distance herself from that thought, reframing this private event in a hierarchy with respect to herself as just another experience forming part of her whole context. It is expected for this type of exercise to help de-literalize private events, making it easier for the parents to take action in the direction of their values, and not necessarily toward what they think or feel: that is, make space for acceptance. This exercise connects with the "Forest road" metaphor and the "Mind is a lake" exercise. As homework, they were asked to continue practicing informal full attention in some activity with their children and for themselves. A list of informal full attention activities was proposed (eating, showering, observing sounds, etc.). Finally, the garden metaphor was taken up again, telling them that they needed to keep working on the garden. Session 3 In the third session we reviewed the skills practiced and how they could be applied in a functional analysis of the children's and the parents' own behavior. Afterwards, homework was reviewed, and problems found were evaluated. The session started with an exercise on mindfulness to sounds. The exercise began with meditation concentrating on the present moment. The mothers were asked to concentrate on the sounds while a track was played with sounds from nature. As in the rest of the mindfulness exercises, they were reminded of the importance of paying full attention, without judging the experience. Later, actions were reviewed again with the "Garden" exercise. This way, we evaluated progress during the sessions and identified the barriers that came up when these actions were carried out. Based on the problems found during the week, they were asked to identify a difficult situation with their child and make a functional analysis with the aid of a sheet. First, they were asked to describe the situation but not judge it. The difference between describing and judging an experience should be emphasized. A functional analysis was conducted of both parents' and children's behavior, keeping in mind background factors, problem behavior in terms of actions, private events, and physiological reactions, and their consequences in these three terms. At this point, they reflected on whether the reaction was consequent with their values, or if on the contrary, it was an impulsive response and they had been fused with private events when they acted. They were asked how the skills learned during the program could be employed in each of the links in this chain of behavior. As an antecedent control, the mindfulness exercises may be of help in anchoring in the present, observing the experience without judging it, and becoming aware of the private events that are related to the reactions. The defusion and acceptance exercises can be of help in taking a perspective on thoughts and emotions at the moment, so reactions are not driven by private events, but with a space for their acceptance. Finally, the garden exercise regards values and actions which are the guide for identifying whether reactions and consequences are in line with personal values and the sense they make in their own lives. The goal of facilitating functional behavior analysis associated with the skills worked on in the program is combined with parental emotion regulation by building up a flexible response pattern in parenting. Another defusion exercise called "The cascade of emotions" was carried out. As in the previous session, the purpose was to de-literalize private events. The participants were asked to imagine different thoughts that arise in an upsetting situation and to write them down or draw on leaves that run along the course of a river. These exercises were also intended as mechanisms for showing the mother how to lessen her reactivity to private events so she would be able to relive them without needing to judge or react to them. The session ended with the "Connect and Shape" model developed by Whittingham, as a positive parenting model following a series of steps in managing child behavior problems. To summarize, first the child is validated emotionally to understand their emotions in relation to the situation. After that, it should be attempted to reorient behavior by facilitating an opportunity to respond adequately, without explicitly solving the problem. The third step consists of paying attention and waiting, at a certain distance, and accepting a new opportunity for molding. If during any of these three steps their behavior comes closer to adequate adaptive behavior, it should be immediately reinforced. Homework was to apply this reaction model and identify the barriers found when applying it. Then, they were to keep practicing the exercises and skills they had been training in throughout the protocol, especially considering their actions in the direction of values and full attention exercises. Session 4 The purpose of the last session was to provide the parents with some strategies for managing their children's behavior and emotional problems. We reviewed the actions proposed in "the garden" exercise and valued the importance of continuing to progress in actions for achieving goals even though "the forest is getting dark". The "Parenting tree" metaphor, which makes an analogy between each part of the tree and aspects of parenting, was introduced. The roots, which give the tree sustenance and sustainability, represent parental values and family dynamics. Emotional competencies are represented as the trunk, which provides a structure and support for the branches of the tree, which represent educational styles and patterns. These points were worked on up to this session in the program. In this last session, concrete educational patterns and styles with flexible positive parenting were worked on to form the tree's canopy. Based on the "Connect and Shape" schema presented in the previous session, the difficulties found during the week of their application were discussed. At this time, all the acceptance, perspective-taking, and mindfulness skills learned in the protocol need to be put into practice to carry out this schema. Options for applying it suitably were given with examples. Different behavioral strategies that could be useful for managing behavior problems were added to it. Specifically, the following behavior modification techniques were practiced: models and modeling, identification of reinforcers, positive and negative reinforcement, control of antecedent stimuli, differential reinforcement, Premack principle, extinction, overcorrection, and timeout. Other educational patterns, such as emotional validation of the children, setting rules and limits, giving orders, and managing information were also practiced. The session ended by urging the families to keep working on the "Garden" exercise and applying the program skills. Treatment Outcomes and Follow-Up David's mother's progress in treatment was positive. Figure 1 shows the mother's mood and coping progress over the course of the intervention. Mood process outcomes showed an improvement at the end of the sessions from the second one. This increase was especially pronounced in the last session, in which we found the lowest level of mood in the pre-session test. Furthermore, we observed how mood was lower at the beginning of each session (more sadness) and it always improved at the end. Regarding perception of coping, we found maintenance in the two first sessions. Like mood, in sessions three and four we observed the lowest levels of coping at the beginning of each session, which increased at the end to a high level of coping. The largest difference was found in the last session. Regarding valued actions (assessed at the start of the sessions), we found a decrease in scores throughout the sessions. It is possible that there is a relationship between these three variables. At follow-up, valued actions score increased to a high level. Table 2 shows scores assessed with the instruments described above. We observed an improvement between pre-and post-test score in all variables, except for an aware response style, parenting stressors, and satisfaction with life. Following Jacobson and Truax, we found significant clinical changes in total score for emotion regulation skills (DERS total score), emotional acceptance, access to emotion regulation strategies, and baby's rewards. At the end of the intervention, the mother considered that she should continue improving. She specifically noted, "when he misbehaves, I would like not to be so negative, because I get very sad". She also noted some strategies to regulate herself, such as "to breathe and think at this moment how much I love him" and "I try not to think about the harm he does to me and my family". Table 2. Pre, post, and follow-up scores on the mother. Variable Pre Post Follow-Up Note: * clinically significant change improvement; ** clinically significant change recovery. Regarding satisfaction with the intervention we found a high score. On the other hand, protocol exercises and contents of the clinical protocol were rated as very useful, satisfactory, and it seemed quite easy to carry out. A follow-up was conducted 3 months after treatment. We found improvements in all variables evaluated except in active response style. These changes are clinically significant in parental psychological flexibility, an open response style, emotion regulation skill (DERS total score), achievement of goals in distress situations, access to emotion regulation strategies, general parenting stress, baby's rewards, and parental stressors. At follow-up, the mother noted that to regulate herself, she "thinks of the good times with him". As for David's improvements measured with SDQ, we found that the mother perceived a clinically significant change in problems with peers. She also perceived a decrease in emotional symptoms, which was the biggest problem that she scored at the beginning of the intervention. To evaluate David's emotional well-being, the self-report version of the SDQ was applied. All scores of the SDQ were found in a normal range. Scores were lower for problems with peers, emotional symptoms, and behavioral problems. Prosocial behavior scored high. On the other hand, we found clinically significant improvements in experiential avoidance, cognitive fusion, and value-directed actions, which could be interpreted as an increase in psychological flexibility (Table 3). Note: * clinically significant change improvement; ** clinically significant change recovery. SDQ scores were not taken at pre-test. Discussion This article presented a family intervention employing contextual therapies, mainly Acceptance and Commitment Therapy (ACT), to promote psychological flexibility skills and emotion regulation of parents through a case study of a mother and son with behavior problems. The results showed improvement in parental psychological flexibility, emotion regulation, and parental stress. The study illustrates the application of various strategies for strengthening acceptance of private events that can appear while managing one's children's emotional and behavior problems. Several different exercises were used to promote perspective-taking (or defusion) to make space for this acceptance. One of the main problems that David's mother had was cognitive fusion with her thoughts. Thoughts such as: "My son inherited his problem from his grandfather", "All this makes us suffer as a family", or "I am afraid that he'll end up with a personality problem like my father", along with all the emotional burden involved, were lived as if they were real here and now, and furthermore maintained the coherence of a dysfunctional interaction between mother and son, leading to coercive responses in impulsive reactions. Cognitive fusion in parenting can lead to dysfunctional reactions. Most of these reactions can be explained by functional analysis as a pattern of experiential avoidance of these private events which are maintained by short-term negative reinforcement. Rumination about parenting is also related to higher stress, which emotional awareness and acceptance skills modulate. The emotional distancing exercises may have promoted psychological flexibility and an open disposition to distressful experiences, reducing avoidance and parental stress. Similarly, Ascanio-Velasco and Ferro Garca found improvements in the level of stress in a family whose son had behavior problems after applying Parent and Child Interaction Therapy (PCIT) and ACT defusion and valuing elements. There was also a context of verbal regulation based on judgements of her son's good/bad behavior. This led to a diversity of emotional invalidation reactions in David that led to developing similar regulation patterns in him, for example constant rumination about "everything is shit" or "what a shitty life". This rumination pattern could be one of the factors involved in David's aggressive and avoidance behaviors. At the end of the intervention with the mother, a reduction in experiential avoidance, more acceptance, and score within normative ranges on self-perceived behavior problems were achieved. Nevertheless, the mother still thought her son had behavior problems. The clinical protocol applied included mindfulness exercises for promoting full attention, both in private events and interactions in family relations. These skills cannot be considered disconnected from those mentioned above. Mindfulness to experience without judging and with a disposition to openness involves exposure that gradually decreases the emotional reactivity. It should also be borne in mind that the reactions to these thoughts are mostly maintained by negative reinforcement, since they continue to palliate in some way the immediate aversive consequences one feels in a certain context, not only behavior (observable), but also by cognitive emotional avoidance processes (unobservable behavior). As in the case illustrated, previous studies have shown that intervention for parents with children with problem behavior employing mindfulness strategies have improved stress levels. Finally, there were significant improvements in the mother's emotion regulation skills, especially in emotional acceptance, the use of strategies to achieve objectives, and access to emotion regulation strategies in distressful situations. The strategies included are based on emotional validation of the behavior and emotional responses of children and on improvement of emotional awareness using Dialectical Behavioral Therapy (DBT) exercises and strategies for strengthening full awareness and emotional acceptance. In this case, David's mother referred to several occasions when she had learned to use her "wise mind", and even made the gesture of taking a step back to remind herself to take perspective. The strategies employed in DBT have already been explored in populations without borderline personality disorder as effective in promoting emotion regulation. Its effectiveness has been explored in some cases of mothers with emotion regulation problems where improvements were found in parenting, in emotion regulation skills, and in stress levels. Similar results have been found in parents with children with behavior problems. These results are comparable with those found in this study, in which inclusion of emotion regulation strategies based on acceptance, mindfulness, and defusion achieved similar results. In general, all the aspects of flexibility and emotion regulation were framed in a context of values. This makes sense of and motivates the acceptance-based change. The original creative hopelessness processes serve as the basis for generating the motivation to change. From there on, targets and goals are posed from more specific to more abstract terms and are present in the background of the change in motivated behavior in the direction of values. Sometimes, the need for change is motivated by the perception of affection in these vital areas. Specifically, in the case illustrated, the distress associated with "the family", as a socially constructed value, was given by the problems in family dynamics, which from the mother's point of view were caused by David. Another aspect worth mentioning found in the process measurements is the relationship observed at the beginning of the sessions between actions in the direction of values during the week, and the mood and perceived ability to cope. Thus, the sessions in which there were less achievement of actions coincided with lower mood and coping. This study had some limitations. In the first place, the intervention was performed only with the mother, which led us to reflect on the difficulties that would come up in applying these interventions with involvement of both parents, which would be extremely enriching. In this sense, it is a future line that both parents are involved in the intervention. It should be noted that although this study presents the results as a single case, the intervention was performed in a small group, so the results should be considered with this format in mind. Furthermore, the measures employed were mostly self-reported. We tried to palliate this limitation by including several informants and a starting interview. Aside from this, although process measurements were included, this could be improved with ecological momentary assessment, as well as observational records (both observable and verbal behavior) could be included to assess changes during the therapeutic interaction. Due to design limitations, it was not possible to calculate the effect size; however, to compensate for this limitation, the clinically significant change analysis method was used. Likewise, this study shows an application to a specific disorder, but it would be beneficial to prove its effects on other disorders. In conclusion, the intervention in this case study showed positive results in improving parental psychological flexibility skills, emotion regulation, and the mother's stress, both at post-test and follow-up. We also observed improvement in David's psychological flexibility, with less experiential avoidance and cognitive fusion and more acceptance and willingness to action. These findings suggest the benefits of applying these techniques in family intervention and encourage continuing to explore what each of the factors and components of the protocol contribute. Conclusions Clinical Implications This study presents a series of exercises and metaphors which may be applied and adapted to family intervention with third-wave therapies, mainly ACT. The intervention mainly considered aspects related to emotion regulation and flexibility from a perspective of acceptance. Thus, we did not pursue control or change in emotion, but attempted to change how they interacted with these emotions. The use of emotion regulation strategies directed at modifying or changing emotions is common in psychological problems, but may provide responses of emotional invalidation, both in the client and in others (in this case, the children). Work on experiential acceptance of emotions and thoughts that arise during parenting or management of behavior problems is therefore of special relevance. Experiential acceptance makes sense if the intervention is framed within a context of values which decide, within the variability of the behavior, what actions will take one nearer to a life with sense in one's personal values. It should also be emphasized that the use of metaphors and exercises must not be applied indiscriminately following the protocol word for word, but should be presented in coordination with both observable and verbal clinically relevant behaviors. Similarly, the metaphors and exercises should be directed at strengthening various skills at the same time (acceptance, perspective-taking, full attention), so they should be connected to each other. For example, the exercise on full attention to emotions can also promote acceptance of emotions at the same time. Functional analysis of behavior is also present throughout the clinical protocol, both in the son's behavior as reported by the mother and of the mother herself in her in-session and out-of-session reactions. Funding: This work is supported by the Spanish Ministry of Science and Innovation (Project reference/AEI/10.13039/501100011033) awarded to I.G. The present study was carried out thanks to a postdoctoral grant of the "Plan Propio de Investigacion" of the University of Almeria, from which the first author is a beneficiary. Institutional Review Board Statement: The study was conducted according to the guidelines of the Declaration of Helsinki and approved by the Institutional Ethics Committee of Andalusian Health Service's Almeria Research Committee (protocol code PI-REFLEX-ESFA-19, approved: 2470672020). This case study is part of a clinical trial registered with ClinicalTrals.gov (Identifier: NCT04267523). Informed Consent Statement: Written informed consent was obtained from the patient(s) to publish this paper. Data Availability Statement: The data presented in this study are available on request from the corresponding author. Acknowledgments: The researchers would like to thank the family involved in this case study, as well as the clinical psychologists who provided access to the case for intervention. Conflicts of Interest: The authors declare no conflict of interest. The funders had no role in the design of the study; in the collection, analyses, or interpretation of data; in the writing of the manuscript or in the decision to publish the results. Table A1. Example of a clinical protocol dialogue with the mother. T: Then there's this thought of "he's doing it to hurt me" "this is all coming from his grandfather" and... M: And then I feel that everything turns around and I answer. T: Who is having that thought at that moment? M: Me. T: So, can you make a choice to do one or the other? M: I don't know. T: Think for a moment what you could have done in that moment if you used your wise mind. Think about what has stopped you from following your wise mind, from following the path of your forest. M: Yes, I can step back and pay attention to how I feel... T: If you make space for your thoughts and emotions, if you let them be there for a while, we may not necessarily have to respond as if they were there. So, which direction would you go? M: That would bring me closer to my goals. Note: M: mother, T: Therapist.
Technical grade but not recrystallized alpha-naphthylthiourea potentiates superoxide release by rat neutrophils stimulated in vitro by phorbol myristate acetate. alpha-Naphthylthiourea (ANTU) causes pulmonary edema and pleural effusion in rats. It has been suggested that ANTU pneumotoxicity may be mediated by blood neutrophils (PMNs) via the release of reactive oxygen species. Accordingly, we tested the effect of technical grade ANTU (tANTU) on the ability of rat peritoneal PMNs to release superoxide (O2-). tANTU did not itself stimulate O2- production by PMNs, but it increased the O2- released in response to PMN stimulation by phorbol myristate acetate (PMA). This effect was dependent upon the amount of tANTU added. In PMNs activated in vitro by a submaximal PMA stimulus, addition of 20 micrograms/ml tANTU doubled superoxide release. When tANTU was recrystallized from ethanol, the purified ANTU was not effective in potentiating the effect of PMA on PMNs. This suggests that an impurity in technical grade ANTU is capable of increasing O2- release by stimulated PMNs. tANTU and recrystallized ANTU caused similar pneumotoxicity in rats in vivo, suggesting that the unidentified impurity does not markedly influence the biologic effects of ANTU.
/// Returns true if this is a valid pixel value. /// /// # Examples /// /// ``` /// use riscan_pro::CameraCalibration; /// let camera_calibration = CameraCalibration::from_project_path("data/project.RiSCAN") /// .unwrap() /// .pop() /// .unwrap(); /// // The camera calibration is 1024x768 /// assert!(camera_calibration.is_valid_pixel(0., 0.)); /// assert!(!camera_calibration.is_valid_pixel(1024., 0.)); /// assert!(!camera_calibration.is_valid_pixel(0., 768.)); /// ``` pub fn is_valid_pixel<T: Into<f64>>(&self, u: T, v: T) -> bool { let u = u.into(); let v = v.into(); u >= 0. && v >= 0. && u < self.width as f64 && v < self.height as f64 }
The Washington Wizards will begin training camp in about two weeks. While they have 15 players under guaranteed deals, the most allowed by the NBA, Ernie Grunfeld and the rest of his staff will continue inviting players to camp. Recently, both Ish Smith and Toure’ Murry agreed to join the Wizards for camp later this month. Surprisingly, the team hasn’t had an issue with getting players to accept their camp invitations. Since the team’s roster is full, the players that accept invites will likely audition for other clubs throughout the process. Unless the Washington Wizards could find a trade or waive a player, the guys that will join them for camp don’t have much of a chance to make the final roster. Today, Yahoo! Sports’ Shams Charania reported that another veteran will join the team for camp. Josh Harrellson, John Wall‘s former teammate at Kentucky, will be in the nation’s capital. Free agent forward Josh Harrellson has agreed to a non-guaranteed deal with the Washington Wizards, league source tells Yahoo Sports. — Shams Charania (@ShamsCharania) September 15, 2015 The Washington Wizards loaded up on wing players this summer and failed to replace Kevin Seraphin in the process. As our David Statman put it, the Wizards’ fatal flaw this upcoming season could be their lack of front court depth. Harrellson isn’t a bruising big man like Nene or Marcin Gortat, but he is solid fundamentally and he does shoot the ball well from the perimeter. Coming out of Kentucky in 2011, Harrellson wasn’t a coveted star like most of his teammates. The 6’10” forward/center had cups of coffee with the New York Knicks, Miami Heat and Detroit Pistons. His per game stats won’t jump off the screen, but in 32 games with the Pistons this past season, Harrellson shot nearly 39 percent from three. Randy Wittman will play more small-ball this upcoming season, and while Harrellson isn’t a prototypical stretch four, he can space the floor. At this point, I’m not sure that having DeJuan Blair over Harrellson on the roster would be much of an upgrade, especially since the latter can contribute on the offensive end. Harrellson, who’s nicknamed Jorts (the guy was born to be a Wizard, really), will probably rock an NBA uniform this upcoming season. The Wizards don’t have a roster spot open, but if he plays well, they could end up dumping someone like Blair. Washington will miss Seraphin’s scoring and Harrellson could potentially give them a spark off the bench, especially since he can knock down the outside shot. He’s not a great defensively player, but his shooting might make him a solid fourth big on the bench. Welcome to D.C., Jorts.
STUDY OF THE INFLUENCE OF DEFOCUSED LASER MARKING PROCESS BY MELTING ON SAMPLES OF STEEL The studies relate to the process of laser marking by melting on the samples of structural steel. The zone of Raleigh for fiber laser was determined. The theoretical dependences of the diameter of the working spot from defocusing and diameter of the radiation falling on the lens were received. Experiments were realized with 50G structural steel. The dependence of contrast of marking from defocusing for two power densities was determined. Working intervals were determined for studied magnitudes for visual perception of the marking.
MILLIMETER/SUBMILLIMETER SPECTROSCOPY OF TiO (X3r): THE RARE TITANIUM ISOTOPOLOGUES Pure rotational spectra of the rare isotopologues of titanium oxide, 46TiO, 47TiO, 49TiO, and 50TiO, have been recorded using a combination of Fourier transform millimeter-wave (FTmmW) and millimeter/submillimeter direct absorption techniques in the frequency range 62538 GHz. This study is the first complete spectroscopic characterization of these species in their X3r ground electronic states. The isotopologues were created by the reaction of N2O or O2 and titanium vapor, produced either by laser ablation or in a Broida-type oven, and observed in the natural Ti isotopic abundances. Between 10 and 11 rotational transitions J + 1 J were measured for each species, typically in all 3 spinorbit ladders = 1, 2, and 3. For 47TiO and 49TiO, hyperfine structure was resolved, originating from the titanium-47 and titanium-49 nuclear spins of I = 5/2 and 7/2, respectively. For the = 1 and 3 components, the hyperfine structure was found to follow a classic Land pattern, while that for = 2 appeared to be perturbed, likely a result of mixing with the nearby isoconfigurational a1 state. The spectra were analyzed with a case (a) Hamiltonian, and rotational, spinorbit, and spinspin parameters were determined for each species, as well as magnetic hyperfine and electric quadrupole constants for the two molecules with nuclear spins. The most abundant species, 48TiO, has been detected in circumstellar envelopes. These measurements will enable other titanium isotopologues to be studied at millimeter wavelengths, providing Ti isotope ratios that can test models of nucleosynthesis.
RAWSTORY — Rep. Robert Wexler (D-FL) says he’s hatched a plan that will secure health care for children, help to restore America’s reputation around the world, and empower the the Democratic party to rediscover the courage of its convictions. He calls it “impeachment hearings.” Appearing in his home state for a meeting of the Palm Beach County Democratic Executive Committee last week, Wexler told the crowd that if Congress were to hold hearings on the impeachment of Vice President Dick Cheney, the move would advance a wide array of Democratic legislative priorities and even help a more “popular” United States head off foreign policy crises. The remarks were first reported by the Palm Beach Post’s George Bennett. “The way we pass stem-cell research, the way we get implemented a children’s health care plan, the way we get higher CAFE [corporate average fuel economy] standards to bring our energy debacle into a better condition for generations to come is to have impeachment hearings,” Wexler said, appearing to nearly run out breath at one point during his speech. “Because that’ll get the president’s eye. That’ll get the vice president’s eye. That for the first time will show that the Democratic majority is here, and that in fact we have the courage of our convictions, and that we’re not bound to be tied by conventional wisdom.” Wexler said that impeachment hearings weren’t just an option available to Congress, but a requirement. “This administration has abused its power in office…and it is the obligation — not discretionary — but it is the obligation of this Congress to investigate,” he said. “And that’s what I and some of my colleagues are beginning to call for.” Later, Wexler suggested the US was sorely in need of popularity boost in the world community. Continue Reading
<gh_stars>1-10 from django.urls import path from ap.apps.events import views app_name = 'events' urlpatterns = [ path( 'search/', views.search, name="search"), path( '<int:event_id>/<str:event_slug>/organize/', views.organize_event, name="organize_event"), path( '<int:event_id>/<str:event_slug>/', views.detail, name="detail"), path( 'organize/', views.index, {'organize': True}, name="organizers_index" ), path( '<str:tense>/', views.index, name="index"), path( '', views.index, name="index"), ]
/** An ASTVisitor that constructs a list of ASTNodes that start / end per line * * <p>Which we'll use later on when attributing comments to specific ASTNodes * to save having to look ahead in the AST tree * * <p>Will I add comments into this list ? Will I indeed. */ public class AstToLineVisitor extends ASTVisitor { Logger logger = Logger.getLogger(AstToLineVisitor.class); Map<Integer, List<ASTNode>> startLineNumberAstsMap = new LinkedHashMap<>(); // order-preserving Map<Integer, List<ASTNode>> endLineNumberAstsMap = new LinkedHashMap<>(); List<CommentText> comments; CompilationUnit cu; String src; public AstToLineVisitor(CompilationUnit cu, String src, List<CommentText> comments) { super(true); this.cu = cu; this.comments = comments; this.src = src; } public Map<Integer, List<ASTNode>> getStartLineNumberAstsMap() { return startLineNumberAstsMap; } public Map<Integer, List<ASTNode>> getEndLineNumberAstsMap() { return endLineNumberAstsMap; } public boolean preVisit2(ASTNode node) { if (node instanceof MethodDeclaration || node instanceof CatchClause || node instanceof Statement || node instanceof Expression || // inside ExpressionStatements node instanceof VariableDeclaration || node instanceof TypeDeclaration || node instanceof AnonymousClassDeclaration ) { int lineNumber = cu.getLineNumber(node.getStartPosition()); // int columnNumber = cu.getColumnNumber(node.getStartPosition()); List<ASTNode> lineList = startLineNumberAstsMap.get(lineNumber); if (lineList == null) { lineList = new ArrayList<>(); startLineNumberAstsMap.put(lineNumber, lineList); } lineList.add(node); } return true; } public void postVisit(ASTNode node) { if (node instanceof MethodDeclaration || node instanceof CatchClause || node instanceof Statement || node instanceof Expression || // inside ExpressionStatements node instanceof VariableDeclaration || node instanceof TypeDeclaration || node instanceof AnonymousClassDeclaration ) { int lineNumber = cu.getLineNumber(node.getStartPosition() + node.getLength()); // int columnNumber = cu.getColumnNumber(node.getStartPosition()); List<ASTNode> lineList = endLineNumberAstsMap.get(lineNumber); if (lineList == null) { lineList = new ArrayList<>(); endLineNumberAstsMap.put(lineNumber, lineList); } lineList.add(node); } } }
Criteria of 'Nominal' and 'Real' Convergence of Managerial Abilities in the Enlarged Europe: Cohesion or Diversity? For the Economic and Monetary Union, five nominal convergence criteria have to be accomplished by candidate and member states; the real convergence - the catching-up process - is also an important subject of debates. Could we talk about similar criteria for the higher education system? In the paper we analyze the opinions concerning managerial abilities required or desired and try to identify possible convergence solutions.
It's the time of year for local college and high school graduates to take that big step into the future. Here's a list of dates and times for area graduations. All are held on school property unless otherwise noted. South Walton High School, 7 p.m. Silver Sands School, 6:30 p.m. Walton High School, 7 p.m. Freeport High School, 7 p.m. Radford M. Locklin Technical Center, 6 p.m., Milton High School, 5445 Stewart St. Santa Rosa High School, 7 p.m., Milton High School, 5445 Stewart St. Niceville High School, 7 p.m. Gulf Breeze High School, 11 a.m., Pensacola Bay Center, 201 E. Gregory St. Pace High School, 11 a.m., Pensacola Bay Center, 201 E. Gregory St. Navarre High School, 6 p.m., Pensacola Bay Center, 201 E. Gregory St. Laurel Hill School, 6 p.m. Fort Walton Beach High School, 7:30 p.m. Choctawhatchee High School, 7:30 p.m. Crestview High School, 8 p.m. Milton High School, 8 p.m. Santa Rosa Blended Academy, 5 p.m., Milton High School, 5445 Stewart St. Central High School, 6 p.m.
import {InjectionToken} from '@angular/core'; export let APP_CONFIG = new InjectionToken('app.config'); export const AppConfig = { routes: { shopping: 'shopping', error404: '404' }, endpoints: { productsBaseUrl: 'https://api.shutterstock.com', productsGetPath: '/v2/images/search' }, snackBarDuration: 3000, repositoryURL: 'https://github.com/affilnost/angular5-example-shopping-app', defultSHContent: '[{"id":"257450194","name":"Chicken salad with leaf vegetables and cherry toma...",' + '"imgUrl":"https://image.shutterstock.com/display_pic_with_logo/236329/257450194/stock-photo-chicken-salad' + '-with-leaf-vegetables-and-cherry-tomatoes-257450194.jpg","description":"Chicken salad with leaf vegetables' + ' and cherry tomatoes"},{"id":"548526682","name":"Easter cake on a white background","imgUrl":"https://ima' + 'ge.shutterstock.com/display_pic_with_logo/2675854/548526682/stock-photo-easter-cake-on-a-white-background' + '-548526682.jpg","description":"Easter cake on a white background"},{"id":"591617762","name":"Chocolate egg' + ' exploded","imgUrl":"https://image.shutterstock.com/display_pic_with_logo/685426/591617762/stock-photo-cho' + 'colate-egg-exploded-591617762.jpg","description":"Chocolate egg exploded"},{"id":"525754399","name":"Glass' + ' of milk isolated on white","imgUrl":"https://image.shutterstock.com/display_pic_with_logo/371512/52575439' + '9/stock-photo-glass-of-milk-isolated-on-white-525754399.jpg","description":"Glass of milk isolated on whi' + 'te"},{"id":"629596088","name":"Bread and Bakery Products Isolated on White. Diffe...","imgUrl":"https://i' + 'mage.shutterstock.com/display_pic_with_logo/3011495/629596088/stock-photo-bread-and-bakery-products-isola' + 'ted-on-white-different-types-of-bread-sesame-bun-baguette-baked-629596088.jpg","description":"Bread and Ba' + 'kery Products Isolated on White. Different types of bread: sesame bun, baguette, baked rolls, rustic brea' + 'd, round bun, sesame bun."}]' };
The modern supply chain is a cornerstone of enterprise e-business. Manufacturers have spent countless millions on technology to support inventory practices that are unqualified successes -- until the attacks on Sept. 11. In addition to the terrible loss of life and property destruction, the Sept. 11 terrorist attacks wreaked havoc with the nation's supply chains. Authorities responded to the emergency by implementing a broad array of security measures that grounded air cargo planes, prevented ships from docking at seaports, and stalled trucks at border crossings. Retailers couldn't get needed merchandise, and manufacturers suffered parts shortages. No one has measured the attacks' cumulative financial impact on supply chains, but the cost will certainly be measured in the millions. The modern supply chain is a cornerstone of enterprise e-business. Manufacturers have spent countless millions on information technology that supports just-in-time (JIT) inventory practices to improve efficiency and reduce costs. JIT is credited with the consistent improvement in the U.S. Census Bureau's inventory-to-sales ratio--a key metric for measuring manufacturing efficiency--over the last 11 years. JIT is an unqualified success, helping manufacturers become more competitive and reducing volatility in the economy. Companies shouldn't walk away from JIT inventory management, but they should make adjustments. "People still want their inventories as low as possible," says O'Marah. "But the word 'possible' has a different meaning now." Ford is not abandoning its JIT system, on which it has spent millions of dollars, but will begin stockpiling engines and other key parts at some U.S. plant locations to prepare for future transportation disruptions. Companies typically maintain a certain amount of extra inventory called "safety stock" to compensate for unforeseen shortages. However, most companies allocate only enough safety stock to handle relatively small problems such as a truck blowing out a tire or a defective parts lot. It's very difficult to set limits on safety stocks for a random event like the Sept. 11 attacks. Bruce Tempkin of Forrester Research describes the problem: "The dilemma with increasing safety stocks is that any increase will lead to too much cost all of the time but the increased stock is still unlikely to be enough to cover you in a real emergency." Companies need to adopt a more thoughtful approach to inventory increases rather than a knee-jerk reaction that blindly increases safety stocks. Dwight Klappich of Meta Group says that "going back to warehouses full of inventory is not the right answer. Companies currently set safety stocks like a shot in the dark. They need to think a lot more about how they approach it." To accomplish this, IT managers should consider specialized inventory-optimization software from vendors such as Baxter Planning Systems, Gain Systems, Optiant, Oracle, Rapt, and SmartOps. These vendors help with massive inventory-planning problems and can perform the necessary mathematics to evaluate and react to event probabilities such as changes in weather and other unforeseen circumstances. Companies can also prepare for unanticipated supply-chain disruptions by using e-sourcing programs to identify alternative suppliers. You may not be able to get a widget from Mexico but you can still get one from a supplier in Indiana. Companies should use logistics software or suppliers that let them identify alternate delivery routes. This might let you reroute materials or merchandise to an alternative plant or distribution center rather than sending it off to an idle location. One thing is clear: Sept. 11 is a big wake-up call for supply-chain managers and e-business champions to re-examine their IT systems for weaknesses and do a better job of preparing for future disasters.
Platelet-rich plasma promotes recruitment of macrophages in the process of tendon healing Introduction Researchers have investigated the use of platelet-rich plasma (PRP) therapy. However, the mechanisms through which PRP affects tissue repair remain unclear. We hypothesize that PRP promotes tissue repair through not only via direct manner on the local cells but also via indirect manner that encourage the recruitment of reparative cells such as macrophages (MPs), and it depends on the quality of PRP including the concentration of leukocytes. The aim of this study is to elucidate the actions of the MPs in the mechanisms of PRP on tissue repair processes. Methods Leukocyte-rich (LR) PRP and leukocyte-poor (LP) PRP were prepared from 12-week-old C57BL6 mice. Full-thickness defects were created in central third of patellar tendons of 12-week-old C57BL/6 mice for histologic analysis (n = 36) and 12-week-old B6.129P-Cx3cr1tm1Litt/J mice for flow cytometry analysis (n = 108). B6.129P-Cx3cr1tm1Litt/J mouse is GFP-positive only in the MP-linage cells thus MPs recruited to the repair tissue can be distinguished whether it had originated from administrated PRP or recruited from host mouse. Mice were treated either with LR-PRP, LP-PRP, or without PRP (control group). Histological analyses were performed to evaluate the tendon healing using Bonar score as semi-quantitative histological scoring system. Flow cytometric analyses were performed to count the number of GFP-positive cells around repaired patellar tendon. In addition, the ratio of pro-inflammatory MPs (M1)/anti-inflammatory MPs (M2) were analyzed in those GFP-positive cells. The statistical analysis was performed using GraphPad Prism ver6. P values < 0.05 were considered statistically significant. Results In LR-PRP and LP-PRP groups, all variables in Bonar score such as cell morphology, cellularity, vascularity, and collagen arrangement were significantly improved in comparison with control group, indicating that both PRPs promote tendon hearing. LP-PRP promoted the tendon healing significantly faster than that of LR-PRP on postoperative day 28 (P < 0.001). LR-PRP enhanced angiogenesis (vascularity: P < 0.001), while LP-PRP improved the collagen arrangement on postoperative day 28 (collagen arrangement: P < 0.01). In other variables such as cell morphology and cellularity score, there were no significant differences between LR-PRP and LP-PRP groups in any time points. Flow cytometric findings showed that recruitment of GFP-positive MPs in the LR and LP-PRP groups were significantly increased from postoperative day 4 compared with control group without PRP treatment (P < 0.001). The majority of GFP-positive MPs were M1 at the initiation of tendon healing phase, and M2 were gradually increased from postoperative day 4. The number of M1 was significantly high both in the LP- and LR-PRP groups (day 4 and 7, p < 0.001), but the number of M2 was high only in the LP-PRP group (day 7 and 14, P < 0.05) when it compared with control group. The M1/M2 ratio on postoperative day 7 was significantly lower in the LP-PRP group than those in the control group (P < 0.05). Conclusions This study demonstrated that PRP enhanced the tendon healing and promoted the recruitment of MPs to the injured tissue. The subtypes of MPs were different depends on the types of PRPs, suggesting that leukocytes in PRP influence the effect of PRP therapy. Introduction Platelet-rich plasma (PRP) is an autologous blood that concentrates platelets and contains diverse growth factors and cytokines. PRP therapy is a promising as that is simple, safe, low cost, and minimally invasive and could be used to promote the tissue repair process . PRP has recently been used as a therapeutic material in many fields. As the use of PRP has increased in the clinic, the number of clinical and basic studies supporting the efficacy of PRP therapy has also increased . However, some studies have shown less favorable results, and evidence supporting the use of PRP in the clinical setting remains insufficient. Moreover, researchers have proposed several problems related to the use of PRP therapy. First, although some studies have supported the efficacy of PRP in the clinical setting during the tissue repair process , the molecular mechanisms through which PRP exerts these effects are still unclear. In a previous study, administration of PRP significantly increased angiogenesis during the early phase of the tendon repair process. However, the cells participating in the early phase of the PRP-dependent tissue repair process have not been identified. Second, although some classification systems based on leukocyte numbers, leukocyte activation status, and platelet concentration have been proposed, few studies have been conducted to evaluate the effects of the quality of PRP on the tissue repair process. Therefore, the effects of differences in the quality of PRP remain unclear. Generally, macrophages (MPs) are thought to play important roles in the early phase of the tissue repair process. MPs are unique effector cells in innate immunity and play critical roles in tissue repair . In addition, MPs comprise two phenotypically distinct subtypes, i.e., pro-inflammatory MPs (M1), which promote the inflammation phase, and anti-inflammatory MPs (M2), which promote the tissue regeneration phase. The timely shift from M1 to M2 is thought to be crucial for tissue repair . In addition, there has been some discussion about whether the efficacy of the PRP is affected by the concentration and composition of leukocytes in the PRP, particularly regarding leukocyte-rich PRP (LR-PRP) versus leukocyte-poor PRP (LP-PRP). Indeed, our previous work showed that the leukocyte concentration and composition in the PRP influenced the expression of growth factors and cytokines. Additionally, these leukocytes may have positive effects, such as antimicrobial effects, or negative effects, such as excessive inflammation, via the release of catabolic cytokines. Some studies have also suggested that LR-PRP possesses both catabolic and anabolic effects, whereas LP-PRP exerts anabolic effects rather than catabolic effects in injured tissues. In contrast, some studies have suggested that LR-PRP and LP-PRP have similar safety profiles, and adverse reactions to PRP may not be directly related to leukocyte concentrations. Thus, further studies are needed to standardize the concentrations of leukocytes needed in optimal PRP, which may vary according to pathophysiology, and to elucidate the effects of molecular mechanisms on the quality of PRP. In this study, we hypothesized that the tissue repair mechanism of PRP may involve both direct and indirect effects, e.g., recruitment of reparative cells through blood flow, particularly MPs, depending on the quality of PRP. Accordingly, we aimed to elucidate the effects of MPs on the tissue repair process and to evaluate the influence of PRP quality on the activity of MPs. Ethics statement All experimental procedures and protocols in this study were approved by the Institutional Animal Care and Use Ethics Committee of Juntendo University (approval number 300200). Animals This study was a controlled laboratory study. In total, 58 female C57BL/6 mice (12 weeks old) and 108 female B6.129P-Cx3cr1 tm1Litt / J mice expressing green fluorescent protein (GFP) in MPs obtained from The Jackson Laboratory (Bar Harbor, ME, USA) were used in this study. The effects of MPs on injured patella tendons were investigated by flow cytometry analysis. Blood collection and PRP preparation LR-PRP and LP-PRP were prepared from whole blood (WB) of C57BL/6 donor mice (n 40) using the double spin technique. Approximately 1 mL WB was drawn via cardiac puncture into a micro tube containing EDTA-2Na as an anticoagulant (Microtainer; BD Biosciences, Bedford, MA, USA). After the first spin (220g, 10 min, 25 C), the upper layer, buffy coat, and the layer below the buffy coat were transferred to another tube for LR-PRP, and the upper layer and buffy coat were transferred to another tube using the original Tornado-N technique for LP-PRP ( Fig. 1). After the second spin (2400 g, 10 min, 25 C), the supernatant (platelet-poor plasma ) was removed, and approximately 100 mL PPP remained. The pellet from the bottom of each tube was resuspended in the remaining PPP to prepare LR-PRP and LP-PRP. LR-PRP and LP-PRP (50 mL each) was divided into another tube and cryopreserved at 80 C until application (Fig. 1). Hematological analysis The platelet, leukocyte, and erythrocyte concentrations and leukocyte compositions of whole-blood, LR-PRP, and LP-PRP samples were determined using an automated hematology analyzer (Poch-100iV Diff; Sysmex, Kobe, Japan) immediately after preparation. Surgical procedure and PRP application Twelve-week-old C57BL/6 mice and B6.129P-Cx3cr1 tm1Litt /J mice were anesthetized with 4% isoflurane, a longitudinal skin incision was made over the patellar tendon. Then, full-thickness defects were created in the central third of the patellar tendon using a microsurgery technique described by Dyment et al.. Microtweezers were slid under the tendon and spread to tension the tendon. The central third of the patellar tendon was cut away with micro scissors (Fig. 2B). The cryopreserved PRP prepared from C57BL/6 mice was thawed, 0.5 mM calcium chloride (Sigma Aldrich, St. Louis, MO, USA) was added, and the samples were incubated for 1 h at 37 C in a water bath to activate the PRP and form a gel ( Fig. 2A,C). For histological analysis, C57BL/6 mice treated with LP-PRP (n 12) or LR-PRP (n 12) on the patellar tendon defect were defined as the PRP groups, and without application of PRP were defined as the control group (n 12). For flow cytometry analysis, B6.129P-Cx3cr1 tm1Litt /J mice treated with PRP on the patellar tendon defect were defined as the LR-PRP (n 36) and LP-PRP groups (n 36), and B6.129P-Cx3cr1 tm1Litt /J mice without application of PRP were defined as the control group (n 36). After the end of the procedure, the skin was closed with a 5e0 nylon suture. Mice were allowed to be fully active after the operation. Histological analysis Histological analysis were performed on postoperative day 7, 14, 28, or 42 (n 3/time point/group) according to the method described by Kawamoto et al.. After euthanasia, hind limb were harvested an the femur and tibia were cut at midshaft. The samples were fixated with 4% paraformaldehyde (Nakarai Tesque, Kyoto, Japan) for 1h at 4 C. After fixation, the samples were cryoprotected with 30% sucrose (ATAGO, Tokyo, Japan) overnight at 4 C. After three times wash with 1x PBS, the samples were frozen in a cooled hexane (Nakarai Tesque, Kyoto, Japan), and then freeze embedded with carboxymethyl cellulose (CMC) gel (Leica microsystems, Wetzlar, Germany). Then, sagittal frozen sections (5 mm thickness) were made within the defect using a tungsten carbide blade. Each sample were stained with hematoxylin and eosin (H&E). Semiquantitative histological evaluation of tendon healing process was performed in accordance with Bonar score. The variables included in this scoring system were cell morphology, collagen arrangement, cellularity, and vascularity with higher grades indicating worse tendon structure (each factor; 0e3 points). Flow cytometry analysis B6.129P-Cx3cr1 tm1Litt /J mice from the three groups were sacrificed on days 1, 2, 4, 7, 14, or 28 after operation (n 6/time point/ group). CX3CR1-GFP mice were used to distinguish MPs derived from administrated PRP (GFP-negative) or recruited by host mice (GFP-positive). After euthanasia, the patellar tendons were harvested and dissociated using collagenase for 2 h. The solution was moved to Falcon round-bottom polypropylene tubes (Corning, NY, USA) for flow cytometry using a 100-mm nylon strainer. Fifty microliters of count beads (CountBright Absolute Counting Beads; Thermo Fisher Scientific, USA) and Fc blocking reagents were added to each tube, and tubes were centrifuged (180g, 5 min, 4 C). The supernatants were removed, and 80 mL of phosphate-buffered saline (PBS)/10% fetal calf serum (FCS) was added to each tube. Next, rat anti-mouse F4/80 APC antibodies (BioLegend, San Diego, CA, USA), rat anti-mouse CD11b Alexa Fluor 700 antibodies (BioLegend, San Diego, CA, USA) and rat anti-mouse Ly6C PerCP/Cy5.5 antibodies (BioLegend, San Diego, CA, USA) were added to each tube (volume: 10 mL). Tubes were then incubated on ice for 30 min and centrifuged (180g, 5 min, 4 C). The supernatants were removed, and 500 mL PBS/10% FCS 0.005% Hoechst was added. Compensation was performed on the BD LSRFORTESSA flow cytometer using BD FACSDiva software (BD Bioscience) at the beginning of each experiment. Data were analyzed using FlowJo software (FlowJo LLC, USA). Gating strategy was performed following exclusion of debris The Tornado-N technique for LR-PRP and LP-PRP preparation. The first spin was carried out at 220g for 10 min at 25 C, and the second spin was carried out at 2400g for 10 min at 25 C. After the first spin, the layer between the red layer (including neutrophils and erythrocytes) and the buffy coat (including platelets and a few lymphocytes) was shaken up carefully using a pipette. Fig. 2. Surgical procedure and PRP application. A) PRP gel. B) A full-thickness defect was created in the central third of the patellar tendon. C) PRP gel was applied to the patellar tendon defect. PT patellar tendon, TT tibia tuberosity. and cellular aggregates and live/dead discrimination. The positive populations were identified using unstained controls to determine the negative populations. The cells were plotted F4/80 and CD11b. We consider the positive populations as MPs. In the positive populations, the GFP-positive MPs were then distinguished from GFPnegative MPs. We counted absolute cell number of the GFPpositive MPs on each time points. Based on previous studies, characterizing Ly6C hi MPs as M1 and Ly6C lo MPs as M2 via flow cytometry, CX3CR1 hi Ly6C cells were considered as M1 and CX3CR1 low /Ly6C-cells as M2. The GFP-positive MPs were then analyzed by plotting Ly6C against CX3CR1. We performed absolute cell counts of M1 and M2 to analyze M1/M2 ratio on each time points. Statistical analysis All data were presented as means ± standard deviations (SDs). All analyses were performed using GraphPad Prism ver6.0 (GraphPad Software, Inc., La Jolla, CA, USA). P values of less than 0.05 were considered statistically significant. Histological findings Histological analysis showed that the invasion of inflammatory cells occurred at initiation phase of tendon healing and gradually regenerated the tendon structure (Fig. 4A). On the day 7, inflammatory cells were abundantly observed in the LR-PRP and LP-PRP groups compared with control group. With regard to the Bonar score, total Bonar score was significantly improved both in LP and LR-PRP group in comparison with those of control group (on postoperative day 14: P < 0.05, day 28: P < 0.01, day42: P < 0.001, Fig. 4B, and almost all of the variables of Bonar score significantly improved both in LR-PRP and LP-PRP groups in comparison with control group as well (cell morphology on postoperative day 28, 42: P < 0.01, cellularity on postoperative day 7, 14, 28, 42: P < 0.05, vascularity on postoperative day 7, 14, 28,42: P < 0.001, collagen arrangement on postoperative day 7, 14, 28, 42: P < 0.05, Fig. 4C). The tendon healing was significantly earlier in LP-PRP group than those of LR-PRP group on postoperative day 28 (total Bonar score, P < 0.001), and collagen arrangement was improved earlier in LP-PRP than LR-PRP group on day 28 (P < 0.01, Fig. 4C). The vascularity was significantly high in LR-PRP group on day 28 (P < 0.001). In other variables such as cell morphology and cellularity score, there were no significant differences between LR-PRP and LP-PRP groups in any time points. Flow cytometry findings At first, the F4/80 and CD11b positive cells in the repaired tendon tissue were gathered, then GFP-positive cells were counted as MPs recruited from host mouse not from PRPs (Fig. 5A). Flow cytometry analysis showed that the number of GFP-positive MPs around the patellar tendon defects in the LR-PRP and LP-PRP groups were gradually increased from postoperative day 1 and significantly increased on postoperative day 4 and 7 in comparison with the control group (day 4 (Fig. 5B). Next, the GFP-positive MPs were sorted with Ly6C and CX3CR1 antibody to analyze the absolute cell counts of M1 and M2 MPs recruited from host mice (Fig. 6A). The number of M1 in control group was highest on postoperative day 28, while those in the LR-PRP and LP-PRP groups were highest at day 4 and decreased with time (Fig. 6B) (Fig. 6B). Finally, the M1/M2 ratio was analyzed. M1/M2 ratio >1 means that there are relatively more M1 than M2 MPs. In control group, M1/M2 ratio was highest on postoperative day 14, while those in LP-and LR-PRP was highest on postoperative day 1 (Fig. 6C) PRP enhanced the recruitment of MPs but LP-PRP could lead more M2 phenotype that decrease inflammation and encourage tissue repair. Discussion The tissue repair process is traditionally divided into three sequential phases: inflammation, proliferation, and remodeling. Platelets are the first cells that are accumulated at an injured site and initiate the repair process by secreting various cytokines and growth factors. PRP has been used based on the hypothesis that cytokines and growth factors secreted by platelets will activate the tissue repair process by affecting the local cells at injured site. In addition, PRP has been known to enhance angiogenesis during early tendon repair. In this study, we revealed that PRP enhanced the recruitment of MPs from early phase of tendon repair and demonstrated that those cells were originated from not administrated PRP but from blood flow. This observation suggested that the cytokines and growth factors released from PRP would enhance the cell migration and invasion of MPs from immediately after the administration of PRP. This study demonstrated that this process is one of the mechanisms of PRPenhanced tissue repair system. MPs are essential for early-phase tissue repair. In addition, the balance between M1 and M2 is thought to be important for this process. M1 MPs are thought to promote the inflammation phase by producing cytokines/chemokines, such as CeC motif chemokine ligand 2, monocyte chemoattractant protein-1, inducible nitric oxide synthase, tumor necrosis factor-a, interleukin (IL)-12, IL-1b, and vascular endothelial growth factor. In contrast, M2 MPs promote the proliferation and remodeling phases by producing cytokines/chemokines, such as IL-4, IL-10, transforming growth factorb, arginase-1, insulin-like growth factor-1, and platelet-derived growth factor-b. In our data, both M1 and M2 in control group gradually increased with time and the peak of M1/M2 ratio was day 14 (Fig. 6). On the other hand, in the PRP groups, the peak was observed in early phase of tendon healing (M1: day 4, M2: day 7) and M1/M2 ratio was highest at the day after PRP administration (day1) both in LR-and LP-PRP. This observation suggests that PRP administration enhances the inflammation and initiate the tissue remodeling state. Therefore, PRPs would exert their effect especially in the degenerative tissue conditions with low or no blood supply as PRP enhances the recruitment of MPs via chemotaxis manner independent of blood flow. In this study, we demonstrated that local application of LR-PRP and LP-PRP to injured tissue promoted the recruitment of MPs derived from peripheral tissues and blood. Importantly, recruitment of reparative cells during the early phase is essential for inducing the normal cycle of the tissue repair process. Thus, local application of PRP could enhance the tissue repair process via not only direct mechanisms, such as inducing the proliferation of localized cells via growth factors within the PRP, but also indirect mechanisms, such as recruitment of reparative cells, particularly MPs, through peripheral tissue and blood flow (Fig. 7). Moreover, some reports have described the association between PRP and MPs subtypes. For example, Omar et al. suggested that PRP caused suppression of inflammation and induction of M2 MPs. Accordingly, we hypothesized that the activity of MPs may be influenced by PRP quality, particularly the concentration and composition of leukocytes. We demonstrated that LR-PRP mainly enhanced the effects of M1 MPs, whereas LP-PRP more strongly induced the activity of M2 MPs. Commonly, M1 MPs can be generated by stimulation with bacterial lipopolysaccharides (LPS) in combination with IFN-g. On the other hand, M2 MPs can be generated by various stimulation such as IL-4, IL-10 produced by Th2 lymphocyte. The biological basis for this may be in the relative level of inflammatory versus anti-inflammatory mediators present in LR-PRP and LP-PRP. Inflammatory mediators such as TNF-a, IL-6, and IFN-Y are increased significantly in the presence of LR-PRP, whereas injection of LP-PRP increases anti-inflammatory mediators such as IL-4 and IL-10. This would be affected by the composition and concentration of leukocytes, platelets, and erythrocytes in PRP. It is known that granulocytes and erythrocytes abundantly contained in LR-PRP secrete a lot of inflammatory mediators, while lymphocytes abundantly contained in LP-PRP secrete a lot of anti-inflammatory mediators as represented by Th2 lymphocytes. Also, These findings indicated that LR-PRP may cause a more pronounced inflammatory phase and that the acute infiltration and subsequent recruitment of inflammatory cells may stimulate the tissue repair process more rapidly. In contrast, LP-PRP may enhance the proliferation and remodeling phases more rapidly due to its strong potential to induce anabolic effects. Specifically, LR-PRP may need to be selected owing to its catabolic effects on the pathophysiology of degenerative changes in tissues, such as intractable tendinopathy. A recent meta-analyses of PRP in tendinopathy showed that LR-PRP was associated with strongly positive outcomes. In contrast, LP-PRP may have to be used in to exploit its anabolic effects, e.g., in osteoarthritis, tendon rupture, and pulled muscles. Accordingly, the optimal PRP may differ depending on the specific disease pathophysiology. In this study, we found that PRP promoted tendon repair through recruitment of MPs and that the leukocyte concentration and composition of PRP influenced the shift from M1 to M2 MPs. To the best of our knowledge, this is the first report describing these findings, and we expect that these results will contribute to elucidation of the mechanisms through which PRP therapy promotes the tissue repair process. There are some limitations to this study. First, we used allogeneic PRP in this study; we could not use autologous PRP. However, the inbred animals used in this study are thought to be nearly identical to each other. Second, the murine patellar tendon defect model used in this study does not truly replicate human chronic degenerative changes. Third, we didn't administrate saline or platelet-poor plasma on the defect of patellar tendon in control group, therefore, there is possibility that the effect of inducing macrophages in LR-PRP and LP-PRP groups would be caused by foreignebody reaction. Forth, we have not confirmed whether tendon healing with PRP therapy is inhibited by suppression of the actions of MPs during the early phase of the tissue healing process. Further studies are needed to address these issues. Conclusions PRP therapy promoted the recruitment of macrophages in the process of tendon healing, and the leukocyte concentration and composition of PRP influenced the balance between M1 and M2 MPs. Thus, these results suggested that the tissue repair mechanism of PRP may involve both direct and indirect effects, with the latter being related to recruitment of reparative cells from the blood in a PRP quality-dependent manner. For further improvement of the efficacy of PRP therapy according to the specific pathophysiology of the disease, additional studies are needed to elucidate the mechanisms through which PRP quality affects tissue repair. Declaration of competing interest The authors declare no conflict of interest.
Respiratory extracorporeal membrane oxygenation and central-lineassociated bloodstream infection: Experience at a tertiary-care center during the coronavirus disease 2019 (COVID-19) pandemic continue transmission-based precautions, what time point is specified? a. 10 days b. 1130 days c. > 30 days 9. What factors influence the decision to remove patients with COVID-19 from transmission-based precautions? a. RNA test availability b. Illness severity c. Improvement in symptoms d. Asymptomatic vs symptomatic e. Length of time from initial positive test f. Patient characteristics (eg, immunocompromised) g. Discharge to home h. Discharge to congregate living facility (eg, nursing home, jail, shelter) i. Other (specify): (Free text) 10. Additional comments about discontinuation of transmissionbased precautions for patients with COVID-19? (Free text) Methods This retrospective study was conducted from December 2013 to the end of February 2021 in 28-bed intensive care units at Tokyo Metropolitan Tama Medical Center, a 790-bed, public, tertiarycare center in Tokyo, Japan. The study center began respiratory ECMO placement in December 2013. The center has been registered with the extracorporeal life support organization (ELSO) since 2015, 5 and 10-20 respiratory ECMO placements are performed there annually. Patients who received respiratory ECMO during the study period were enrolled for analysis. Their demographic data, indication for ECMO placement, ECMO device days (called ECMO days), duration of ICU hospitalization, in-hospital mortality at the index hospitalization, the number of ECMO-CLABSI events, and causative pathogens were extracted from the electronic medical records. ECMO-CLABSI patients were required to have a laboratory-confirmed bloodstream infection that was not secondary to an infection at another body site. The definitions of CLABSI, ECMO days, and the ECMO device utilization ratio (DUR) from the National Healthcare Safety Network (NHSN) were used for ECMO-CLABSI. 6 The incidence density of ECMO-CLABSI and the ECMO-DUR were calculated. The Institutional Review Board of the Tokyo Metropolitan Tama Medical Center approved this study. Results In total, 97 patients received respiratory ECMO placement, and the cumulative ECMO-days were 1,138. The in-hospital mortality rate was 38.1% (37 of 97), the median respiratory ECMO-days per patient was 8.0 days (range, 1-55), and the overall ECMO-DUR was 0.023. All the patients with ECMO were concurrently fitted with a central venous catheter and arterial catheter during ECMO use. In total, ECMO-CLABSI developed in 12 patients, and the cumulative incidence density of ECMO-CLABSI during the entire study period was 10.54 per 1,000 ECMO days. Figure 1 shows the trends in the ECMO-CLABSI incidence and the ECMO-DUR. After February 2020, when the study center began admitting patients with COVID-19, both the ECMO-DUR and ECMO-CLABSI incidence density increased noticeably in comparison with the preceding period The ECMO-DUR was 0.018-0.061, with a rate ratio of 3.29 (95% confidence interval , 2.89-3.72). The ECMO-CLABSI incidence density was 10.11-11.53 per 1.000 ECMO days, with an incidence ratio of 1.14 (95% CI, 0.16-3.42). The most common causative pathogens in ECMO-CLABSI were Candida spp (3 of 12) followed by Staphylococcus spp (2 of 12). In-hospital mortality was higher in patients with ECMO-CLABSI than in those without ECMO-CLBSI: 75.0% (9 of 12) versus 32.9% (28 of 85). When the outcomes of the patients with COVID-19 on ECMO were compared with those without COVID-19 (Supplementary Table 1 online), the former tended to be more obese (body mass index >25 km/m 2 ). Although the difference was statistically nonsignificant, more ECMO-CLABSI cases were observed among patients with COVID-19. The incidence density was 16.19 per 1,000 ECMO days among patients with COVID-19 versus 8.98 per 1,000 ECMO days among those without COVID-19, for an incidence ratio of 1.80 (95% CI, 0.26-5.41). Discussion In this study, we examined trends in respiratory ECMO use over 7 years at a tertiary-care center in Japan. The overall incidence density of ECMO-CLABSI was 10.54 per 1,000 ECMO days, which is in line with other observational studies. 3,4 Respiratory ECMO use has increased since the COVID-19 pandemic began, and increasing incidence density of ECMO-CLABSI has also been observed. The clear increase in the incidence density of ECMO-CLABSI following the COVID-19 outbreak in the present study reflects the findings of a previous study in which an increase in the incidence of healthcare-associated infections, including CLABSI, occurred during the COVID-19 pandemic. 7,8 Supplementary Table 1 (online) shows that the proportion of patients with BMI >25 kg/m 2 was higher among those with COVID-19 while on ECMO. Although central venous catheterization in the femoral vein should be avoided in obese patients, 9 respiratory ECMO catheterization is frequently performed using the femoral vein. Dressing failure, local contamination, and local bacterial overgrowth create suboptimal conditions for the catheterization site. Moreover, prolonged catheterization, which can also contribute to ECMO-CLABSI development, has been observed in patients with COVID-19. Given the increased use of ECMO during the COVID-19 pandemic, an evidence-based approach is urgently needed to prevent ECMO-CLABSI. This study has several limitations. Because it was conducted at a single tertiary-care center, its findings may not apply to other institutions. Because all patients with ECMO were fitted with a central venous catheter and an arterial catheter, distinguishing ECMO-CLABSI from other catheter-related BSI was challenging. Moreover, ECMO-CLABSI may not have caused the death of the patients with ECMO. Because relatively few patients were enrolled, further studies enrolling a larger cohort are needed to verify these findings. Although there is a consensus on indications for ECMO placement, some variation in the ECMO procedure in the present study may have affected the results. In the present study, we determined the incidence of ECMO-CLABSI at a tertiary-care center in Japan. Since the COVID-19 pandemic began, demand for ECMO use has been increasing, and patients with COVID-19 requiring ECMO placement may be at risk of developing ECMO-CLABSI. Further studies enrolling a larger patient population with ECMO placement in the context of COVID-19 care are needed to clarify the ECMO-CLABSI risk in patients with COVID-19.
import numpy as np import pandas as pd def evaluate_TPD(path): xlsx = pd.read_excel(path, header=None) score = 0. frame_size = xlsx.shape[0] print(frame_size) for t in range(frame_size): det_obj = xlsx.shape[1] trac_obj = xlsx.shape[1] for n in range(1, xlsx.shape[1]+1): if n != int(xlsx.iloc[t, n-1]): if xlsx.iloc[t, n-1] == 0: det_obj -= 1 trac_obj -= 1 else: trac_obj -= 1 tpd = trac_obj / det_obj score += tpd print('TPD :%.9f'%(score/frame_size)) if __name__ == "__main__": path = 'C:/Users/이승환/Desktop/GIT/TrackPerformerAlgorism/excel/test1_our_deepsort_labels.xlsx' print(path.split('/')[1], 'files operation..') evaluate_TPD(path)
Clinical web environment to assist the diagnosis of Alzheimer's disease and other dementias In this article we present a web application for an interactive and modular virtual clinical environment, (EDEVITALZH), which constitutes an essential part of an intelligent system of neural computation to assist the diagnosis of Alzheimers disease and other dementias (SICONMID3), based on the HUMANN neural architecture. By using EDEVITALZH, it is possible to pre-diagnose dementia, to give a probable diagnosis of Alzheimers disease and differential diagnosis of dementias in a more reliable and flexible way in primary care as well as in specialised centres, due to its use in a telemedicine format. EDEVITALZH presents a Global Clinical Protocol for Dementias (GCPD) implemented using a web interface supported by a three level modular architecture (data, diagnosis and communication security) that allows rigorous and easy data handling, as well as undertaking a previous analysis before diagnosis and comparative studies of patients regardless of their actual location and geographical position. EDEVITALZH permits the fusion of heterogeneous data, enabling data introduction to be processed and analysed ranging from the purely numerical to the imprecise sentences of natural speech, normally associated with clinical records and/or of histopathological interpretations, including multidimensional and multi-parameter signals. Key-Words: Web Environment, Internet, Artificial Neural Networks, Diagnosis of Dementias, Alzheimer s Disease.
Port site recurrence and unusual diffuse subcutaneous metastases of unexpected early stage ovarian cancer after laparoscopic surgery: a case report Port site recurrence is a rare but well-documented adverse event peculiar to laparoscopic surgery. We report an unusual outcome of unexpected early stage ovarian cancer in which port site recurrence occurred after laparoscopic surgery and was followed by diffuse subcutaneous metastases. A 31-year-old Japanese woman with a large tumor in her abdomen visited our hospital. Because no intratumoral solid component was detected on diagnostic imaging, the tumor was diagnosed as a benign ovarian tumor and the patient underwent left ovarian laparoscopic cystectomy. Contrary to our expectations, however, the ovarian tumor was a mucinous carcinoma. We performed additional surgery, but the tumor recurred in the umbilical area, and multiple subcutaneous metastases later appeared. The curative effect of chemotherapy and radiation was limited. This atypical metastatic distribution of an extremely small amount of cancer might have been caused by the laparoscopic procedure. Protection against tumor cell dissemination is necessary during all forms of laparoscopic surgery. Introduction Although laparoscopic surgery is now widely used to treat various gynecological diseases owing to its safety and less invasive nature, ovarian cancer is an exception to this trend from the viewpoint of oncologic outcomes. The potential risk of port site recurrence (PSR) is one of the most important concerns. However, the precise mechanism of PSR has not been fully elucidated. Herein we report a case of PSR followed by diffuse subcutaneous metastases subsequent to laparoscopic ovarian cystectomy performed for unexpected early stage ovarian cancer. This is the first report demonstrating that even an extremely small amount of cancer tissue is associated with a risk of PSR, and this may be a hallmark of poor prognosis, especially in the absence of carcinomatosis or other advanced stages of cancer. Case Report A 31-year-old Japanese woman, gravida 0, with no remarkable medical history, presented with the complaint of abdominal distension. Ultrasound at the time of initial examination revealed a large tumor with no solid component in the abdominal cavity. Initial laboratory tests including tumor marker profile demonstrated no remarkable findings: carcinoembryonic antigen (CEA) 1.0 ng/mL, cancer antigen 125 (CA125) 32.0 U/mL, and cancer antigen 19-9 (CA19-9) 15.4 U/mL. Contrast-enhanced magnetic resonance imaging (MRI) of the pelvis revealed a 30 24 13-cm polycystic tumor with no intratumoral solid component (Figure 1a). The tumor showed no contrast enhancement. Based on the absence of malignant findings, we diagnosed a benign ovarian tumor. In the following month, we performed a laparoscopic left ovarian cystectomy. The operative time was 135 minutes and the blood loss was 850 mL, including intratumoral fluid. At the beginning of the operation, we inflated the abdomen using CO 2 gas, maintaining intra-abdominal pressure during pneumoperitoneum below 10 mmHg. A 3-cm incision was made at the umbilical site, through which 5 liters of intratumoral mucinous fluid were aspirated by rupturing directly without any wound protection ( Figure 2). Some of the intratumoral fluid leaked into the abdomen. Afterwards, a 5-mm trocar was inserted into the lower right abdomen, a SILS TM Port (Covidien, Mansfield, MA, USA) was used in the umbilical site, and the tumor was resected laparoscopically. The excised tumor was removed through the umbilical incision site and appeared to be benign on macroscopic examination. No other abnormal findings were observed in the abdominal cavity. Contrary to our expectations, the tumor was diagnosed as a mucinous carcinoma rather than a benign tumor. Macroscopically, no malignant findings, including in the solid component, could be seen in the tumor. Examination of the entire specimen (109 segments in total) and histopathological analysis revealed that the majority of the tumor consisted of an adenoma, but a small number of individual cells with severe atypia had invaded 1 mm into the stroma ( Figure 3a-3c). These were 3, 4, and 10 mm in size. Additional tests and treatments were performed. Contrast-enhanced computed tomography (CT) and endoscopy of the gastrointestinal tract and colon demonstrated no remarkable findings. We excised the residual left adnexa, partial omentum, and appendix via open laparotomy on postoperative day 59. The operative time was 71 minutes and the blood loss was 32 mL. Only a few, solitary, atypical cells were found in the histopathological specimen of the residual left ovary. Cytology of the ascites was negative. Stage 1C1 ovarian cancer was finally diagnosed. We discussed the potential risks of ovarian cancer with the patient and her family and decided to pursue a course of follow-up without any additional treatment. Eleven months after the second surgery, a 2-cm tumor in the umbilical area was identified on follow-up CT (Figure 4a), and PSR was diagnosed. The tumor marker profiles were unremarkable: CEA 0.2 ng/mL and CA125 21.4 U/mL. The CA19-9 value of 51.9 U/mL was slightly higher than normal. No other tumor was observed on diagnostic imaging, and the recurrent tumor was resected in the fol-lowing month. The operative time was 90 minutes and the blood loss was 10 mL. Histopathological analysis indicated a recurrence of the ovarian cancer. The incised margin of the specimen contained no cancer cells. Cytology of the ascites was negative. Adjuvant combined chemotherapy with paclitaxel and carboplatin was initiated. However, multiple subcutaneous metastases appeared around the right axilla during chemotherapy (Figure 4b). The patient was treated with a combination of chemotherapy and radiation, but the curative effect was limited, and the subcutaneous metastases in the region of the right axilla emerged repeatedly. The subcutaneous metastases gradually spread to other parts of the body and later appeared in bone and the adrenal glands, which were the atypical places for the spread of ovarian cancer. Eventually, the cancer metastasized to the systemic lymph nodes, liver, and thorax. The patient died 36 months after the first surgery. The patient and her family agreed to the publication of the present report. Discussion Because laparoscopic tumor resection is now the first choice in the treatment of benign ovarian tumors, preopera- tive differentiation between benign and malignant ovarian tumors is crucial. However, even with state-of-the-art diagnostic imaging techniques, an accurate diagnosis is particularly challenging when the cancer cells exist only within a limited area in a large ovarian tumor. A laparoscopic procedure performed for early ovarian cancer that cannot be detected preoperatively might result in a poor outcome, as in the present case. This is the first report of an unusual manifestation of PSR of ovarian cancer. This case has two important implications. First, even in early stage ovarian cancer, and even as a result of an extremely small amount of cancer, PSR can occur after laparoscopic surgery. Our literature search of the PubMed database identified reports of PSR, but there were no reports of the occurrence of PSR in early stage ovarian cancer. All previous studies reported that PSR occurred in advanced stages, including carcinomatosis and metastases. In the present case, we strongly suspect a relationship between PSR and the laparoscopic procedure because the case involved early stage ovarian cancer that could not be detected preoperatively owing to the extremely small size of the cancer. Moreover, the procedure of rupturing the tumor to reduce its volume and the lack of wound protection during the tumorectomy are both suspected to have increased the risk of PSR. To prevent unexpected tumor cell dissemination, a no-touch isolation technique should be employed, in which the tumor is ruptured in a bag to prevent spillage into the abdomen. Second, PSR might be a hallmark of poor prognosis in the absence of carcinomatosis or other advanced stage cancer, as evidenced by the atypical metastatic distribution observed in the present case. Some reports of PSR have indicated that PSR itself did not influence the prognosis of ovarian cancer. In most cases, PSR occurs in advanced stage cancer, and patients who are at risk of PSR have a poor prognosis owing to their advanced cancer status. We therefore believe that there is no relationship between the PSR itself and the prognosis of advanced cancer. However, the same cannot be said in early ovarian cancer, such as in the present case, which demonstrated that PSR was a risk factor for atypical metastatic distribution, i.e., multiple, recurrent, subcutaneous metastases. The occurrence of subcutaneous metastases without any other metastases caused by internal cancer is unusual 6). The physiology of the atypical metastatic distribution in this case was similar to that observed in the case of umbilical nodules sometimes referred to as "Sister Mary Joseph's nodules" (SMJN) 7,8). SMJN is a result of the metastasis of cancer in the pelvis or abdomen, and the umbilicus is at risk in the spread of cancer cells owing to several factors including hematogenous or lymphatic metastasis, transperitoneal in-vasion, and remnant structures. The exact metastatic mechanism in SMJN remains unclear, but SMJN is sometimes known as the spread to subcutaneous tissue. It is likely that the atypical metastatic distribution in this case was caused by a mechanism related to SMJN. In the present case, SMJN may unfortunately have been primarily iatrogenic. From a laparoscopic perspective, CO 2 -pneumoperitoneum might be related to the atypical metastatic distribution observed in the present case. Volz et al. demonstrated in an animal model that pneumoperitoneum provoked cancer cell implantation and growth 9). Some reports have also suggested that pneumoperitoneum might trigger the proliferation of ovarian cancer cells in subcutaneous tissue 10,11). Although other reports have indicated that pneumoperitoneum did not influence the overall survival of ovarian cancer 12,13), these studies focused on advanced stages of cancer. CO 2 -pneumoperitoneum may also have triggered atypical metastatic distribution, i.e., multiple subcutaneous metastases, in the present case. Conclusion Our findings suggest that PSR occurred following laparoscopic surgery for early stage ovarian cancer in the present case. An atypical metastatic distribution following PSR indicated that PSR might be a hallmark of poor prognosis. We strongly recommend that tumor cell dissemination be prevented during all types of laparoscopic surgery, given the difficulty of making an accurate, preoperative diagnosis of ovarian tumors. Further research is needed to confirm the precise mechanism of the PSR for prevention.
package seers.bugrepanalyzer.stats; import java.util.List; public class IndexStats { private List<AssTermStats> termStats; private int numDoc; private int numTerms; private int numTermsThreshold; private int threshold; private long totalDf; public List<AssTermStats> getTermStats() { return termStats; } public void setTermStats(List<AssTermStats> termStats) { this.termStats = termStats; } public int getNumDoc() { return numDoc; } public void setNumDoc(int numDoc) { this.numDoc = numDoc; } public int getNumTerms() { return numTerms; } public void setNumTerms(int numTerms) { this.numTerms = numTerms; } public int getNumTermsThreshold() { return numTermsThreshold; } public void setNumTermsThreshold(int numTermsThreshold) { this.numTermsThreshold = numTermsThreshold; } public int getThreshold() { return threshold; } public void setThreshold(int threshold) { this.threshold = threshold; } @Override public String toString() { return "IndexStats [numDoc=" + numDoc + ", numTerms=" + numTerms + ", numTermsThreshold=" + numTermsThreshold + ", threshold=" + threshold + "]"; } public long getTotalDf() { return totalDf; } public void setTotalDf(long totalDf) { this.totalDf = totalDf; } }
<reponame>hendrikKahl/landscaper<gh_stars>0 // SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company and Gardener contributors. // // SPDX-License-Identifier: Apache-2.0 package helm import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/runtime/inject" lsv1alpha1 "github.com/gardener/landscaper/apis/core/v1alpha1" ) func AddActuatorToManager(mgr manager.Manager) error { a, err := NewActuator() if err != nil { return err } if _, err := inject.LoggerInto(ctrl.Log.WithName("controllers").WithName("MockDeployer"), a); err != nil { return err } return ctrl.NewControllerManagedBy(mgr). For(&lsv1alpha1.DeployItem{}). Complete(a) }
From IMF Poster Child to Wayward Student This chapter considers why the International Monetary Fund (IMF) did it not prevent Argentina's record default of 2001. It suggests that the IMF was both unable and unwilling to stop it. While the second enforcement mechanism of conditional IMF lending was initially fully operative, helping to enforce Argentina's compliance in the first years of the crisis, the outcome of the megaswap greatly reduced the risk of an Argentine default to the international financial system. Combined with mounting domestic opposition in the United States to further international bailout loans, this greatly weakened the IMF's capacity to impose fiscal discipline on Argentina, eventually leading the Fund to pull the plug on its own bailout program, causing the second enforcement mechanism to break down altogether. The chapter recounts the process through which this breakdown occurred.
from sys import stdin from itertools import repeat def main(): n, m = map(int, stdin.readline().split()) dat = map(int, stdin.read().split(), repeat(10, 2 * m)) c = [0] * (n + 1) for x in dat: c[x] += 1 f = 0 for i in xrange(n + 1): if c[i] & 1: print "NO" return print "YES" main()
// @noEmit: true // @allowJs: true // @checkJs: true // @skipLibCheck: true // @lib: es2017, dom // @Filename: foo.js // Repro for #16585 const x = { bar() { setTimeout(function() { arguments }, 0); } }
Thermal Degradation of HDPE in a Batch Pressure Reactor: Reaction Time and Mechanical Stirring Effect The effect of reaction time and mechanical stirring on thermal degradation of high density polyethylene(HDPE) was studied at 350°C under nitrogen atomosphere in a batch pressure reactor. Changes in molecular weight(MW), molecular weight distribution (MWD), and crystalline behaviors of the degraded products were investigated by gel chromatography (GPC) and differential scanning calorimetry (DSC). It was found that MWD curves all shifted toward lower molecular weight with increasing reaction time, with both the extent of the movement and its showing a rapid initial drop and then leveling off. In a short period of reaction time, the MW, MWD and crystalline behaviors of the degraded products were affected notably by the mechanical stirring. The of the degraded products without stirring was lower than that of products with stirring in the same time, which should be related to the large difference of temperature distributions in the reactor. When the reaction time reached 4 h, the of the degraded products had dropped to about 5 103g/mol from about 3 105g/mol for the original, and the product did not show the melting and crystallization behaviors of high density polyethylene again.
import tensorflow as tf from tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPooling2D, Flatten, Dropout, Dense import tensorflow_addons as tfa import tensorflow_datasets as tfds import pickle, urllib from datetime import datetime import os import sys import shutil class Preprocessing: @staticmethod def _split_dict(t: tf.Tensor) -> (tf.Tensor, tf.Tensor): return t['image'], t['label'] # TODO is the type of the input tf.Tensor? @staticmethod def _normalize(image: tf.Tensor, label: tf.Tensor) -> (tf.Tensor, tf.Tensor): # Change values range from [0, 255] to [-0.5, 0.5] image = (image / 255) - 0.5 return image, label @staticmethod # this method is only used to reverse normalisation so we can display the images def denormalize(image: tf.Tensor) -> tf.Tensor: return (image + 0.5) * 255 @staticmethod # TODO Resize: In the paper for images they kept the ratio, in mine the images were made square def _resize(image: tf.Tensor, label: tf.Tensor) -> (tf.Tensor, tf.Tensor): image = tf.image.resize(image, size=tf.constant((256, 256))) return image, label @staticmethod # TODO TEMPORARY def _resize_testing(image: tf.Tensor, label: tf.Tensor) -> (tf.Tensor, tf.Tensor): image = tf.image.resize(image, size=tf.constant((224, 224))) return image, label @staticmethod def _augment(image: tf.Tensor, label: tf.Tensor) -> (tf.Tensor, tf.Tensor): image = tf.image.random_brightness(image, max_delta=0.1) image = tf.image.random_contrast(image, lower=0.9, upper=1.1) image = tf.image.random_crop(image, size = (224, 224, 3)) image = tf.image.random_flip_left_right(image) image = tf.clip_by_value(image, -0.5, 0.5) return image, label @staticmethod def create_generator(ds, for_training, batch_size = 128, buffer_size = 256): auto=tf.data.experimental.AUTOTUNE ds = ds.map(Preprocessing._split_dict, num_parallel_calls=auto) ds = ds.map(Preprocessing._normalize, num_parallel_calls=auto) if for_training: ds = ds.map(Preprocessing._resize, num_parallel_calls=auto) else: ds = ds.map(Preprocessing._resize_testing, num_parallel_calls=auto) if for_training: ds = ds.map(Preprocessing._augment, num_parallel_calls=auto) ds = ds.repeat() # repeat forever ds = ds.shuffle(buffer_size=buffer_size) if batch_size > 1: ds = ds.batch(batch_size) # Prefetching overlaps the preprocessing and model execution of a training step. # While the model is executing training step s, the input pipeline is reading the data for step s+1. # Doing so reduces the step time to the maximum (as opposed to the sum) of the training and the time it takes to extract the data. # https://www.tensorflow.org/guide/data_performance ds = ds.prefetch(buffer_size=1) # using "auto" ends up with OOM during validation step return ds class Model: @staticmethod def build(): # Following the paper: "We initialized the weights in each layer from a zero-mean Gaussian distribution with standard deviation 0.01." point_zero_one = tf.compat.v1.keras.initializers.RandomNormal(mean=0.0, stddev=0.01) # "We initialized the neuron biases in the second, fourth, and fifth convolutional layers, # as well as in the fully-connected hidden layers, with the constant 1. This initialization accelerates # the early stages of learning by providing the ReLUs with positive inputs. We initialized the neuron # biases in the remaining layers with the constant 0." # I put this to 0.1 instead of 1, because with 1 it converges very slow in the beginning, (like the bias is so big that it "shadows" the true value) one = tf.compat.v2.constant_initializer(value=0.1) zero = tf.compat.v2.constant_initializer(value=0) # "L2 regularization is also called weight decay in the context of neural networks. # Don't let the different name confuse you: weight decay is mathematically the exact same as L2 regularization." # https://www.tensorflow.org/tutorials/keras/overfit_and_underfit weight_decay = tf.keras.regularizers.l2(0) # TODO I changed it from default: 0.0005 model = tf.keras.Sequential([ # 1st conv. layer # Number of weights is ((11×11×3+1)×96) = 34944 where: # 11 * 11 = convolution filter size # 3 = number of input layers # 1 = bias # 96 = number of output layers Conv2D(96, (11, 11), input_shape=(224, 224, 3), strides=4, activation='relu', bias_initializer=zero, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), BatchNormalization(), MaxPooling2D(pool_size=3, strides=2), # 2nd conv. layer # Number of weights is ((5×5×96+1)×256) = 614656 Conv2D(256, (5, 5), activation='relu', bias_initializer=one, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), BatchNormalization(), MaxPooling2D(pool_size=3, strides=2), # 3rd conv. layer Conv2D(384, (3, 3), activation='relu', bias_initializer=zero, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), # 4th conv. layer Conv2D(384, (3, 3), activation='relu', bias_initializer=one, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), # 5th conv. layer Conv2D(256, (3, 3), activation='relu', bias_initializer=one, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), BatchNormalization(), MaxPooling2D(pool_size=3, strides=2), Flatten(), Dropout(rate=0.5), Dense(4096, activation='relu', bias_initializer=one, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), Dropout(rate=0.5), Dense(4096, activation='relu', bias_initializer=one, kernel_initializer=point_zero_one, kernel_regularizer=weight_decay), # 1000 categories Dense(1000, activation='softmax', bias_initializer=zero, kernel_initializer=point_zero_one) ]) # [PAPER] "We used an equal learning rate for all layers, which we adjusted manually throughout training." # Also check the ReduceLROnPlateau training callback lower model.compile( # [PAPER] We trained our models using stochastic gradient descent with a batch size of 128 examples, momentum of 0.9, and weight decay of 0.0005. # note: the weight decay is above. Check each layer. optimizer=tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9), # "categorical_crossentropy": uses a one-hot array to calculate the probability, # "sparse_categorical_crossentropy": uses a category index # source: https://stackoverflow.com/questions/58565394/what-is-the-difference-between-sparse-categorical-crossentropy-and-categorical-c loss='sparse_categorical_crossentropy', metrics=['accuracy', tf.keras.metrics.SparseTopKCategoricalAccuracy(k=5) ]) return model # TODO From paper: "At test time, the network makes a prediction by extracting five 224 × 224 patches # (the four corner patches and the center patch) as well as their horizontal reflections (hence ten patches in all), # and averaging the predictions made by the network’s softmax layer on the ten patches def configure_gpu(): # from https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) class Alexnet: def __init__(self): configure_gpu() def load_data(self, sample_fraction=1, only_one = False): # http://www.image-net.org/challenges/LSVRC/2012/ # number_categories = 1000 # 1.2 million train images # 150 000 validation images total_train_data_size = 1.2 * 1000 * 1000 # The alternative of counting this would take ages: len(list(train_data)))) total_validation_data_size = 150 * 1000 print("Loading input dataset") train_data, validation_data = Data.load() self.train_data_size = int(sample_fraction * total_train_data_size) self.validation_data_size = int(sample_fraction * total_validation_data_size) if only_one: # I use this in testing self.train_data_size = 1 self.validation_data_size = 1 print(f"A fraction of {sample_fraction} was selected from the total data") print(f"Number of examples in the Train dataset is {self.train_data_size} and in the Validation dataset is {self.validation_data_size}") self.train_data = train_data.take(self.train_data_size) self.validation_data = validation_data.take(self.validation_data_size) def create_generator(self, batch_size = 128): print("Creating the generators") self.batch_size = batch_size self.train_augmented_gen = Preprocessing.create_generator(self.train_data, for_training=True, batch_size = self.batch_size) self.validation_gen = Preprocessing.create_generator(self.validation_data, for_training=False) def build_model(self): self.model = Model.build() @staticmethod def _get_checkpoint_folder(version) -> str: # Checkpoint files contain your model's weights # https://www.tensorflow.org/tutorials/keras/save_and_load return 'trained_models/' + version + '/cp.ckpt' def train(self, dataset_iterations, version, logs='./logs'): # [PAPER] The heuristic which we followed was to divide the learning rate by 10 when the validation error # rate stopped improving with the current learning rate. The learning rate was initialized at 0.01 and # reduced three times prior to termination. reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=1, min_lr=0.0001) # Create a callback that saves the model's weights checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(filepath=Alexnet._get_checkpoint_folder(version), save_weights_only=True, verbose=1) # Create a callback that logs the progress so you can visualize it in Tensorboard log_dir = logs + '/fit/' + datetime.now().strftime('%Y%m%d-%H%M%S') tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1) print("Starting the training") self.history = self.model.fit( x=self.train_augmented_gen, validation_data = self.validation_gen, # An epoch is an iteration over the entire x and y data provided. epochs = dataset_iterations, # Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch steps_per_epoch = self.train_data_size / self.batch_size, callbacks=[reduce_lr, checkpoint_callback, tensorboard_callback] ) def predict(self, images): return self.model.predict(images) def load_model(self, version, path=None): self.build_model() if path is None: path = Alexnet._get_checkpoint_folder(version) self.model.load_weights(path) if __name__ == '__main__': current_version = 'v1.4' network = Alexnet() network.load_data(sample_fraction=1) network.create_generator() network.build_model() # The default behaviour should be to resume training for current version, # so we don't make accidents by overwriting a trained model. if len(sys.argv)==1 or sys.argv[1] is not 'start_new': network.load_model(current_version) # [PAPER] We trained the network for roughly 90 cycles through the # training set of 1.2 million images, which took five to six days on two NVIDIA GTX 580 3GB GPUs" network.train(dataset_iterations=45, version=current_version) # Journal (Run log) # Best record (Full dataset): Epoch 45/45 # 9375/9375 [==============================] - ETA: 0s - loss: 2.8965 - accuracy: 0.3651 - sparse_top_k_categorical_accuracy: 0.6244 # Epoch 00045: saving model to trained_models/v1.4/cp.ckpt # 9375/9375 [==============================] - 1315s 140ms/step - loss: 2.8965 - accuracy: 0.3651 - sparse_top_k_categorical_accuracy: 0.6244 - val_loss: 2.8773 - val_accuracy: 0.3791 - val_sparse_top_k_categorical_accuracy: 0.6313 - lr: 1.0000e-04
<reponame>ufukhalis/gateway<filename>src/main/java/io/github/ufukhalis/gateway/config/GatewayPathConfig.java package io.github.ufukhalis.gateway.config; import lombok.Data; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @Data @Component @EnableAutoConfiguration @EnableConfigurationProperties @ConfigurationProperties(prefix="gateway.config") public class GatewayPathConfig { private List<Mapping> mapping; @Data @EnableConfigurationProperties @ConfigurationProperties(prefix="gateway.config.mapping") public static class Mapping{ private String target; private String uri; } }
/** * Calculate sections of the list * * @param addSeparators True to add GUI-level separators, false to just populate the cache */ private void calculateSections(boolean addSeparators) { char prevFirstChar = 'a'; boolean firstSeparator = true; for (int i = 0; i < mItems.size(); ++i) { String title = mItems.get(i).mTitle; char firstChar; if(title.length() > 0) firstChar = title.toUpperCase(Locale.ENGLISH).charAt(0); else firstChar = '#'; if (Character.isLetter(firstChar)) { if (firstSeparator || firstChar != prevFirstChar) { if(addSeparators) { ListItem item = new ListItem(String.valueOf(firstChar), null, null, true); mItems.add(i, item); mSections.put(i, String.valueOf(firstChar)); i++; } else mSections.put(i, String.valueOf(firstChar)); prevFirstChar = firstChar; firstSeparator = false; } } else if (firstSeparator) { if(addSeparators) { ListItem item = new ListItem("#", null, null, true); mItems.add(i, item); mSections.put(i, "#"); i++; } else mSections.put(i, "#"); prevFirstChar = firstChar; firstSeparator = false; } } notifyDataSetChanged(); }
Quite the eyeful! Christina Milian opted to go sheer on Monday night when she attended the Live By Night Los Angeles premiere in a see-through gown. The sequin copper dress displayed her Spanx underneath as the singer and TV personality opted to go bra-free. It’s unclear whether Milian meant for the look to be so revealing, but she seemed to have a blast none-the-less. For more from Affleck’s interview, watch the clip below!
A Georgia mom who took the internet by storm after video of her shooting her kids' cell phones as a punishment went viral has reportedly lost custody of her two youngest children. Deborah Smith of Coweta County originally made headlines with her creative discipline technique and colorful condemnation of social media. Parents both celebrated and condemned her, but Smith said her technique worked, at least for a while. Parents both celebrated and condemned her, but Smith said her technique worked, at least for a while. But soon she said her sons Ethan and Robbie began to stay out all night, do and sell drugs, and leave her to deal with "the aftermath" as they slept all day. Read: Mother Who Set Newborn Baby On Fire After Hiding Pregnancy Gets 30 Years in Prison "Today, we’re going to take that option of where to sleep away,” Smith says, shotgun in hand, in a newer video, posted April 5. “I’ve had enough.” The camera soon pans to a smoldering fire as Smith is heard in the background cocking her weapon. She pulls the trigger and the fire roars once again. "Boys," she says as the camera focuses on a pile of hot ash, "this is all that's left of your beds. I'm sorry. But they exploded." This time around, not everyone is laughing at Smith's creative parenting. Someone reported the video to Coweta County Department of Children and Family Services. According to AJC.com, a social worker told Smith she had to sign a “safety plan” and agree not to use weapons in front of the children. Read: Parents Who Forced Emaciated 6-Year-Old Boy to Live On Hot Dog Smoothies Sentenced to 20 Years Smith refused to sign away her First and Second Amendment rights, she told AJC, and the department took away her two youngest teens. “They’re at the cusp of being 17 years old, where it goes from being juvenile offenses to adult offenses,” she said. “I just don’t know where it’s gonna end. I don’t want them to die.” In a follow-up video that appears to have been posted after her run-in with Family Services but before the teens were taken away, Smith seems to address the "safety plan." "I've been told I can no longer use a gun or film anymore videos because it might damage my child," she says, before explaining: "Yes, I blew up my children’s phones. Yes, I burned my children’s mattresses. I wanted my children’s attention before it’s too late for them to learn how to be a responsible, respectful adult." Watch: Teacher Accused of Having Sex With Student While Fiance Was At Bachelor Party Related Articles:
def _convert_dict_list_to_dict_numpy(dict_list): dict_numpy = {} for k, v in dict_list.items(): dict_numpy[k] = np.array(v) return dict_numpy
// Same properties in request and response, but different subsets are required. public class Wagon { private String wagonId; private List<Surface> surfaces; private List<String> capabilities; // TODO: derive from surfaces? What is this used for? private Dimensions dimensions; public static Wagon of(Surface surface) { return new Wagon("0", List.of(surface)); } public static Wagon of(List<Surface> surfaces) { return new Wagon("0", List.copyOf(surfaces)); } public static Wagon of(String id, List<Surface> surfaces) { return new Wagon(id, List.copyOf(surfaces)); } private Wagon(String id, List<Surface> surfaces) { this(id, surfaces, List.of(), null); } private Wagon(String id, List<Surface> surfaces, List<String> capabilities, Dimensions dimensions) { this.wagonId = id; this.surfaces = surfaces; this.capabilities = capabilities; this.dimensions = derive(dimensions); } private Dimensions derive(Dimensions dimensions) { if (dimensions != null) { return dimensions; } return surfaces.stream().map(Surface::size).max(Dimensions::compareTo).get(); } public int volume() { throw new UnsupportedOperationException("Not implemented."); } public Wagon withCapabilities(Collection<String> capabilities) { return new Wagon(wagonId, surfaces, List.copyOf(capabilities), dimensions); } public Wagon withDimensions(Dimensions dimensions) { return new Wagon(wagonId, surfaces, capabilities, dimensions); } public String wagonId() { return wagonId; } public List<String> capabilities() { return capabilities; } public List<Surface> surfaces() { return surfaces; } public Dimensions dimensions() { return dimensions; } public int width() { return dimensions.x; } public int depth() { return dimensions.y; } public Surface getSurfaceById(int id) { final var result = surfaces.stream().filter(s -> s.id == id).findAny(); if (result.isEmpty()) { final var ids = surfaces.stream().map(s -> s.id).collect(toList()); throw new IllegalArgumentException("Could not find surface id " + id + " in " + ids); } return result.get(); } public Surface surfaceOf(Dimensions position) { return surfaces.stream().filter(s -> s.origin.z == position.z).findAny().get(); } }
Proposal and numerical feasibility study of a novel multi-modal and multi-axis dynamic vibration absorber consists of spherical viscoelastic material containing embedded ball-like mass This paper proposes a novel DVA (Dynamic Vibration Absorber) consisting of a ball-like mass embedded in a spherical viscoelastic material to meet practical demands for the multi-modal and multi-axis vibration reduction against elastic vibrations of structures. This DVA is called eMDVA (embedded Mass DVA) here, and the embedded mass can vibrate every direction in the viscoelastic medium. The unique concept of the eMDVA is inspired by the damping effect caused by passengers on railway vehicles. This paper describes a basic configuration of the eMDVA and some numerical studies using finite element (FE) vibration analysis to design the eMDVA. From the numerical investigation, it has been found that the natural frequency of a single-mass eMDVA can be controlled by changing the combination of the sizes of the viscoelastic sphere and the embedded mass. The frequency response function (FRF) of the acceleration of the embedded mass versus excitation force has a dominant single peak corresponding to one of the natural frequencies. These results indicate that the proposed eMDVA is suitable as a DVA, and it can be designed to tune the target vibration frequencies of host structures. As a more realistic analysis, numerical investigation for the thin and long plate-like host structure (a 1:10 scale model of the floor structure of a railway vehicle) was conducted, and multi-modal vibration reduction has been observed by applying the eMDVA consisting of two sets of viscoelastic spheres and embedded masses with different sizes. From these numerical investigations, it has been shown that the proposed eMDVA has promising potential as a multi-modal damper for elastic vibrations. response function of of the ball-like versus excitation single peak frequency changes to the size of the show that of host the proper of sizes of the viscoelastic sphere and embedded ball-like mass, eMDVA
On network intrusion detection for deployment in the wild As the number of network-based attacks continue to increase, network operations and management tasks become more and more complex. As we have come to depend on reliable operations of networked systems, it is important to be able to provide security measures that both efficient in terms of processing speed as well as in detecting attacks that are not in the database. To this end, anomaly-based intrusion detection systems allow detection of previously unknown and never seen attacks, and effectively complement signature-based detection schemes. In this paper, we evaluate a robust intrusion detection scheme with the goal of developing stand-alone devices that can be deployed in a plug-and-play manner to existing systems. Such devices are attractive as it allows an added security feature to quickly be deployed without adding to the management complexity of existing systems. Our system is robust in that it is resilient to contaminated traffic that may be included in real-time training. Leveraging this advantage, we show that our detection system can self-train without the need for a large, sanitized training data set typically required for many anomaly-based detection schemes. This feature naturally lends itself to faster deployment and for managing systems in changing environments. We demonstrate this concept by developing a physical prototype using an embedded platform. Our results show that amount of delay introduced by the device is small. Another attractive feature of the stand alone device is that it is impossible to temper with without physical access to the device, even if host systems are compromised.
def export(self, activity, file_name, file_type): buf = "" if file_type == 'csv': buf = self.export_as_csv(file_name, activity) elif file_type == 'gpx': buf = self.export_as_gpx(file_name, activity) elif file_type == 'tcx': buf = self.export_as_tcx(file_name, activity) else: raise Exception("Invalid file type specified.") return buf
import inspect import os import shutil import sys import threading import unittest from processflow.lib.util import print_line from processflow.lib.initialize import initialize, parse_args from processflow.version import __version__, __branch__ class TestInitialize(unittest.TestCase): """ A test class for validating the project setup These tests should be run from the main project directory """ def __init__(self, *args, **kwargs): super(TestInitialize, self).__init__(*args, **kwargs) def test_parse_args_valid(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') argv = ['-c', 'tests/test_configs/valid_config_simple.cfg', '-l', 'pflow.log', '-r', 'resources/', '-m', '999', '--debug', '--dryrun'] pargs = parse_args(argv) self.assertEqual( pargs.config, 'tests/test_configs/valid_config_simple.cfg') self.assertEqual(pargs.resource_path, 'resources/') self.assertEqual(pargs.log, 'pflow.log') self.assertEqual(pargs.max_jobs, 999) self.assertTrue(pargs.debug) self.assertTrue(pargs.dryrun) self.assertFalse(pargs.always_copy) def test_parse_args_print_help(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') argv = ['-h'] with self.assertRaises(SystemExit) as exitexception: pargs = parse_args(argv) self.assertEqual(exitexception.exception.code, 0) argv = [] pargs = parse_args(argv, print_help=True) self.assertEqual(pargs, None) def test_init_print_version(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') argv = ['-v'] with self.assertRaises(SystemExit) as exitexception: a, b, c = initialize(argv=argv, version=__version__) self.assertEqual(exitexception.exception.code, 0) def test_init_no_config(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') argv = [] a, b, c = initialize(argv=argv) self.assertEqual(a, False) self.assertEqual(b, False) self.assertEqual(c, False) def test_init_valid_config_simple(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/valid_config_simple.cfg'] _, _, _ = initialize( argv=pargv, version=__version__, branch=__branch__) def test_init_config_doesnt_exist_simple(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/this_file_doesnt_exist.cfg'] config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) def test_init_config_no_white_space_simple(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/invalid_config_no_white_space.cfg'] config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) def test_init_cant_parse_config(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/invalid_config_cant_parse.cfg'] config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) def test_init_missing_lnd(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/invalid_config_missing_lnd.cfg'] config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) def test_init_from_scratch_config(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/valid_config_from_scratch.cfg', '-m', '1'] project_path = '/p/user_pub/e3sm/baldwin32/testing/empty/' if os.path.exists(project_path): shutil.rmtree(project_path) config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertNotEqual(config, False) self.assertNotEqual(filemanager, False) self.assertNotEqual(runmanager, False) self.assertEqual(os.path.exists(project_path), True) if os.path.exists(project_path): shutil.rmtree(project_path) def test_init_from_scratch_config_bad_project_dir(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/valid_config_from_scratch_bad_project_path.cfg'] project_path = '/usr/testing/' with self.assertRaises(SystemExit) as exitexception: config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) self.assertEqual(os.path.exists(project_path), False) self.assertEqual(exitexception.exception.code, 1) def test_init_from_scratch_config_globus(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/valid_config_from_scratch_globus.cfg'] project_path = '/p/user_pub/e3sm/baldwin32/testing/empty/' if os.path.exists(project_path): shutil.rmtree(project_path) config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertNotEqual(config, False) self.assertNotEqual(filemanager, False) self.assertNotEqual(runmanager, False) self.assertEqual(os.path.exists(project_path), True) if os.path.exists(project_path): shutil.rmtree(project_path) def test_init_from_scratch_config_globus_bad_uuid(self): print '\n' print_line( '---- Starting Test: {} ----'.format(inspect.stack()[0][3]), status='ok') pargv = ['--test', '-c', 'tests/test_configs/valid_config_from_scratch_globus_bad_uuid.cfg'] project_path = '/p/user_pub/e3sm/baldwin32/testing/empty/' if os.path.exists(project_path): shutil.rmtree(project_path) config, filemanager, runmanager = initialize( argv=pargv, version=__version__, branch=__branch__) self.assertEqual(config, False) self.assertEqual(filemanager, False) self.assertEqual(runmanager, False) self.assertEqual(os.path.exists(project_path), True) if os.path.exists(project_path): shutil.rmtree(project_path) if __name__ == '__main__': unittest.main()
The Open Caucus, a forum for discussion on issues of national importance, was first established in 2014 when Senate Liberals opened their Caucus doors to the public on Wednesday mornings. The Open Caucus is now co-sponsored by the Independent Senate Liberals, the Independent Senators Group, and the Office of the Government Representative in the Senate. This non-partisan collaboration now brings together three groups representing the majority of the Senate’s current membership. The discussion is open to all Members of Parliament, Senators, parliamentary staff, media, and the public. As Canadians remain the second-highest per capita users of opioids in the world, an in-depth and informed national conversation needs to be undertaken into how this was allowed to intensify throughout the country over the past several years. Moreover, there has been a rapid increase in the overdoses and deaths caused by opioids, especially from highly-concentrated forms such as fentanyl. The rate of hospitalizations has increased by 27% over the past 5 years, with an average of 11 deaths per day in 2017. Research suggests that the use and misuse of opioids is a complex health and social issue that requires further investigation. In light of this crisis, we ask experts: What factors are contributing to the use, misuse, dependence and/or addiction caused by opioids? What measures can be taken to mitigate the risk of harm caused by opioids? Panelists will be: Dr. Sheri Fandrey: Clinical Assistant Professor, College of Pharmacy, University of Manitoba Dr. John Weekes: Director, Research and Academics, Waypoint Centre for Mental Health Care Dr. Jeffrey Turnbull: Medical Director, Ottawa Inner City Health, Chief of Staff, The Ottawa Hospital Dr. Caroline Hosatte-Ducassy: Emergency Medicine Resident, McGill University Dr. Esther Tailfeathers: Medical Lead for the Population and Public, Indigenous Strategic Care Network The meeting will take place: Wednesday, February 20, 2019 8:00am – 10:00am Room C110, 1 Wellington Street Please RSVP to Andrew Miller at andrew.miller@sen.parl,gc.ca.
<reponame>slavapestov/swift-corelibs-foundation // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* CFConcreteStreams.c Copyright (c) 2000 - 2015 Apple Inc. and the Swift project authors Responsibility: <NAME> */ #include "CFStreamInternal.h" #include "CFInternal.h" #include <CoreFoundation/CFPriv.h> #include <CoreFoundation/CFNumber.h> #include <sys/types.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <sys/stat.h> #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX #include <sys/time.h> #include <unistd.h> #endif #define SCHEDULE_AFTER_WRITE (0) #define SCHEDULE_AFTER_READ (1) #define APPEND (3) #define AT_EOF (4) #define USE_RUNLOOP_ARRAY (5) /* File callbacks */ typedef struct { CFURLRef url; int fd; #ifdef REAL_FILE_SCHEDULING union { CFFileDescriptorRef cffd; // ref created once we open and have an fd CFMutableArrayRef rlArray; // scheduling information prior to open } rlInfo; // If fd > 0, cffd exists. Otherwise, rlArray. #else uint16_t scheduled; // ref count of how many times we've been scheduled #endif CFOptionFlags flags; off_t offset; } _CFFileStreamContext; CONST_STRING_DECL(kCFStreamPropertyFileCurrentOffset, "kCFStreamPropertyFileCurrentOffset"); #if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX CONST_STRING_DECL(_kCFStreamPropertyFileNativeHandle, "_kCFStreamPropertyFileNativeHandle"); #endif #ifdef REAL_FILE_SCHEDULING extern void _CFFileDescriptorInduceFakeReadCallBack(CFFileDescriptorRef); static void fileCallBack(CFFileDescriptorRef f, CFOptionFlags callBackTypes, void *info); static void constructCFFD(_CFFileStreamContext *fileStream, Boolean forRead, struct _CFStream *stream) { CFFileDescriptorContext context = {0, stream, NULL, NULL, (void *)CFCopyDescription}; CFFileDescriptorRef cffd = CFFileDescriptorCreate(CFGetAllocator(stream), fileStream->fd, false, fileCallBack, &context); CFFileDescriptorEnableCallBacks(cffd, forRead ? kCFFileDescriptorReadCallBack : kCFFileDescriptorWriteCallBack); if (fileStream->rlInfo.rlArray) { CFIndex i, c = CFArrayGetCount(fileStream->rlInfo.rlArray); CFRunLoopSourceRef src = CFFileDescriptorCreateRunLoopSource(CFGetAllocator(stream), cffd, 0); for (i = 0; i+1 < c; i += 2) { CFRunLoopRef rl = (CFRunLoopRef)CFArrayGetValueAtIndex(fileStream->rlInfo.rlArray, i); CFStringRef mode = CFArrayGetValueAtIndex(fileStream->rlInfo.rlArray, i+1); CFRunLoopAddSource(rl, src, mode); } CFRelease(fileStream->rlInfo.rlArray); CFRelease(src); } fileStream->rlInfo.cffd = cffd; } #endif static Boolean constructFD(_CFFileStreamContext *fileStream, CFStreamError *error, Boolean forRead, struct _CFStream *stream) { int flags = forRead ? O_RDONLY : (O_CREAT | O_TRUNC | O_WRONLY); #if DEPLOYMENT_TARGET_WINDOWS wchar_t path[CFMaxPathSize]; flags |= (_O_BINARY|_O_NOINHERIT); if (_CFURLGetWideFileSystemRepresentation(fileStream->url, TRUE, path, CFMaxPathSize) == FALSE) #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX char path[CFMaxPathSize]; if (CFURLGetFileSystemRepresentation(fileStream->url, TRUE, (UInt8 *)path, CFMaxPathSize) == FALSE) #endif { error->error = ENOENT; error->domain = kCFStreamErrorDomainPOSIX; return FALSE; } if (__CFBitIsSet(fileStream->flags, APPEND)) { flags |= O_APPEND; flags &= ~O_TRUNC; } do { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX fileStream->fd = open((const char *)path, flags, 0666); #elif DEPLOYMENT_TARGET_WINDOWS fileStream->fd = _wopen(path, flags, 0666); #endif if (fileStream->fd < 0) break; if ((fileStream->offset != -1) && (lseek(fileStream->fd, fileStream->offset, SEEK_SET) == -1)) break; #ifdef REAL_FILE_SCHEDULING if (fileStream->rlInfo.rlArray != NULL) { constructCFFD(fileStream, forRead, stream); } #endif return TRUE; } while (1); __CFBitSet(fileStream->flags, USE_RUNLOOP_ARRAY); error->error = errno; error->domain = kCFStreamErrorDomainPOSIX; return FALSE; } static Boolean fileOpen(struct _CFStream *stream, CFStreamError *errorCode, Boolean *openComplete, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; Boolean forRead = (CFGetTypeID(stream) == CFReadStreamGetTypeID()); *openComplete = TRUE; if (ctxt->url) { if (constructFD(ctxt, errorCode, forRead, stream)) { #ifndef REAL_FILE_SCHEDULING if (ctxt->scheduled > 0) { if (forRead) CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventHasBytesAvailable, NULL); else CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventCanAcceptBytes, NULL); } #endif return TRUE; } else { return FALSE; } #ifdef REAL_FILE_SCHEDULING } else if (ctxt->rlInfo.rlArray != NULL) { constructCFFD(ctxt, forRead, stream); #endif } return TRUE; } CF_PRIVATE CFIndex fdRead(int fd, UInt8 *buffer, CFIndex bufferLength, CFStreamError *errorCode, Boolean *atEOF) { CFIndex bytesRead = read(fd, buffer, bufferLength); if (bytesRead < 0) { errorCode->error = errno; errorCode->domain = kCFStreamErrorDomainPOSIX; return -1; } else { *atEOF = (bytesRead == 0) ? TRUE : FALSE; errorCode->error = 0; return bytesRead; } } static CFIndex fileRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength, CFStreamError *errorCode, Boolean *atEOF, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; CFIndex result; result = fdRead(ctxt->fd, buffer, bufferLength, errorCode, atEOF); #ifdef REAL_FILE_SCHEDULING if (__CFBitIsSet(ctxt->flags, SCHEDULE_AFTER_READ)) { __CFBitClear(ctxt->flags, SCHEDULE_AFTER_READ); if (!*atEOF && ctxt->rlInfo.cffd) { struct stat statbuf; int ret = fstat(ctxt->fd, &statbuf); if (0 <= ret && (S_IFREG == (statbuf.st_mode & S_IFMT))) { off_t offset = lseek(ctxt->fd, 0, SEEK_CUR); if (statbuf.st_size == offset) { _CFFileDescriptorInduceFakeReadCallBack(ctxt->rlInfo.cffd); } } } if (ctxt->rlInfo.cffd) { CFFileDescriptorEnableCallBacks(ctxt->rlInfo.cffd, kCFFileDescriptorReadCallBack); } } #else if (*atEOF) __CFBitSet(ctxt->flags, AT_EOF); if (ctxt->scheduled > 0 && !*atEOF) { CFReadStreamSignalEvent(stream, kCFStreamEventHasBytesAvailable, NULL); } #endif return result; } #ifdef REAL_FILE_SCHEDULING CF_PRIVATE Boolean fdCanRead(int fd) { struct timeval timeout = {0, 0}; fd_set *readSetPtr; fd_set readSet; Boolean result; // fd_set is not a mask in Win32, so checking for an fd that's too big is not relevant if (fd < FD_SETSIZE) { FD_ZERO(&readSet); readSetPtr = &readSet; } else { int size = howmany(fd+1, NFDBITS) * sizeof(uint32_t); uint32_t *fds_bits = (uint32_t *)malloc(size); memset(fds_bits, 0, size); readSetPtr = (fd_set *)fds_bits; } FD_SET(fd, readSetPtr); result = (select(fd + 1, readSetPtr, NULL, NULL, &timeout) == 1) ? TRUE : FALSE; if (readSetPtr != &readSet) { free(readSetPtr); } return result; } #endif static Boolean fileCanRead(CFReadStreamRef stream, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; #ifdef REAL_FILE_SCHEDULING return fdCanRead(ctxt->fd); #else return !__CFBitIsSet(ctxt->flags, AT_EOF); #endif } CF_PRIVATE CFIndex fdWrite(int fd, const UInt8 *buffer, CFIndex bufferLength, CFStreamError *errorCode) { CFIndex bytesWritten = write(fd, buffer, bufferLength); if (bytesWritten < 0) { errorCode->error = errno; errorCode->domain = kCFStreamErrorDomainPOSIX; return -1; } else { errorCode->error = 0; return bytesWritten; } } static CFIndex fileWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength, CFStreamError *errorCode, void *info) { _CFFileStreamContext *fileStream = ((_CFFileStreamContext *)info); CFIndex result = fdWrite(fileStream->fd, buffer, bufferLength, errorCode); #ifdef REAL_FILE_SCHEDULING if (__CFBitIsSet(fileStream->flags, SCHEDULE_AFTER_WRITE)) { __CFBitClear(fileStream->flags, SCHEDULE_AFTER_WRITE); if (fileStream->rlInfo.cffd) { CFFileDescriptorEnableCallBacks(fileStream->rlInfo.cffd, kCFFileDescriptorWriteCallBack); } } #else if (fileStream->scheduled > 0) { CFWriteStreamSignalEvent(stream, kCFStreamEventCanAcceptBytes, NULL); } #endif return result; } #ifdef REAL_FILE_SCHEDULING CF_PRIVATE Boolean fdCanWrite(int fd) { struct timeval timeout = {0, 0}; fd_set *writeSetPtr; fd_set writeSet; Boolean result; if (fd < FD_SETSIZE) { FD_ZERO(&writeSet); writeSetPtr = &writeSet; } else { int size = howmany(fd+1, NFDBITS) * sizeof(uint32_t); uint32_t *fds_bits = (uint32_t *)malloc(size); memset(fds_bits, 0, size); writeSetPtr = (fd_set *)fds_bits; } FD_SET(fd, writeSetPtr); result = (select(fd + 1, NULL, writeSetPtr, NULL, &timeout) == 1) ? TRUE : FALSE; if (writeSetPtr != &writeSet) { free(writeSetPtr); } return result; } #endif static Boolean fileCanWrite(CFWriteStreamRef stream, void *info) { #ifdef REAL_FILE_SCHEDULING return fdCanWrite(((_CFFileStreamContext *)info)->fd); #else return TRUE; #endif } static void fileClose(struct _CFStream *stream, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; if (ctxt->fd >= 0) { close(ctxt->fd); ctxt->fd = -1; #ifdef REAL_FILE_SCHEDULING if (ctxt->rlInfo.cffd) { CFFileDescriptorInvalidate(ctxt->rlInfo.cffd); CFRelease(ctxt->rlInfo.cffd); ctxt->rlInfo.cffd = NULL; } } else if (ctxt->rlInfo.rlArray) { CFRelease(ctxt->rlInfo.rlArray); ctxt->rlInfo.rlArray = NULL; #endif } } #ifdef REAL_FILE_SCHEDULING static void fileCallBack(CFFileDescriptorRef f, CFOptionFlags type, void *info) { struct _CFStream *stream = (struct _CFStream *)info; Boolean isReadStream = (CFGetTypeID(stream) == CFReadStreamGetTypeID()); _CFFileStreamContext *fileStream = isReadStream ? CFReadStreamGetInfoPointer((CFReadStreamRef)stream) : CFWriteStreamGetInfoPointer((CFWriteStreamRef)stream); if (type == kCFFileDescriptorWriteCallBack) { __CFBitSet(fileStream->flags, SCHEDULE_AFTER_WRITE); CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventCanAcceptBytes, NULL); } else { __CFBitSet(fileStream->flags, SCHEDULE_AFTER_READ); CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventHasBytesAvailable, NULL); } } #endif static void fileSchedule(struct _CFStream *stream, CFRunLoopRef runLoop, CFStringRef runLoopMode, void *info) { _CFFileStreamContext *fileStream = (_CFFileStreamContext *)info; Boolean isReadStream = (CFGetTypeID(stream) == CFReadStreamGetTypeID()); CFStreamStatus status = isReadStream ? CFReadStreamGetStatus((CFReadStreamRef)stream) : CFWriteStreamGetStatus((CFWriteStreamRef)stream); if (fileStream->fd < 0 && status != kCFStreamStatusNotOpen) { // Stream's already closed or error-ed out return; } #ifdef REAL_FILE_SCHEDULING if (status == kCFStreamStatusNotOpen) { if (!fileStream->rlInfo.rlArray) { fileStream->rlInfo.rlArray = CFArrayCreateMutable(CFGetAllocator(stream), 0, &kCFTypeArrayCallBacks); } CFArrayAppendValue(fileStream->rlInfo.rlArray, runLoop); CFArrayAppendValue(fileStream->rlInfo.rlArray, runLoopMode); } else { CFRunLoopSourceRef rlSrc; if (!fileStream->rlInfo.cffd) { constructCFFD(fileStream, isReadStream, stream); } rlSrc = CFFileDescriptorCreateRunLoopSource(CFGetAllocator(stream), fileStream->rlInfo.cffd, 0); CFRunLoopAddSource(runLoop, rlSrc, runLoopMode); CFRelease(rlSrc); } #else fileStream->scheduled++; if (fileStream->scheduled == 1 && fileStream->fd > 0 && status == kCFStreamStatusOpen) { if (isReadStream) CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventHasBytesAvailable, NULL); else CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventCanAcceptBytes, NULL); } #endif } static void fileUnschedule(struct _CFStream *stream, CFRunLoopRef runLoop, CFStringRef runLoopMode, void *info) { _CFFileStreamContext *fileStream = (_CFFileStreamContext *)info; #ifdef REAL_FILE_SCHEDULING Boolean isReadStream = (CFGetTypeID(stream) == CFReadStreamGetTypeID()); CFStreamStatus status = isReadStream ? CFReadStreamGetStatus((CFReadStreamRef)stream) : CFWriteStreamGetStatus((CFWriteStreamRef)stream); if (status == kCFStreamStatusNotOpen) { // Not opened yet if (fileStream->rlInfo.rlArray) { CFMutableArrayRef runloops = fileStream->rlInfo.rlArray; CFIndex i, c; for (i = 0, c = CFArrayGetCount(runloops); i+1 < c; i += 2) { if (CFEqual(CFArrayGetValueAtIndex(runloops, i), runLoop) && CFEqual(CFArrayGetValueAtIndex(runloops, i+1), runLoopMode)) { CFArrayRemoveValueAtIndex(runloops, i); CFArrayRemoveValueAtIndex(runloops, i); break; } } } } else if (fileStream->rlInfo.cffd) { if (__CFBitIsSet(fileStream->flags, USE_RUNLOOP_ARRAY)) { // we know that fileStream->rlInfo.rlArray is non-NULL because it is in a union with fileStream->rlInfo.cffd CFMutableArrayRef runloops = fileStream->rlInfo.rlArray; CFIndex i, c; for (i = 0, c = CFArrayGetCount(runloops); i+1 < c; i += 2) { if (CFEqual(CFArrayGetValueAtIndex(runloops, i), runLoop) && CFEqual(CFArrayGetValueAtIndex(runloops, i+1), runLoopMode)) { CFArrayRemoveValueAtIndex(runloops, i); CFArrayRemoveValueAtIndex(runloops, i); break; } } } else { CFRunLoopSourceRef rlSrc = CFFileDescriptorCreateRunLoopSource(CFGetAllocator(stream), fileStream->rlInfo.cffd, 0); CFRunLoopRemoveSource(runLoop, rlSrc, runLoopMode); CFRelease(rlSrc); } } #else if (fileStream->scheduled > 0) fileStream->scheduled--; #endif } static CFTypeRef fileCopyProperty(struct _CFStream *stream, CFStringRef propertyName, void *info) { CFTypeRef result = NULL; _CFFileStreamContext *fileStream = (_CFFileStreamContext *)info; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { // NOTE that this does a lseek of 0 from the current location in // order to populate the offset field which will then be used to // create the resulting value. if (!__CFBitIsSet(fileStream->flags, APPEND) && fileStream->fd != -1) { fileStream->offset = lseek(fileStream->fd, 0, SEEK_CUR); } if (fileStream->offset != -1) { result = CFNumberCreate(CFGetAllocator((CFTypeRef)stream), kCFNumberSInt64Type, &(fileStream->offset)); } #if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX } else if (CFEqual(propertyName, _kCFStreamPropertyFileNativeHandle)) { int fd = fileStream->fd; if (fd != -1) { result = CFDataCreate(CFGetAllocator((CFTypeRef) stream), (const uint8_t *)&fd, sizeof(fd)); } #endif } return result; } static Boolean fileSetProperty(struct _CFStream *stream, CFStringRef prop, CFTypeRef val, void *info) { Boolean result = FALSE; _CFFileStreamContext *fileStream = (_CFFileStreamContext *)info; if (CFEqual(prop, kCFStreamPropertyAppendToFile) && CFGetTypeID(stream) == CFWriteStreamGetTypeID() && CFWriteStreamGetStatus((CFWriteStreamRef)stream) == kCFStreamStatusNotOpen) { if (val == kCFBooleanTrue) { __CFBitSet(fileStream->flags, APPEND); fileStream->offset = -1; // Can't offset and append on the stream } else { __CFBitClear(fileStream->flags, APPEND); } result = TRUE; } else if (CFEqual(prop, kCFStreamPropertyFileCurrentOffset)) { if (!__CFBitIsSet(fileStream->flags, APPEND)) { result = CFNumberGetValue((CFNumberRef)val, kCFNumberSInt64Type, &(fileStream->offset)); } if ((fileStream->fd != -1) && (lseek(fileStream->fd, fileStream->offset, SEEK_SET) == -1)) { result = FALSE; } } return result; } static void *fileCreate(struct _CFStream *stream, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; _CFFileStreamContext *newCtxt = (_CFFileStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFFileStreamContext), 0); if (!newCtxt) return NULL; newCtxt->url = ctxt->url; if (newCtxt->url) { CFRetain(newCtxt->url); } newCtxt->fd = ctxt->fd; #ifdef REAL_FILE_SCHEDULING newCtxt->rlInfo.cffd = NULL; #else newCtxt->scheduled = 0; #endif newCtxt->flags = 0; newCtxt->offset = -1; return newCtxt; } static void fileFinalize(struct _CFStream *stream, void *info) { _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; if (ctxt->fd > 0) { #ifdef REAL_FILE_SCHEDULING if (ctxt->rlInfo.cffd) { CFFileDescriptorInvalidate(ctxt->rlInfo.cffd); CFRelease(ctxt->rlInfo.cffd); ctxt->rlInfo.cffd = NULL; } #endif close(ctxt->fd); #ifdef REAL_FILE_SCHEDULING } else if (ctxt->rlInfo.rlArray) { CFRelease(ctxt->rlInfo.rlArray); #endif } if (ctxt->url) { CFRelease(ctxt->url); } CFAllocatorDeallocate(CFGetAllocator(stream), ctxt); } static CFStringRef fileCopyDescription(struct _CFStream *stream, void *info) { // This needs work _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info; if (ctxt->url) { return CFCopyDescription(ctxt->url); } else { return CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("fd = %d"), ctxt->fd); } } /* CFData stream callbacks */ typedef struct { CFDataRef data; // Mutable if the stream was constructed writable const UInt8 *loc; // Current location in the file Boolean scheduled; char _padding[3]; } _CFReadDataStreamContext; #define BUF_SIZE 1024 typedef struct _CFStreamByteBuffer { UInt8 *bytes; CFIndex capacity, length; struct _CFStreamByteBuffer *next; } _CFStreamByteBuffer; typedef struct { _CFStreamByteBuffer *firstBuf, *currentBuf; CFAllocatorRef bufferAllocator; Boolean scheduled; char _padding[3]; } _CFWriteDataStreamContext; static Boolean readDataOpen(struct _CFStream *stream, CFStreamError *errorCode, Boolean *openComplete, void *info) { _CFReadDataStreamContext *dataStream = (_CFReadDataStreamContext *)info; if (dataStream->scheduled) { if (CFDataGetLength(dataStream->data) != 0) { CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventHasBytesAvailable, NULL); } else { CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventEndEncountered, NULL); } } errorCode->error = 0; *openComplete = TRUE; return TRUE; } static void readDataSchedule(struct _CFStream *stream, CFRunLoopRef rl, CFStringRef rlMode, void *info) { _CFReadDataStreamContext *dataStream = (_CFReadDataStreamContext *)info; if (dataStream->scheduled == FALSE) { dataStream->scheduled = TRUE; if (CFReadStreamGetStatus((CFReadStreamRef)stream) != kCFStreamStatusOpen) return; if (CFDataGetBytePtr(dataStream->data) + CFDataGetLength(dataStream->data) > dataStream->loc) { CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventHasBytesAvailable, NULL); } else { CFReadStreamSignalEvent((CFReadStreamRef)stream, kCFStreamEventEndEncountered, NULL); } } } static CFIndex dataRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength, CFStreamError *error, Boolean *atEOF, void *info) { _CFReadDataStreamContext *dataCtxt = (_CFReadDataStreamContext *)info; const UInt8 *bytePtr = CFDataGetBytePtr(dataCtxt->data); CFIndex length = CFDataGetLength(dataCtxt->data); CFIndex bytesToCopy = bytePtr + length - dataCtxt->loc; if (bytesToCopy > bufferLength) { bytesToCopy = bufferLength; } if (bytesToCopy < 0) { bytesToCopy = 0; } if (bytesToCopy != 0) { memmove(buffer, dataCtxt->loc, bytesToCopy); dataCtxt->loc += bytesToCopy; } error->error = 0; *atEOF = (dataCtxt->loc < bytePtr + length) ? FALSE : TRUE; if (dataCtxt->scheduled && !*atEOF) { CFReadStreamSignalEvent(stream, kCFStreamEventHasBytesAvailable, NULL); } return bytesToCopy; } static const UInt8 *dataGetBuffer(CFReadStreamRef stream, CFIndex maxBytesToRead, CFIndex *numBytesRead, CFStreamError *error, Boolean *atEOF, void *info) { _CFReadDataStreamContext *dataCtxt = (_CFReadDataStreamContext *)info; const UInt8 *bytePtr = CFDataGetBytePtr(dataCtxt->data); CFIndex length = CFDataGetLength(dataCtxt->data); CFIndex bytesToRead = bytePtr + length - dataCtxt->loc; if (bytesToRead > maxBytesToRead) { *numBytesRead = maxBytesToRead; *atEOF = FALSE; } else { *numBytesRead = bytesToRead; *atEOF = TRUE; } error->error = 0; const UInt8 *buffer = dataCtxt->loc; dataCtxt->loc += *numBytesRead; if (dataCtxt->scheduled && !*atEOF) { CFReadStreamSignalEvent(stream, kCFStreamEventHasBytesAvailable, NULL); } return buffer; } static Boolean dataCanRead(CFReadStreamRef stream, void *info) { _CFReadDataStreamContext *dataCtxt = (_CFReadDataStreamContext *)info; return (CFDataGetBytePtr(dataCtxt->data) + CFDataGetLength(dataCtxt->data) > dataCtxt->loc) ? TRUE : FALSE; } static Boolean writeDataOpen(struct _CFStream *stream, CFStreamError *errorCode, Boolean *openComplete, void *info) { _CFWriteDataStreamContext *dataStream = (_CFWriteDataStreamContext *)info; if (dataStream->scheduled) { if (dataStream->bufferAllocator != kCFAllocatorNull || dataStream->currentBuf->capacity > dataStream->currentBuf->length) { CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventCanAcceptBytes, NULL); } else { CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventEndEncountered, NULL); } } errorCode->error = 0; *openComplete = TRUE; return TRUE; } static void writeDataSchedule(struct _CFStream *stream, CFRunLoopRef rl, CFStringRef rlMode, void *info) { _CFWriteDataStreamContext *dataStream = (_CFWriteDataStreamContext *)info; if (dataStream->scheduled == FALSE) { dataStream->scheduled = TRUE; if (CFWriteStreamGetStatus((CFWriteStreamRef)stream) != kCFStreamStatusOpen) return; if (dataStream->bufferAllocator != kCFAllocatorNull || dataStream->currentBuf->capacity > dataStream->currentBuf->length) { CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventCanAcceptBytes, NULL); } else { CFWriteStreamSignalEvent((CFWriteStreamRef)stream, kCFStreamEventEndEncountered, NULL); } } } static CFIndex dataWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength, CFStreamError *errorCode, void *info) { _CFWriteDataStreamContext *dataStream = (_CFWriteDataStreamContext *)info; CFIndex result; CFIndex freeSpace = dataStream->currentBuf->capacity - dataStream->currentBuf->length; if (dataStream->bufferAllocator == kCFAllocatorNull && bufferLength > freeSpace) { errorCode->error = ENOMEM; errorCode->domain = kCFStreamErrorDomainPOSIX; return -1; } else { result = bufferLength; while (bufferLength > 0) { CFIndex amountToCopy = (bufferLength > freeSpace) ? freeSpace : bufferLength; if (freeSpace > 0) { memmove(dataStream->currentBuf->bytes + dataStream->currentBuf->length, buffer, amountToCopy); buffer += amountToCopy; bufferLength -= amountToCopy; dataStream->currentBuf->length += amountToCopy; } if (bufferLength > 0) { CFIndex bufSize = BUF_SIZE > bufferLength ? BUF_SIZE : bufferLength; _CFStreamByteBuffer *newBuf = (_CFStreamByteBuffer *)CFAllocatorAllocate(dataStream->bufferAllocator, sizeof(_CFStreamByteBuffer) + bufSize, 0); if (newBuf == NULL) { errorCode->error = ENOMEM; errorCode->domain = kCFStreamErrorDomainPOSIX; return -1; } else { newBuf->bytes = (UInt8 *)(newBuf + 1); newBuf->capacity = bufSize; newBuf->length = 0; newBuf->next = NULL; dataStream->currentBuf->next = newBuf; dataStream->currentBuf = newBuf; freeSpace = bufSize; } } } errorCode->error = 0; } if (dataStream->scheduled && (dataStream->bufferAllocator != kCFAllocatorNull || dataStream->currentBuf->capacity > dataStream->currentBuf->length)) { CFWriteStreamSignalEvent(stream, kCFStreamEventCanAcceptBytes, NULL); } return result; } static Boolean dataCanWrite(CFWriteStreamRef stream, void *info) { _CFWriteDataStreamContext *dataStream = (_CFWriteDataStreamContext *)info; if (dataStream->bufferAllocator != kCFAllocatorNull) return TRUE; if (dataStream->currentBuf->capacity > dataStream->currentBuf->length) return TRUE; return FALSE; } static CFPropertyListRef dataCopyProperty(struct _CFStream *stream, CFStringRef propertyName, void *info) { _CFWriteDataStreamContext *dataStream = (_CFWriteDataStreamContext *)info; CFIndex size = 0; _CFStreamByteBuffer *buf; CFAllocatorRef alloc; UInt8 *bytes, *currByte; if (!CFEqual(propertyName, kCFStreamPropertyDataWritten)) return NULL; if (dataStream->bufferAllocator == kCFAllocatorNull) return NULL; alloc = dataStream->bufferAllocator; for (buf = dataStream->firstBuf; buf != NULL; buf = buf->next) { size += buf->length; } bytes = (UInt8 *)CFAllocatorAllocate(alloc, size, 0); currByte = bytes; for (buf = dataStream->firstBuf; buf != NULL; buf = buf->next) { memmove(currByte, buf->bytes, buf->length); currByte += buf->length; } return CFDataCreateWithBytesNoCopy(alloc, bytes, size, alloc); } static void *readDataCreate(struct _CFStream *stream, void *info) { _CFReadDataStreamContext *ctxt = (_CFReadDataStreamContext *)info; _CFReadDataStreamContext *newCtxt = (_CFReadDataStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFReadDataStreamContext), 0); if (!newCtxt) return NULL; newCtxt->data = (CFDataRef)CFRetain(ctxt->data); newCtxt->loc = CFDataGetBytePtr(newCtxt->data); newCtxt->scheduled = FALSE; return (void *)newCtxt; } static void readDataFinalize(struct _CFStream *stream, void *info) { _CFReadDataStreamContext *ctxt = (_CFReadDataStreamContext *)info; CFRelease(ctxt->data); CFAllocatorDeallocate(CFGetAllocator(stream), ctxt); } static CFStringRef readDataCopyDescription(struct _CFStream *stream, void *info) { return CFCopyDescription(((_CFReadDataStreamContext *)info)->data); } static void *writeDataCreate(struct _CFStream *stream, void *info) { _CFWriteDataStreamContext *ctxt = (_CFWriteDataStreamContext *)info; _CFWriteDataStreamContext *newCtxt; if (ctxt->bufferAllocator != kCFAllocatorNull) { if (ctxt->bufferAllocator == NULL) ctxt->bufferAllocator = CFAllocatorGetDefault(); CFRetain(ctxt->bufferAllocator); newCtxt = (_CFWriteDataStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFWriteDataStreamContext) + sizeof(_CFStreamByteBuffer) + BUF_SIZE, 0); newCtxt->firstBuf = (_CFStreamByteBuffer *)(newCtxt + 1); newCtxt->firstBuf->bytes = (UInt8 *)(newCtxt->firstBuf + 1); newCtxt->firstBuf->capacity = BUF_SIZE; newCtxt->firstBuf->length = 0; newCtxt->firstBuf->next = NULL; newCtxt->currentBuf = newCtxt->firstBuf; newCtxt->bufferAllocator = ctxt->bufferAllocator; newCtxt->scheduled = FALSE; } else { newCtxt = (_CFWriteDataStreamContext *)CFAllocatorAllocate(CFGetAllocator(stream), sizeof(_CFWriteDataStreamContext) + sizeof(_CFStreamByteBuffer), 0); newCtxt->firstBuf = (_CFStreamByteBuffer *)(newCtxt+1); newCtxt->firstBuf->bytes = ctxt->firstBuf->bytes; newCtxt->firstBuf->capacity = ctxt->firstBuf->capacity; newCtxt->firstBuf->length = 0; newCtxt->firstBuf->next = NULL; newCtxt->currentBuf = newCtxt->firstBuf; newCtxt->bufferAllocator = kCFAllocatorNull; newCtxt->scheduled = FALSE; } return (void *)newCtxt; } static void writeDataFinalize(struct _CFStream *stream, void *info) { _CFWriteDataStreamContext *ctxt = (_CFWriteDataStreamContext *)info; if (ctxt->bufferAllocator != kCFAllocatorNull) { _CFStreamByteBuffer *buf = ctxt->firstBuf->next, *next; while (buf != NULL) { next = buf->next; CFAllocatorDeallocate(ctxt->bufferAllocator, buf); buf = next; } CFRelease(ctxt->bufferAllocator); } CFAllocatorDeallocate(CFGetAllocator(stream), ctxt); } static CFStringRef writeDataCopyDescription(struct _CFStream *stream, void *info) { return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("<CFWriteDataContext %p>"), info); } static const struct _CFStreamCallBacksV1 fileCallBacks = {1, fileCreate, fileFinalize, fileCopyDescription, fileOpen, NULL, fileRead, NULL, fileCanRead, fileWrite, fileCanWrite, fileClose, fileCopyProperty, fileSetProperty, NULL, fileSchedule, fileUnschedule}; static struct _CFStream *_CFStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL, Boolean forReading) { _CFFileStreamContext fileContext; CFStringRef scheme = fileURL ? CFURLCopyScheme(fileURL) : NULL; if (!scheme || !CFEqual(scheme, CFSTR("file"))) { if (scheme) CFRelease(scheme); return NULL; } CFRelease(scheme); fileContext.url = fileURL; fileContext.fd = -1; return _CFStreamCreateWithConstantCallbacks(alloc, &fileContext, (struct _CFStreamCallBacks *)(&fileCallBacks), forReading); } CF_EXPORT CFReadStreamRef CFReadStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL) { return (CFReadStreamRef)_CFStreamCreateWithFile(alloc, fileURL, TRUE); } CF_EXPORT CFWriteStreamRef CFWriteStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL) { return (CFWriteStreamRef)_CFStreamCreateWithFile(alloc, fileURL, FALSE); } // CFReadStreamRef takes ownership of the fd, and will close() it CFReadStreamRef _CFReadStreamCreateFromFileDescriptor(CFAllocatorRef alloc, int fd) { _CFFileStreamContext fileContext; fileContext.url = NULL; fileContext.fd = fd; return (CFReadStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &fileContext, (struct _CFStreamCallBacks *)(&fileCallBacks), TRUE); } // CFWriteStreamRef takes ownership of the fd, and will close() it CFWriteStreamRef _CFWriteStreamCreateFromFileDescriptor(CFAllocatorRef alloc, int fd) { _CFFileStreamContext fileContext; fileContext.url = NULL; fileContext.fd = fd; return (CFWriteStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &fileContext, (struct _CFStreamCallBacks *)(&fileCallBacks), FALSE); } static const struct _CFStreamCallBacksV1 readDataCallBacks = {1, readDataCreate, readDataFinalize, readDataCopyDescription, readDataOpen, NULL, dataRead, dataGetBuffer, dataCanRead, NULL, NULL, NULL, NULL, NULL, NULL, readDataSchedule, NULL}; static const struct _CFStreamCallBacksV1 writeDataCallBacks = {1, writeDataCreate, writeDataFinalize, writeDataCopyDescription, writeDataOpen, NULL, NULL, NULL, NULL, dataWrite, dataCanWrite, NULL, dataCopyProperty, NULL, NULL, writeDataSchedule, NULL}; CF_EXPORT CFReadStreamRef CFReadStreamCreateWithBytesNoCopy(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator) { _CFReadDataStreamContext ctxt; CFReadStreamRef result; ctxt.data = CFDataCreateWithBytesNoCopy(alloc, bytes, length, bytesDeallocator); result = (CFReadStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &ctxt, (struct _CFStreamCallBacks *)(&readDataCallBacks), TRUE); CFRelease(ctxt.data); return result; } /* This needs to be exported to make it callable from Foundation. */ CF_EXPORT CFReadStreamRef CFReadStreamCreateWithData(CFAllocatorRef alloc, CFDataRef data) { _CFReadDataStreamContext ctxt; CFReadStreamRef result = NULL; CFDataRef copiedData = CFDataCreateCopy(alloc, data); ctxt.data = copiedData; result = (CFReadStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &ctxt, (struct _CFStreamCallBacks *)(&readDataCallBacks), TRUE); CFRelease(copiedData); return result; } CFWriteStreamRef CFWriteStreamCreateWithBuffer(CFAllocatorRef alloc, UInt8 *buffer, CFIndex bufferCapacity) { _CFStreamByteBuffer buf; _CFWriteDataStreamContext ctxt; buf.bytes = buffer; buf.capacity = bufferCapacity; buf.length = 0; buf.next = NULL; ctxt.firstBuf = &buf; ctxt.currentBuf = ctxt.firstBuf; ctxt.bufferAllocator = kCFAllocatorNull; return (CFWriteStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &ctxt, (struct _CFStreamCallBacks *)(&writeDataCallBacks), FALSE); } CF_EXPORT CFWriteStreamRef CFWriteStreamCreateWithAllocatedBuffers(CFAllocatorRef alloc, CFAllocatorRef bufferAllocator) { _CFWriteDataStreamContext ctxt; ctxt.firstBuf = NULL; ctxt.currentBuf = NULL; ctxt.bufferAllocator = bufferAllocator; return (CFWriteStreamRef)_CFStreamCreateWithConstantCallbacks(alloc, &ctxt, (struct _CFStreamCallBacks *)(&writeDataCallBacks), FALSE); } #undef BUF_SIZE
Investigators have arrested the driver of the bus that crashed into an overpass at the Miami International Airport nearly a year ago, killing three people and injuring dozens of others, Miami-Dade Police said. Ramon Ferreiro, 47, of Miami, was arrested on Thursday and charged with three counts of vehicular homicide for the December 1, 2012 wreck that killed three and injured others traveling to West Palm Beach for a gathering of Jehovah's Witnesses. According to investigators, Ferreiro was not familiar with the surrounding areas of the airport and mistakenly entered the lower concourse where the bus did not meet the height requirements. The 12-foot-high vehicle smashed into a concrete overpass that had only an 8-foot-6-inch clearance, police said. One man, Serafin Castillo, 86, of Miami, died at the scene. Francisco Urana, 56, and Gliceria Garcia, 75, both of Miami, died from their injuries at a hospital. A total of 31 passengers were transported to area hospitals. The driver sustained minor injuries. The bus had been chartered by the church congregation and was headed to West Palm Beach. After taking witness statements and seeing crash reconstruction information, investigators concluded that Ferreiro was traveling 33 MHP in a 15 MPH speed zone. Ferreiro also drove past eight low clearance warning signs equipped with amber lights, according to an arrest warrant. Passengers on the bus warned Ferreiro about his location, but he kept driving until the crash happened, according to the warrant. Investigators noted that there was no indication Ferreiro applied the brakes or tried any evasive actions prior to slamming into the overpass, according to the warrant. Ferreiro's actions "showed a willful and wanton disregard for the safety of his own passengers," Miami-Dade Police Detective George Wilhelm wrote in his report. Records show Ferreiro was released from jail in Miami-Dade after posting a $50,000 bond.
<gh_stars>1-10 # Chapter 4. 이터레이터와 제너레이터 # 4.1 수동으로 이터레이터 소비 # ▣ 문제 : 순환 가능한 아이템에 접근할 때 for 순환문을 사용하고 싶지 않다. # ▣ 해결 : 수동으로 이터레이터를 소비하려면 next() 함수를 사용하고 StopIteration 예외를 처리하기 위한 코드를 직접 작성한다. with open('files/somefile.txt', 'r') as f: try: while True: line = next(f) print(line, end='') except StopIteration: pass with open('files/somefile.txt', 'r') as f: while True: line = next(f, None) if line is None: break print(line, end='') # ▣ 토론 : 대개의 경우 순환에 for 문을 사용하지만 보다 더 정교한 조절이 필요한 때도 있다. # 기저에서 어떤 동작이 일어나는지 정확히 알아둘 필요가 있다. items = [1, 2, 3] it = iter(items) print(next(it)) print(next(it)) print(next(it)) print(next(it)) # 4.2 델리게이팅 순환 # ▣ 문제 : 리스트, 튜플 등 순환 가능한 객체를 담은 사용자 정의 컨테이너를 만들었다. # 이 컨테이너에 사용 가능한 이터레이터를 만들고 싶다. # ▣ 해결 : 일반적으로 컨테이너 순환에 사용할 __iter__() 메소드만 정의해 주면 된다. class Node: def __init__(self, value): self._value = value self._children = [] def __repr__(self): return 'Node({!r})'.format(self._value) def add_child(self, node): self._children.append(node) def __iter__(self): return iter(self._children) if __name__ == '__main__': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) for ch in root: print(ch) # ▣ 토론 : 파이썬의 이터레이터 프로토콜은 __iter__() 가 실제 순환을 수행하기 위한 __next__() 메소드를 구현하는 특별 이터레이터 # 객체를 반환하기를 요구한다. # 4.3 제너레이터로 새로운 순환 패턴 생성 # ▣ 문제 : 내장 함수(range(), reversed())와는 다른 동작을 하는 순환 패턴을 만들고 싶다. # ▣ 해결 : 새로운 순환 패턴을 만들고 싶다면, 제너레이터 함수를 사용해서 정의해야 한다. def frange(start, stop, increment): x = start while x < stop: yield x x += increment for n in frange(0, 4, 0.5): print(n) for n in frange(0, 1, 0.125): print(n) # ▣ 토론 : 내부의 yield 문의 존재로 인해 함수가 제너레이터가 되었다. # 일반 함수와는 다르게 제너레이터는 순환에 응답하기 위해 실행된다. def countdown(n): print('Starting to count from', n) while n > 0: yield n n -= 1 print('Done!') c = countdown(3) print(c) print(next(c)) print(next(c)) print(next(c)) print(next(c)) # 4.4 이터레이터 프로토콜 구현 # ▣ 문제 : 순환을 지원하는 객체를 만드는데, 이터레이터 프로토콜을 구현하는 쉬운 방법이 필요하다. # ▣ 해결 : 객체에 대한 순환을 가장 쉽게 구현하는 방법은 제너레이터 함수를 사용하는 것이다. # 노드를 깊이-우선 패턴으로 순환하는 이터레이터를 구현하고 싶다면 다음 코드를 참고한다. class Node: def __init__(self, value): self._value = value self._children = [] def __repr__(self): return 'Node({!r})'.format(self._value) def add_child(self, node): self._children.append(node) def __iter__(self): return iter(self._children) def depth_first(self): yield self for c in self: yield from c.depth_first() if __name__ == '__main__': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) child1.add_child(Node(3)) child1.add_child(Node(4)) child2.add_child(Node(5)) for ch in root.depth_first(): print(ch) # 4.5 역방향 순환 # ▣ 문제 : 시퀀스 아이템을 역방향으로 순환하고 싶다. # ▣ 해결 : 내장 함수 reversed() 를 사용한다. a = [1, 2, 3, 4] for x in reversed(a): print(x) # - 역방향 순환은 객체가 __reversed__() 특별 메소드를 구현하고 있거나 크기를 알 수 있는 경우에만 가능하다. # 두 조건 중에서 아무것도 만족하지 못하면 객체를 먼저 리스트로 변환해야 한다. f = open('files/somefile.txt') for line in reversed(list(f)): print(line, end='') # - 순환 가능 객체를 리스트로 변환할 때 많은 메모리가 필요하다. # 4.6 추가 상태를 가진 제너레이터 함수 정의 # ▣ 문제 : 제너레이터 함수를 정의하고 싶지만, 사용자에게 노출할 추가적인 상태를 넣고 싶다. # ▣ 해결 : 사용자에게 추가 상태를 노출하는 제너레이터를 원할 때, __iter__() 메소드에 제너레이터 함수 코드를 넣어서 쉽게 클래스로 # 구현할 수 있다. from collections import deque class linehistory: def __init__(self, lines, histlen=3): self.lines = lines self.history = deque(maxlen=histlen) def __iter__(self): for lineno, line in enumerate(self.lines, 1): # enumerate(self.lines, 1) 함수의 출력값 : (줄 번호, 줄 내용), 1번부터 번호 출력 self.history.append((lineno, line)) yield line def clear(self): self.history.clear() with open('files/somefile.txt') as f: lines = linehistory(f) for line in lines: if 'python' in line: for lineno, hline in lines.history: print('{}:{}'.format(lineno, hline), end='') # ▣ 토론 : 제너레이터를 사용하면 모든 작업을 함수만으로 하려는 유혹에 빠지기 쉽다. # 만약 제너레이터 함수가 프로그램의 다른 부분과 일반적이지 않게 상호작용해야 할 경우 코드가 꽤 복잡해질 수 있다. # 이럴 때는 앞에서 본 대로 클래스 정의만을 사용한다. f = open('files/somefile.txt') lines = linehistory(f) next(lines) # __iter__ 메서드가 iter 객체를 리턴하지 않아 next 메소드가 호출되지 않는다. it = iter(lines) next(it) next(it) # 4.7 이터레이터의 일부 얻기 # ▣ 문제 : 이터레이터가 만드는 데이터의 일부를 얻고 싶지만, 일반적인 자르기 연산자가 동작하지 않는다. # ▣ 해결 : 이터레이터와 제너레이터의 일부를 얻는 데는 itertools.islice() 함수가 가장 이상적이다. def count(n): while True: yield n n += 1 c = count(0) print(c[10:20]) # 제너레이터는 슬라이스 연산자가 동작하지 않는다. import itertools for x in itertools.islice(c, 10 ,20): print(x) # ▣ 토론 : 이터레이터와 제너레이터는 일반적으로 일부를 잘라낼 수 없다. 왜냐하면 데이터의 길이를 알 수 없기 때문이다. # islice() 의 실행 결과는 원하는 아이템의 조각을 생성하는 이터레이터지만, 이는 시작 인덱스까지 모든 아이템을 소비하고 # 버리는 식으로 수행한다. 그리고 그 뒤의 아이템은 마지막 인덱스를 만날 때까지 islice 객체가 생성한다. # 4.8 순환 객체 첫 번째 부분 건너뛰기 # ▣ 문제 : 순환 객체의 아이템을 순환하려고 하는데, 처음 몇가지 아이템에는 관심이 없어 건너뛰고 싶다. # ▣ 해결 : itertools 모듈이 이 용도로 사용할 수 있는 몇 가지 함수가 있다. 첫 번째는 itertools.dropwhile() 함수이다. # 이 함수를 사용하려면, 함수와 순환 객체를 넣으면 된다. 반환된 이터레이터는 넘겨준 함수가 True 를 반환하는 동안은 # 시퀀스의 첫 번째 아이템을 무시한다. with open('files/somefile.txt') as f: for line in f: print(line, end='') from itertools import dropwhile with open('files/somefile.txt') as f: for line in dropwhile(lambda line: line.startswith('#'), f): print(line, end='') from itertools import islice items = ['a', 'b', 'c', 1, 4, 10, 15] for x in islice(items, 3, None): print(x) # ▣ 토론 : dropwhile() 과 islice() 함수는 다음과 같이 복잡한 코드를 작성하지 않도록 도와준다. with open('files/somefile.txt') as f: # 처음 주석을 건너뛴다. while True: line = next(f, '') if not line.startswith('#'): break # 남아 있는 라인을 처리한다. while line: # 의미 있는 라인으로 치환한다. print(line, end='') line = next(f, None) # - 파일 전체에 걸쳐 주석으로 시작하는 모든 라인을 필터링 with open('files/somefile.txt') as f: lines = (line for line in f if not line.startswith('#')) for line in lines: print(line, end='') # 4.9 가능한 모든 순열과 조합 순환 # ▣ 문제 : 아이템 컬렉션에 대해 가능한 모든 순열과 조합을 순환하고 싶다. # ▣ 해결 : itertools 모듈은 이와 관련 있는 세 함수를 제공한다. # - itertools.permutations() : 아이템 컬렉션을 받아 가능한 모든 순열을 튜플 시퀀스로 생성 items = ['a', 'b', 'c'] from itertools import permutations for p in permutations(items): print(p) for p in permutations(items, 2): # 특정 길이의 순열을 원하는 경우 print(p) # - itertools.combinations() : 입력 받은 아이템의 가능한 조합을 생성 # 조합의 경우 실제 요소의 순서는 고려하지 않는다 from itertools import combinations for c in combinations(items, 3): print(c) for c in combinations(items, 2): print(c) # - itertools.combinations_with_replacement() : 같은 아이템을 두 번 이상 선택할 수 있게 한다. from itertools import combinations_with_replacement for c in combinations_with_replacement(items, 3): print(c) # ▣ 토론 : 이번 레시피에서 itertools 모듈의 편리한 도구 중 몇 가지만을 다루었다. # 사실 순열이나 조합을 순환하는 코드를 직접 작성할 수도 있겠지만, 그렇게 하려면 꽤 많은 고민을 해야 한다. # 순환과 관련해서 복잡한 문제에 직면한다면 우선 itertools 부터 살펴보는 것이 좋다. # 4.10 인덱스-값 페어 시퀀스 순환 # ▣ 문제 : 시퀀스를 순환하려고 한다. 이때 어떤 요소를 처리하고 있는지 번호를 알고 싶다. # ▣ 해결 : 내장 함수 enumerate() 를 사용하면 간단히 해결할 수 있다. my_list = ['a', 'b', 'c'] for idx, val in enumerate(my_list): print(idx, val) # - 출력 시 번호를 1번부터 시작 my_list = ['a', 'b', 'c'] for idx, val in enumerate(my_list, 1): print(idx, val) def parse_data(filename): with open('PythonCookBook/files/'+filename, 'rt') as f: for lineno, line in enumerate(f, 1): fields = line.split() try: count = int(fields[0]) except ValueError as e: print('Line {}: Parse error: {}'.format(lineno, e)) parse_data('somefile.txt') # - enumerate() 는 특정 값의 출현을 위한 오프셋 추적에 활용하기 좋다. from collections import defaultdict word_summary = defaultdict(list) with open('PythonCookBook/files/somefile.txt', 'r') as f: lines = f.readlines() for idx, line in enumerate(lines): # 현재 라인에 단어 리스트를 생성 words = [w.strip().lower() for w in line.split()] for word in words: word_summary[word].append(idx) print(word_summary) # ▣ 토론 : 카운터 변수를 스스로 다루는 것에 비해 enumerate() 를 사용하는 것이 훨씬 보기 좋다. lineno = 1 for line in f: lineno += 1 for lineno, line in enumerate(f): print(lineno) # - 한 번 더 풀어 줘야 하는 튜플의 시퀀스에 enumerate() 를 사용하는 경우 data = [(1, 2), (3, 4), (5, 6), (7, 8)] for n, (x, y) in enumerate(data): # 올바른 방법 print(n, (x, y)) for n, x, y in enumerate(data): # 에러! print(n, (x, y)) # 4.11 여러 시퀀스 동시에 순환 # ▣ 문제 : 여러 시퀀스에 들어 있는 아이템을 동시에 순환하고 싶다. # ▣ 해결 : 여러 시퀀스를 동시에 순환하려면 zip() 함수를 사용한다. xpts = [1, 5, 4, 2, 10, 7] ypts = [101, 78, 37, 15, 62, 99] for x, y in zip(xpts, ypts): print(x, y) # - 순환은 한쪽 시퀀스의 모든 입력이 소비되었을 때 정지한다. 따라서 순환의 길이는 입력된 시퀀스 중 짧은 것과 같다. a = [1, 2, 3] b = ['w', 'x', 'y', 'z'] for i in zip(a, b): print(i) # - 긴 시퀀스를 기준으로 순환을 수행하려면 itertools.zip_longest() 를 사용한다. from itertools import zip_longest for i in zip_longest(a, b): print(i) for i in zip_longest(a, b, fillvalue=0): print(i) # ▣ 토론 : zip() 은 데이터를 묶어야 할 때 주로 사용한다. headers = ['name', 'shares', 'price'] values = ['ACME', 100, 490.1] s = dict(zip(headers, values)) # zip() 을 사용해서 두 값을 딕셔너리로 생성 for name, val in zip(headers, values): print(name, '=', val) # - zip() 에 시퀀스를 두 개 이상 입력할 수 있다. a = [1, 2, 3] b = [10, 11, 12] c = ['x', 'y', 'z'] for i in zip(a, b, c): print(i) # - zip() 이 결과적으로 이터레이터를 생성한다는 점을 기억하자. 묶은 값이 저장된 리스트가 필요하다면 list() 함수를 사용한다. zip(a, b) list(zip(a, b)) # 4.12 서로 다른 컨테이너 아이템 순환 # ▣ 문제 : 여러 객체에 동일한 작업을 수행해야 하지만, 객체가 서로 다른 컨테이너에 들어 있다. # ▣ 해결 : itertools.chain() 메소드로 이 문제를 간단히 해결할 수 있다. 타입이 달라도 가능하다. from itertools import chain a = [1, 2, 3, 4] b = ['x', 'y', 'z'] for x in chain(a, b): print(x) # - chain() 은 일반적으로 모든 아이템에 동일한 작업을 수행하고 싶지만 이 아이템이 서로 다른 세트에 포함되어 있을 때 사용한다. # 반복문을 두 번 사용하는 것보다 훨씬 보기 좋다. active_items = set(list([1,2,3,4])) inactive_items = [1,2,3,4] for item in chain(active_items, inactive_items): print(item) # ▣ 토론 : itertools.chain() 은 하나 혹은 그 이상의 순환 객체를 인자로 받는다. # 그리고 입력 받은 순환 객체 속 아이템을 차례대로 순환하는 이터레이터를 생성한다. # 큰 차이는 아니지만, 우선적으로 시퀀스를 하나로 합친 다음 순환하는 것보다 chain() 을 사용하는 것이 더 효율적이다. for x in a + b: # 비효율적(a 와 b 가 동일한 타입이어야 한다.) pass for x in chain(a, b): # 더 나은 방식 pass # 4.13 데이터 처리 파이프라인 생성 # ▣ 문제 : 데이터 처리를 데이터 처리 파이프라인과 같은 방식으로 순차적으로 처리하고 싶다. # 예를 들어, 처리해야 할 방대한 데이터가 있지만 메모리에 한꺼번에 들어가지 않는 경우에 적용할 수 있다. # ▣ 해결 : 제너레이터 함수를 사용하는 것이 처리 파이프라인을 구현하기에 좋다. import os import fnmatch import gzip import bz2 import re def gen_find(filepat, top): ''' 디렉터리 트리에서 와일드 카드 패턴에 매칭하는 모든 파일 이름을 찾는다. ''' for path, dirlist, filelist in os.walk(top): # walk() : 파일 시스템 경로, 디렉토리 리스트, 파일 리스트를 트리 탐색으로 가져오는 함수 for name in fnmatch.filter(filelist, filepat): # filter() : 패턴에 해당하는 파일을 걸러내는 함수 yield os.path.join(path, name) # join() : 여러개의 경로를 합치는 함수 def gen_opener(filenames): ''' 파일 이름 시퀀스를 하나씩 열어 파일 객체를 생성한다. 다음 순환으로 넘어가는 순간 파일을 닫는다. ''' for filename in filenames: if filename.endswith('.gz'): f = gzip.open(filename, 'rt') elif filename.endswith('.bz2'): f = bz2.open(filename, 'rt') else: f = open(filename, 'rt') yield f f.close() def gen_concatenate(iterators): ''' 이터레이터 시퀀스를 합쳐 하나의 시퀀스로 만든다. ''' for it in iterators: yield from it def gen_grep(pattern, lines): ''' 라인 시퀀스에서 정규식 패턴을 살펴본다. ''' pat = re.compile(pattern) for line in lines: if pat.search(line): yield line lognames = gen_find('*.txt', 'PythonCookBook/files/') files = gen_opener(lognames) lines = gen_concatenate(files) pylines = gen_grep('(?i)Python', lines) for line in pylines: print(line) # - 전송한 바이트 수를 찾고 그 총합을 구함 bytecolumn = (line.rsplit(None, 1)[1] for line in pylines) # rsplit 오른쪽부터 처리 print([x for x in bytecolumn]) bytes = (int(x) for x in bytecolumn if x != '-') print('Total', sum(bytes)) # ▣ 토론 : 파이프라인으로 데이터를 처리하는 방식은 파싱, 실시간 데이터 읽기, 주기적 폴링 등 다른 문제에도 사용할 수 있다. # 코드를 이해할 때, yield 문이 데이터 생성자처럼 동작하고 for 문은 데이터 소비자처럼 동작한다는 점이 중요하다. # 제너레이터가 쌓이면, 각 yield 가 순환을 하며 데이터의 아이템 하나를 파이프라인의 다음 단계로 넘긴다. # 마지막 예제에서 sum() 함수가 실질적으로 프로그램을 운용하며 제너레이터 파이프라인에서 한 번에 하나씩 아이템을 꺼낸다. # 4.14 중첩 시퀀스 풀기 # ▣ 문제 : 중첩된 시퀀스를 합쳐 하나의 리스트로 만들고 싶다. # ▣ 해결 : 이 문제는 yield from 문이 있는 재귀 제너레이터를 만들어 쉽게 해결할 수 있다. from collections import Iterable def flatten(items, ignore_types=(str, bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x, ignore_types): yield from flatten(x) # flatten 호출시 수행된 yield 값들을 모두 가져옴 else: yield x items = [1, 2, [3, 4, [5, 6], 7], 8] for x in flatten(items): print(x) # - 앞의 코드에서 isinstance(x, Iterable) 은 아이템이 순환 가능한 것인지 확인한다. # 순환이 가능하다면 yield from 으로 모든 값을 하나의 서브루틴으로 분출한다. # 결과적으로 중첩되지 않은 시퀀스 하나가 만들어진다. items = ['Dave', 'Paula', ['Thomas', 'Lewis']] for x in flatten(items): print(x) # - 추가적으로 전달 가능한 인자 ignore_types 와 not isinstance(x, ignore_types) 로 문자열과 바이트가 순환 가능한 것으로 # 해석되지 않도록 했다. # 이렇게 해야만 리스트에 담겨있는 문자열을 전달했을 때 문자를 하나하나 펼치지 않고 문자열 단위로 전개한다. # ▣ 토론 : 서브루틴으로써 다른 제너레이터를 호출할 때 yield from 을 사용하면 편리하다. # 이 구문을 사용하지 않으면 추가적인 for 문이 있는 코드를 작성해야 한다. def flatten(items, ignore_types=(str, bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x, ignore_types): for i in flatten(x): yield i else: yield x # 4.15 정렬된 여러 시퀀스를 병합 후 순환 # ▣ 문제 : 정렬된 시퀀스가 여럿 있고, 이들을 하나로 합친 후 정렬된 시퀀스를 순환하고 싶다. # ▣ 해결 : 간단하다. heapq.merge() 함수를 사용하면 된다. import heapq a = [1, 4, 7, 10] b = [2, 5, 6, 11] for c in heapq.merge(a, b): print(c) # ▣ 토론 : heapq.merge 는 아이템에 순환적으로 접근하며 제공한 시퀀스를 한꺼번에 읽지 않는다. # 따라서 아주 긴 시퀀스도 별다른 무리 없이 사용할 수 있다. import heapq with open('sorted_file_1', 'rt') as file1, open('sorted_file_2', 'rt') as file2, open('merged_file', 'wt') as outf: for line in heapq.merge(file1, file2): outf.write(line) # 4.16 무한 while 순환문을 이터레이터로 치환 # ▣ 문제 : 함수나 일반적이지 않은 조건 테스트로 인해 무한 while 순환문으로 데이터에 접근하는 코드를 만들었다. # ▣ 해결 : 입출력과 관련 있는 프로그램에 일반적으로 다음과 같은 코드를 사용한다. # CHUNKSIZE = 8192 # # def reader(s): # while True: # data = s.recv(CHUNKSIZE) # if data == b'': # break # process_data(data) # # def reader(s): # for chunk in iter(lambda: s.recv(CHUNKSIZE), b''): # process_data(data) import sys f = open('PythonCookBook/files/somefile.txt') for chunk in iter(lambda: f.read(10), ''): # '' 를 만날때까지 파일 read 를 수행. n = sys.stdout.write(chunk) # ▣ 토론 : 내장 함수 iter() 의 기능은 거의 알려져 있지 않다. # 이 함수에는 선택적으로 인자 없는 호출 가능 객체와 종료 값을 입력으로 받는다. # 이렇게 사용하면 주어진 종료 값을 반환하기 전까지 무한히 반복해서 호출 가능 객체를 호출한다.
#pragma once #include <sys/time.h> uint64_t UsecTimestamp(void) { timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000000) + tv.tv_usec; }
<reponame>AY1920S2-CS2103-W14-3/main package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; /** * Adds a person to the address book. */ public class UndoCommand extends Command { public static final String COMMAND_WORD = "undo"; public static final String COMMAND_FUNCTION = "Undo the last entered command that changes the data. Listing and " + "sorting do not count as changing the data."; public static final String MESSAGE_USAGE = COMMAND_WORD + ": " + COMMAND_FUNCTION + "\n"; public static final String MESSAGE_SUCCESS = "Command Undone!"; public static final String MESSAGE_LAST_CHANGE = "Already At Last Change!"; /** * Creates an UndoCommand to add the specified {@code Person} */ public UndoCommand() { } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); if (model.undoStackSize() == 1) { throw new CommandException(MESSAGE_LAST_CHANGE); } String commandType = model.undo(); if (commandType.equals("ADDRESS")) { return new CommandResult(String.format(MESSAGE_SUCCESS)); } else if (commandType.equals("BIRTHDAY")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, false, false, false, true, false, false); } else if (commandType.equals("ASSIGNMENTS")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, false, true, false, false, false, false); } else if (commandType.equals("EVENTS")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, false, false, true, false, false, false); } else if (commandType.equals("RESTAURANTS")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, false, false, false, false, true, false); } else if (commandType.equals("USERPREF")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, false, false, false, false, false, false); } else if (commandType.equals("GETDETAIL")) { return new CommandResult(String.format(MESSAGE_SUCCESS), false, false, true, false, false, false, false, false); } else { throw new CommandException("BUG ENCOUNTERED, NOT SUPPOSED TO REACH HERE"); } } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof UndoCommand); } @Override public String toString() { return COMMAND_WORD; } }
import { Global } from "@emotion/react"; import type { GlobalProvider } from "@ladle/react"; import { globalStyle } from "../src/globalStyle"; export const Provider: GlobalProvider = ({ children }) => ( <> <Global styles={globalStyle} /> {children} </> );
<filename>atlas_grav/lib/DFRobot_PH/src/DFRobot_PH.cpp /* * file DFRobot_PH.cpp * @ https://github.com/DFRobot/DFRobot_PH * * Arduino library for Gravity: Analog pH Sensor / Meter Kit V2, SKU: SEN0161-V2 * * Copyright [DFRobot](http://www.dfrobot.com), 2018 * Copyright GNU Lesser General Public License * * version V1.0 * date 2018-04 */ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DFRobot_PH.h" //#include <EEPROM.h> #define EEPROM_write(address, p) {int i = 0; byte *pp = (byte*)&(p);for(; i < sizeof(p); i++) EEPROM.write(address+i, pp[i]);} #define EEPROM_read(address, p) {int i = 0; byte *pp = (byte*)&(p);for(; i < sizeof(p); i++) pp[i]=EEPROM.read(address+i);} #define PHVALUEADDR 0x00 //the start address of the pH calibration parameters stored in the EEPROM DFRobot_PH::DFRobot_PH() { this->_temperature = 25.0; this->_phValue = 7.0; this->_acidVoltage = 2512.0; //buffer solution 4.0 at 25C this->_neutralVoltage = 1879.0; //buffer solution 7.0 at 25C this->_voltage = 1500.0; } DFRobot_PH::~DFRobot_PH() { } void DFRobot_PH::begin() { EEPROM_read(PHVALUEADDR, this->_neutralVoltage); //load the neutral (pH = 7.0)voltage of the pH board from the EEPROM Serial.print("_neutralVoltage:"); Serial.println(this->_neutralVoltage); if(EEPROM.read(PHVALUEADDR)==0xFF && EEPROM.read(PHVALUEADDR+1)==0xFF && EEPROM.read(PHVALUEADDR+2)==0xFF && EEPROM.read(PHVALUEADDR+3)==0xFF){ this->_neutralVoltage = 1500.0; // new EEPROM, write typical voltage EEPROM_write(PHVALUEADDR, this->_neutralVoltage); } EEPROM_read(PHVALUEADDR+4, this->_acidVoltage);//load the acid (pH = 4.0) voltage of the pH board from the EEPROM Serial.print("_acidVoltage:"); Serial.println(this->_acidVoltage); if(EEPROM.read(PHVALUEADDR+4)==0xFF && EEPROM.read(PHVALUEADDR+5)==0xFF && EEPROM.read(PHVALUEADDR+6)==0xFF && EEPROM.read(PHVALUEADDR+7)==0xFF){ this->_acidVoltage = 2032.44; // new EEPROM, write typical voltage EEPROM_write(PHVALUEADDR+4, this->_acidVoltage); } } float DFRobot_PH::readPH(float voltage, float temperature) { float slope = (7.0-4.0)/((this->_neutralVoltage-1500.0)/3.0 - (this->_acidVoltage-1500.0)/3.0); // two point: (_neutralVoltage,7.0),(_acidVoltage,4.0) float intercept = 7.0 - slope*(this->_neutralVoltage-1500.0)/3.0; //Serial.print("slope:"); //Serial.print(slope); //Serial.print(",intercept:"); //Serial.println(intercept); this->_phValue = slope*(voltage-1500.0)/3.0+intercept; //y = k*x + b return _phValue; } void DFRobot_PH::calibration(float voltage, float temperature,char* cmd) { this->_voltage = voltage; this->_temperature = temperature; strupr(cmd); phCalibration(cmdParse(cmd)); // if received Serial CMD from the serial monitor, enter into the calibration mode } void DFRobot_PH::calibration(float voltage, float temperature) { this->_voltage = voltage; this->_temperature = temperature; if(cmdSerialDataAvailable() > 0){ phCalibration(cmdParse()); // if received Serial CMD from the serial monitor, enter into the calibration mode } } boolean DFRobot_PH::cmdSerialDataAvailable() { char cmdReceivedChar; static unsigned long cmdReceivedTimeOut = millis(); while(Serial.available()>0){ if(millis() - cmdReceivedTimeOut > 500U){ this->_cmdReceivedBufferIndex = 0; memset(this->_cmdReceivedBuffer,0,(ReceivedBufferLength)); } cmdReceivedTimeOut = millis(); cmdReceivedChar = Serial.read(); if (cmdReceivedChar == '\n' || this->_cmdReceivedBufferIndex==ReceivedBufferLength-1){ this->_cmdReceivedBufferIndex = 0; strupr(this->_cmdReceivedBuffer); return true; }else{ this->_cmdReceivedBuffer[this->_cmdReceivedBufferIndex] = cmdReceivedChar; this->_cmdReceivedBufferIndex++; } } return false; } byte DFRobot_PH::cmdParse(const char* cmd) { byte modeIndex = 0; if(strstr(cmd, "ENTERPH") != NULL){ modeIndex = 1; }else if(strstr(cmd, "EXITPH") != NULL){ modeIndex = 3; }else if(strstr(cmd, "CALPH") != NULL){ modeIndex = 2; } return modeIndex; } byte DFRobot_PH::cmdParse() { byte modeIndex = 0; if(strstr(this->_cmdReceivedBuffer, "ENTERPH") != NULL){ modeIndex = 1; }else if(strstr(this->_cmdReceivedBuffer, "EXITPH") != NULL){ modeIndex = 3; }else if(strstr(this->_cmdReceivedBuffer, "CALPH") != NULL){ modeIndex = 2; } return modeIndex; } void DFRobot_PH::phCalibration(byte mode) { char *receivedBufferPtr; static boolean phCalibrationFinish = 0; static boolean enterCalibrationFlag = 0; switch(mode){ case 0: if(enterCalibrationFlag){ Serial.println(F(">>>Command Error<<<")); } break; case 1: enterCalibrationFlag = 1; phCalibrationFinish = 0; Serial.println(); Serial.println(F(">>>Enter PH Calibration Mode<<<")); Serial.println(F(">>>Please put the probe into the 4.0 or 7.0 standard buffer solution<<<")); Serial.println(); break; case 2: if(enterCalibrationFlag){ if((this->_voltage>1322)&&(this->_voltage<1678)){ // buffer solution:7.0{ Serial.println(); Serial.print(F(">>>Buffer Solution:7.0")); this->_neutralVoltage = this->_voltage; Serial.println(F(",Send EXITPH to Save and Exit<<<")); Serial.println(); phCalibrationFinish = 1; }else if((this->_voltage>1854)&&(this->_voltage<2210)){ //buffer solution:4.0 Serial.println(); Serial.print(F(">>>Buffer Solution:4.0")); this->_acidVoltage = this->_voltage; Serial.println(F(",Send EXITPH to Save and Exit<<<")); Serial.println(); phCalibrationFinish = 1; }else{ Serial.println(); Serial.print(F(">>>Buffer Solution Error Try Again<<<")); Serial.println(); // not buffer solution or faulty operation phCalibrationFinish = 0; } } break; case 3: if(enterCalibrationFlag){ Serial.println(); if(phCalibrationFinish){ if((this->_voltage>1322)&&(this->_voltage<1678)){ EEPROM_write(PHVALUEADDR, this->_neutralVoltage); }else if((this->_voltage>1854)&&(this->_voltage<2210)){ EEPROM_write(PHVALUEADDR+4, this->_acidVoltage); } Serial.print(F(">>>Calibration Successful")); }else{ Serial.print(F(">>>Calibration Failed")); } Serial.println(F(",Exit PH Calibration Mode<<<")); Serial.println(); phCalibrationFinish = 0; enterCalibrationFlag = 0; } break; } }
<filename>Space_Invaders/classes/Game/Sprites/Player.py import pygame from . import MovingObject, Bullet from .. import Direction class Player(MovingObject): # Static method to store sprites sprites = [] def __init__(self, sensitivity: int, game_width: int, game_height: int, initial_x: int, initial_y: int, init_life: int, fps: int, bullet_grp: pygame.sprite.Group(), bullet_direction: Direction, debug: bool = False, isAI: bool = False): """Main class for the player object""" # Store the items self.is_AI = isAI self.bullet_direction = bullet_direction # Call the superclass super().__init__(sensitivity, initial_x, initial_y, game_width, game_height, Player.sprites[-1], debug) # Scale the image to 50x50 self.scale(50 * game_width // 600, 50 * game_height // 800) # Invicibility when it just spawned self.invincible = fps # Player bullet group self.bullet_grp = bullet_grp # If the life is not valid set it to 3 by default if init_life <= 0: init_life = 3 # Initial amount of life self.init_life = init_life # Set rotation to None self.rotation = 0 # Store game variables self.fps = fps # Reset player character self.reset() def reset(self) -> None: """Reset the player stats to original stats""" # Reset life self.life = self.init_life # Reset shooting cooldown self.maxcooldown = self.fps // 2.5 # Keep track of bullet cooldown self.cooldown = 0 # Reset position self.x = self.initial_x self.y = self.initial_y # Reset the bullet power self.bullet_power = 1 # Rerender rect self.changed = True # Give player 1s invisibility self.invincible = self.fps def isInvincible(self) -> bool: """Check if the player is invincible""" return self.invincible > 0 def increase_bullet_power(self, inc: int): """Increase the player bullet power by inc""" self.bullet_power += inc def get_bullet_power(self) -> int: """Return the bullet power of the player""" return self.bullet_power def add_lifes(self, no: int) -> None: """Adds life to the player""" assert no > 0 self.life += no def isAI(self) -> bool: """Check if it is an ai instance of the Player""" return self.is_AI def on_cooldown(self) -> bool: """Check if shooting is on cooldown""" return self.cooldown > 0 def shoot(self) -> bool: """Lets the player shoot a bullet if the player is not on cooldown""" # If the player is not on cooldown if not self.on_cooldown(): # Add the bullet to the bullet group self.bullet_grp.add( Bullet(self.sensitivity * 1.5, self.get_center()[0], self.get_y(), self.bullet_direction, self.game_width, self.game_height, self.debug)) # Reset the cooldown self.cooldown = self.maxcooldown # Return True if the player has shot return True # Return false if player fails to shoot return False def move_up(self) -> None: """Do not allow the player to move up""" pass def move_down(self) -> None: """Do not allow the player to move down""" pass def move_left(self) -> None: """Move the player to the left""" # If the player is not at the leftmost part of the screen if self.x > self.image.get_width() // 8: # allow the player to move left super().move_left() # Otherwise print debug message elif self.debug: print("Hit left most") def move_right(self) -> None: """Move the player right""" # If the player is not at the right most if self.x <= self.game_width: # allow the player to move right super().move_right() # Otherwise print debug message elif self.debug: print("Hit right most") def is_destroyed(self) -> bool: """Returns whether the player is destroyed""" return self.get_lives() == 0 def destroy(self, lives: int = 1) -> None: """Destroys the ship 1 time""" # If the player is no invincible if not self.invincible: # Reduce the life of the player if self.life < lives: self.life = 0 else: self.life -= lives # Make the player invincible for 1 second self.invincible = self.fps def get_lives(self) -> int: """Get the number of lives left""" return self.life def rotate(self, angle: int): """Store the rotation to be updated when sprite changes""" # Store the angle rotation self.rotation = angle # Call the super rotate class method return super().rotate(self.rotation) def update(self) -> None: """Update the position of the player""" # If the player is invincible if self.invincible > 0: # Reduce invincibility amount self.invincible -= 1 # If the player gun is on cooldown if self.cooldown > 0: # Reduce cooldown self.cooldown -= 1 # Load the Image of the player based on his life self.image = Player.sprites[ self.get_lives() - 1 if self.get_lives() < len(Player.sprites) else len(Player.sprites) - 1] # Rotate the corresponding image self.rotate(self.rotation) # Scale the image to 50x50 self.scale(50 * self.game_width // 600, 50 * self.game_height // 800) # Call the super update return super().update()
package sonar.core.helpers; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fml.common.network.ByteBufUtils; import sonar.core.SonarCore; import sonar.core.api.nbt.IBufObject; import sonar.core.api.nbt.INBTObject; import sonar.core.api.nbt.INBTSyncable; import sonar.core.network.sync.ISyncPart; import sonar.core.network.sync.SyncableList; public class NBTHelper { /** cheats to add info to a TileEntity on place, without having a stack */ public static boolean setTileEntityNBT(World worldIn, @Nullable EntityPlayer player, BlockPos pos, NBTTagCompound fakeTag) { ItemStack stack = new ItemStack(Blocks.AIR, 1); stack.getTagCompound().setTag("BlockEntityTag", fakeTag); return ItemBlock.setTileEntityNBT(worldIn, player, pos, stack); } public static void readSyncParts(NBTTagCompound nbt, SyncType type, List<ISyncPart> syncableList) { for (ISyncPart part : syncableList) { if (part != null && part.canSync(type)) { part.readData(nbt, type); } } } public static void readSyncParts(NBTTagCompound nbt, SyncType type, SyncableList syncableList) { for (ISyncPart part : syncableList.getStandardSyncParts()) { if (part != null && part.canSync(type)) { part.readData(nbt, type); } } } public static NBTTagCompound writeSyncParts(NBTTagCompound nbt, SyncType type, List<ISyncPart> syncableList, boolean forceSync) { for (ISyncPart part : syncableList) { if (part != null && (forceSync || type.mustSync() || part.canSync(type))) { part.writeData(nbt, type); } } return nbt; } public static NBTTagCompound writeSyncParts(NBTTagCompound nbt, SyncType type, SyncableList syncableList, boolean forceSync) { for (ISyncPart part : (ArrayList<ISyncPart>) syncableList.getSyncList(type).clone()) { if (part != null && (forceSync || type.mustSync() || part.canSync(type))) { part.writeData(nbt, type); syncableList.onPartSynced(part); } } syncableList.onPartsSynced(); return nbt; } public static ISyncPart getSyncPartByID(ArrayList<ISyncPart> parts, int id) { String tag = String.valueOf(id); for (ISyncPart part : parts) { if (part != null && part.getTagName().equals(tag)) { return part; } } return null; } /** typically used for Fluid/item/energy stacks */ @Nullable public static <T extends INBTSyncable> T instanceNBTSyncable(Class<T> classType, NBTTagCompound tag) { T obj; try { (obj = classType.newInstance()).readData(tag, SyncType.SAVE); return obj; } catch (InstantiationException | IllegalAccessException e) { SonarCore.logger.error("FAILED TO CREATE NEW INSTANCE OF " + classType.getSimpleName()); } return null; } public static void readSyncedNBTObjectList(String tagName, NBTTagCompound tag, NBTRegistryHelper<? extends INBTObject> helper, List objectList) { if (tag.hasKey(tagName + "null")) { objectList = Collections.emptyList(); } else if (tag.hasKey(tagName)) { NBTTagList list = tag.getTagList(tagName, 10); if (objectList == null) { objectList = new ArrayList<>(); } for (int i = 0; i < list.tagCount(); i++) { NBTTagCompound compound = list.getCompoundTagAt(i); int slot = compound.getInteger("Slot"); boolean set = slot < objectList.size(); switch (compound.getByte("f")) { case 0: if (set) { objectList.set(slot, helper.readFromNBT(compound)); } else { objectList.add(slot, helper.readFromNBT(compound)); } break; case 1: long stored = compound.getLong("Stored"); if (stored != 0) { objectList.set(slot, helper.readFromNBT(compound)); } else { objectList.set(slot, null); } break; case 2: objectList.set(slot, null); break; } } } } public static NBTTagCompound writeSyncedNBTObjectList(String tagName, NBTTagCompound tag, NBTRegistryHelper helper, List objectList, List lastList) { if (objectList == null) { objectList = new ArrayList<>(); } if (lastList == null) { lastList = new ArrayList<>(); } NBTTagList list = new NBTTagList(); int size = Math.max(objectList.size(), lastList.size()); for (int i = 0; i < size; ++i) { INBTObject current = null; INBTObject last = null; if (i < objectList.size()) { current = (INBTObject) objectList.get(i); } if (i < lastList.size()) { last = (INBTObject) lastList.get(i); } NBTTagCompound compound = new NBTTagCompound(); if (current != null) { if (last != null) { if (!helper.areTypesEqual(current, last)) { compound.setByte("f", (byte) 0); lastList.set(i, current); helper.writeToNBT(compound, (INBTObject) objectList.get(i)); } } else { compound.setByte("f", (byte) 0); lastList.add(i, current); helper.writeToNBT(compound, (INBTObject) objectList.get(i)); } } else if (last != null) { lastList.set(i, null); compound.setByte("f", (byte) 2); } if (!compound.hasNoTags()) { compound.setInteger("Slot", i); list.appendTag(compound); } } if (list.tagCount() != 0) { tag.setTag(tagName, list); } return tag; } public static List<? extends INBTObject> readNBTObjectList(String tagName, NBTTagCompound tag, RegistryHelper<? extends INBTObject> helper) { List<INBTObject> objects = new ArrayList<>(); if (tag.hasKey(tagName)) { NBTTagList list = tag.getTagList(tagName, 10); for (int i = 0; i < list.tagCount(); i++) { NBTTagCompound compound = list.getCompoundTagAt(i); objects.add(readNBTObject(compound, helper)); } } return objects; } public static NBTTagCompound writeNBTObjectList(String tagName, NBTTagCompound tag, List<? extends INBTObject> objects) { if (objects == null || objects.isEmpty()) { return tag; } NBTTagList list = new NBTTagList(); for (INBTObject object : objects) { if (object != null) { NBTTagCompound compound = new NBTTagCompound(); writeNBTObject(object, compound); list.appendTag(compound); } } tag.setTag(tagName, list); return tag; } public static INBTObject readNBTObject(NBTTagCompound tag, RegistryHelper<? extends INBTObject> helper) { if (tag.hasKey("type")) { String type = tag.getString("type"); if (type.equals("NULLED")) { return null; } if (helper.getRegisteredObject(type) == null) { SonarCore.logger.warn("NBT ERROR: " + "Unregistered " + helper.registeryType() + ": " + type + " in " + helper.toString()); return null; } INBTObject filter = (INBTObject) helper.getRegisteredObject(type).instance(); filter.readFromNBT(tag); return filter; } else { return null; } } public static NBTTagCompound writeNBTObject(INBTObject object, NBTTagCompound tag) { if (object != null) { tag.setString("type", object.getName()); object.writeToNBT(tag); } else { tag.setString("type", "NULLED"); } return tag; } public static IBufObject readBufObject(ByteBuf buf, RegistryHelper<? extends IBufObject> helper) { if (buf.readBoolean()) { String type = ByteBufUtils.readUTF8String(buf); if (helper.getRegisteredObject(type) == null) { SonarCore.logger.warn("BYTE BUF: " + "Unregistered " + helper.registeryType() + ": " + type); return null; } IBufObject info = (IBufObject) helper.getRegisteredObject(type).instance(); info.readFromBuf(buf); return info; } else { return null; } } public static void writeBufObject(IBufObject object, ByteBuf buf) { if (object != null) { buf.writeBoolean(true); ByteBufUtils.writeUTF8String(buf, object.getName()); object.writeToBuf(buf); } else { buf.writeBoolean(false); } } /* public static void writeEnergyStorage(EnergyStorage storage, NBTTagCompound nbt) { NBTTagCompound energyTag = new NBTTagCompound(); storage.writeToNBT(energyTag); nbt.setTag("energyStorage", energyTag); } public static void readEnergyStorage(EnergyStorage storage, NBTTagCompound nbt) { if (nbt.hasKey("energyStorage")) { storage.readFromNBT(nbt.getCompoundTag("energyStorage")); } } */ public static void writeFluidToBuf(FluidStack stack, ByteBuf buf) { ByteBufUtils.writeUTF8String(buf, FluidRegistry.getFluidName(stack.getFluid())); buf.writeInt(stack.amount); if (stack.tag != null) { buf.writeBoolean(true); ByteBufUtils.writeTag(buf, stack.tag); } else { buf.writeBoolean(false); } } public static FluidStack readFluidFromBuf(ByteBuf buf) { String fluidName = ByteBufUtils.readUTF8String(buf); if (fluidName == null || FluidRegistry.getFluid(fluidName) == null) { return null; } FluidStack stack = new FluidStack(FluidRegistry.getFluid(fluidName), buf.readInt()); if (buf.readBoolean()) { stack.tag = ByteBufUtils.readTag(buf); } return stack; } public static void writeTankInfo(FluidTankInfo tank, NBTTagCompound nbt) { tank.fluid.writeToNBT(nbt); nbt.setInteger("capacity", tank.capacity); } public static FluidTankInfo readTankInfo(NBTTagCompound nbt) { return new FluidTankInfo(FluidStack.loadFluidStackFromNBT(nbt), nbt.getInteger("capacity")); } public static NBTTagCompound writeDoubleArray(NBTTagCompound tag, double[] array, String tagName) { NBTTagList list = new NBTTagList(); for (double d : array) { list.appendTag(new NBTTagDouble(d)); } tag.setTag(tagName, list); return tag; } public static double[] readDoubleArray(NBTTagCompound tag, String tagName, int size) { NBTTagList list = tag.getTagList(tagName, NBT.TAG_DOUBLE); double[] array = new double[size]; for (int i = 0; i < list.tagCount(); i++) { array[i] = list.getDoubleAt(i); } return array; } public enum SyncType { SAVE(0), DROP(2), SPECIAL(3), PACKET(4), DEFAULT_SYNC(1), SYNC_OVERRIDE(1), NONE(5); private int type; SyncType(int type) { this.type = type; } public int getSubType() { return type; } public boolean mustSync() { return this == SYNC_OVERRIDE || this == SAVE; } public boolean isType(SyncType... types) { for (SyncType type : types) { if (type.type == this.type) { return true; } } return false; } public static boolean isGivenType(SyncType current, SyncType... types) { if (current == null) { return false; } for (SyncType type : types) { if (type.type == current.type) { return true; } } return false; } } public void getAndCheck(Object obj, NBTTagCompound tag, String key, boolean shouldCheck) { if (!shouldCheck || tag.hasKey(key)) { obj = readNBTBase(tag, tag.getTag(key).getId(), key); } } public static NBTTagCompound writeNBTBase(NBTTagCompound nbt, int type, Object object, String tagName) { if (object == null) { SonarCore.logger.error("NBT ERROR: Can't write NULL"); return nbt; } if (tagName == null) { SonarCore.logger.error("NBT ERROR: Can't write with no TAG NAME"); return nbt; } switch (type) { case NBT.TAG_END: nbt.setBoolean(tagName, (Boolean) object); break; case NBT.TAG_BYTE: nbt.setByte(tagName, (Byte) object); break; case NBT.TAG_SHORT: nbt.setShort(tagName, (Short) object); break; case NBT.TAG_INT: nbt.setInteger(tagName, (Integer) object); break; case NBT.TAG_LONG: nbt.setLong(tagName, (Long) object); break; case NBT.TAG_FLOAT: nbt.setFloat(tagName, (Float) object); break; case NBT.TAG_DOUBLE: nbt.setDouble(tagName, (Double) object); break; case NBT.TAG_BYTE_ARRAY: nbt.setByteArray(tagName, (byte[]) object); break; case NBT.TAG_STRING: nbt.setString(tagName, (String) object); break; case NBT.TAG_LIST: nbt.setTag(tagName, (NBTBase) object); break; case NBT.TAG_COMPOUND: nbt.setTag(tagName, (NBTTagCompound) object); break; case NBT.TAG_INT_ARRAY: nbt.setIntArray(tagName, (int[]) object); break; } return nbt; } public static Object readNBTBase(NBTTagCompound nbt, int type, String tagName) { switch (type) { case NBT.TAG_END: return nbt.getBoolean(tagName); case NBT.TAG_BYTE: return nbt.getByte(tagName); case NBT.TAG_SHORT: return nbt.getShort(tagName); case NBT.TAG_INT: return nbt.getInteger(tagName); case NBT.TAG_LONG: return nbt.getLong(tagName); case NBT.TAG_FLOAT: return nbt.getFloat(tagName); case NBT.TAG_DOUBLE: return nbt.getDouble(tagName); case NBT.TAG_BYTE_ARRAY: return nbt.getByteArray(tagName); case NBT.TAG_STRING: return nbt.getString(tagName); case NBT.TAG_COMPOUND: return nbt.getTag(tagName); case NBT.TAG_INT_ARRAY: return nbt.getIntArray(tagName); default: return null; } } public static void writeBufBase(ByteBuf buf, int type, Object object, String tagName) { switch (type) { case NBT.TAG_END: buf.writeBoolean((Boolean) object); return; case NBT.TAG_BYTE: buf.writeByte((Byte) object); return; case NBT.TAG_SHORT: buf.writeShort((Short) object); return; case NBT.TAG_INT: buf.writeInt((Integer) object); return; case NBT.TAG_LONG: buf.writeLong((Long) object); return; case NBT.TAG_FLOAT: buf.writeFloat((Float) object); return; case NBT.TAG_DOUBLE: buf.writeDouble((Double) object); return; case NBT.TAG_BYTE_ARRAY: Byte[] byteArray = (Byte[]) object; buf.writeInt(byteArray.length); for (Byte aByteArray : byteArray) { buf.writeByte(aByteArray); } return; case NBT.TAG_STRING: ByteBufUtils.writeUTF8String(buf, (String) object); return; case NBT.TAG_LIST: ByteBufUtils.writeTag(buf, (NBTTagCompound) object); return; case NBT.TAG_COMPOUND: ByteBufUtils.writeTag(buf, (NBTTagCompound) object); return; case NBT.TAG_INT_ARRAY: Integer[] intArray = (Integer[]) object; buf.writeInt(intArray.length); for (Integer anIntArray : intArray) { buf.writeInt(anIntArray); } } } public static Object readBufBase(ByteBuf buf, int type, String tagName) { switch (type) { case NBT.TAG_END: return buf.readBoolean(); case NBT.TAG_BYTE: return buf.readByte(); case NBT.TAG_SHORT: return buf.readShort(); case NBT.TAG_INT: return buf.readInt(); case NBT.TAG_LONG: return buf.readLong(); case NBT.TAG_FLOAT: return buf.readFloat(); case NBT.TAG_DOUBLE: return buf.readDouble(); case NBT.TAG_BYTE_ARRAY: int byteArraySize = buf.readInt(); byte[] byteArray = new byte[byteArraySize]; for (int i = 0; i < byteArray.length; i++) { byteArray[i] = buf.readByte(); } return byteArray; case NBT.TAG_STRING: return ByteBufUtils.readUTF8String(buf); case NBT.TAG_LIST: case NBT.TAG_COMPOUND: return ByteBufUtils.readTag(buf); case NBT.TAG_INT_ARRAY: int intArraySize = buf.readInt(); int[] intArray = new int[intArraySize]; for (int i = 0; i < intArray.length; i++) { intArray[i] = buf.readInt(); } return intArray; default: return null; } } }
New rules come into force in the UK today designed to provide consumers with stronger powers of redress in the event they fall victim to authorized push payment (APP) fraud. Regulator the Financial Conduct Authority (FCA) has mandated that fraud victims can now complain to the bank that receives funds sent in error to a scammer, as well as their own bank. Both banks have to receive the complaint, with the consumer able to escalate their case to the Financial Ombudsman Service (FOS) if they’re not happy. APP fraud occurs when an account holder is tricked into making a payment to another account, such as in BEC or CEO fraud. There are two main types: with malicious payee fraud the victim authorizes a payment for what they believe to be legitimate purposes, but it’s actually a scam; while in malicious redirection the victim intends to pay a legitimate payee but the fraudster directs them to pay a third party instead. APP fraud losses jumped 44% between the first half of 2017 and the same period last year to reach £145m in the first six months of 2018, according to UK Finance. The banking group argued last year that the government should levy a payments tax to create a fund which could be used by the industry to compensate the growing number of victims. The FOS has claimed in the past that a common strategy of the banks in APP disputes — to blame the customer — is increasingly difficult to do given the sophistication of scams. A new voluntary code is being drawn up for the industry, which should also clarify when lenders are liable to pay up. These will include a duty of care placed on the part of the banks, including processes to confirm the name on the destination bank account. “This industry collaboration is key to tackling fraud and improving outcomes for consumers and businesses alike,” argued Equifax head of ID & fraud, Keith McGill.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.zoo.cat.core.service.executor; import com.google.common.collect.Lists; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.zoo.cat.annotation.Cat; import org.zoo.cat.annotation.TransTypeEnum; import org.zoo.cat.common.utils.CollectionUtils; import org.zoo.cat.common.utils.LogUtil; import org.zoo.cat.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.zoo.cat.common.bean.context.CatTransactionContext; import org.zoo.cat.common.bean.entity.CatInvocation; import org.zoo.cat.common.bean.entity.CatParticipant; import org.zoo.cat.common.bean.entity.CatTransaction; import org.zoo.cat.common.enums.EventTypeEnum; import org.zoo.cat.common.enums.CatActionEnum; import org.zoo.cat.common.enums.CatRoleEnum; import org.zoo.cat.common.exception.CatException; import org.zoo.cat.common.exception.CatRuntimeException; import org.zoo.cat.core.cache.CatTransactionGuavaCacheManager; import org.zoo.cat.core.concurrent.threadlocal.CatTransactionContextLocal; import org.zoo.cat.core.disruptor.publisher.CatTransactionEventPublisher; import org.zoo.cat.core.reflect.CatReflector; import org.zoo.cat.core.utils.JoinPointUtils; import java.lang.reflect.Method; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; /** * this is cat transaction manager. * * @author dzc */ @Component public class CatTransactionExecutor { /** * logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(CatTransactionExecutor.class); /** * transaction save threadLocal. */ private static final ThreadLocal<CatTransaction> CURRENT = new ThreadLocal<>(); private final CatTransactionEventPublisher catTransactionEventPublisher; /** * Instantiates a new Cat transaction executor. * * @param catTransactionEventPublisher the cat transaction event publisher */ @Autowired public CatTransactionExecutor(final CatTransactionEventPublisher catTransactionEventPublisher) { this.catTransactionEventPublisher = catTransactionEventPublisher; } /** * transaction preTry. * * @param point cut point. * @return TccTransaction cat transaction */ public CatTransaction preTry(final ProceedingJoinPoint point) { LogUtil.debug(LOGGER, () -> "......cat transaction starter...."); //build tccTransaction final CatTransaction catTransaction = buildCatTransaction(point, CatRoleEnum.START.getCode(), null); //save tccTransaction in threadLocal CURRENT.set(catTransaction); //publishEvent catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.SAVE.getCode()); //set TccTransactionContext this context transfer remote CatTransactionContext context = new CatTransactionContext(); //set action is try context.setAction(CatActionEnum.TRYING.getCode()); context.setTransId(catTransaction.getTransId()); context.setRole(CatRoleEnum.START.getCode()); CatTransactionContextLocal.getInstance().set(context); return catTransaction; } /** * transaction preTry. * * @param point cut point. * @return TccTransaction cat transaction */ public CatTransaction preTryNotice(final ProceedingJoinPoint point) { LogUtil.debug(LOGGER, () -> "......cat transaction starter...."); //build noticeTransaction final CatTransaction catTransaction = buildCatTransaction(point, CatRoleEnum.START.getCode(), null); //save noticeTransaction in threadLocal CURRENT.set(catTransaction); //publishEvent catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.SAVE.getCode()); //set TccTransactionContext this context transfer remote CatTransactionContext context = new CatTransactionContext(); //set action is notice context.setAction(CatActionEnum.NOTICEING.getCode()); context.setTransId(catTransaction.getTransId()); context.setRole(CatRoleEnum.START.getCode()); CatTransactionContextLocal.getInstance().set(context); return catTransaction; } /** * this is Participant transaction preTry. * * @param context transaction context. * @param point cut point * @return TccTransaction cat transaction */ public CatTransaction preTryParticipant(final CatTransactionContext context, final ProceedingJoinPoint point) { LogUtil.debug(LOGGER, "participant cat transaction start..:{}", context::toString); final CatTransaction catTransaction = buildCatTransaction(point, CatRoleEnum.PROVIDER.getCode(), context.getTransId()); //cache by guava CatTransactionGuavaCacheManager.getInstance().cacheCatTransaction(catTransaction); //publishEvent catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.SAVE.getCode()); //Nested transaction support context.setRole(CatRoleEnum.LOCAL.getCode()); CatTransactionContextLocal.getInstance().set(context); return catTransaction; } /** * Call the confirm method and basically if the initiator calls here call the remote or the original method * However, the context sets the call confirm * The remote service calls the confirm method. * * @param currentTransaction {@linkplain CatTransaction} * @return the object * @throws CatRuntimeException ex */ public Object confirm(final CatTransaction currentTransaction) throws CatRuntimeException { LogUtil.debug(LOGGER, () -> "cat transaction confirm .......!start"); if (Objects.isNull(currentTransaction) || CollectionUtils.isEmpty(currentTransaction.getCatParticipants())) { return null; } currentTransaction.setStatus(CatActionEnum.CONFIRMING.getCode()); updateStatus(currentTransaction); final List<CatParticipant> catParticipants = currentTransaction.getCatParticipants(); boolean success = true; if (CollectionUtils.isNotEmpty(catParticipants)) { List<CatParticipant> failList = Lists.newArrayListWithCapacity(catParticipants.size()); List<Object> results = Lists.newArrayListWithCapacity(catParticipants.size()); for (CatParticipant catParticipant : catParticipants) { try { final Object result = CatReflector.executor(catParticipant.getTransId(), CatActionEnum.CONFIRMING, catParticipant.getConfirmCatInvocation()); results.add(result); } catch (Exception e) { LogUtil.error(LOGGER, "execute confirm :{}", () -> e); success = false; failList.add(catParticipant); } finally { CatTransactionContextLocal.getInstance().remove(); } } executeHandler(success, currentTransaction, failList); return results.get(0); } return null; } /** * cancel transaction. * * @param currentTransaction {@linkplain CatTransaction} * @return the object */ public Object cancel(final CatTransaction currentTransaction) { LogUtil.debug(LOGGER, () -> "tcc cancel ...........start!"); if (Objects.isNull(currentTransaction) || CollectionUtils.isEmpty(currentTransaction.getCatParticipants())) { return null; } //if cc pattern,can not execute cancel if (currentTransaction.getStatus() == CatActionEnum.TRYING.getCode() && Objects.equals(currentTransaction.getPattern(), TransTypeEnum.CC.getCode())) { deleteTransaction(currentTransaction); return null; } currentTransaction.setStatus(CatActionEnum.CANCELING.getCode()); //update cancel updateStatus(currentTransaction); final List<CatParticipant> catParticipants = filterPoint(currentTransaction); boolean success = true; if (CollectionUtils.isNotEmpty(catParticipants)) { List<CatParticipant> failList = Lists.newArrayListWithCapacity(catParticipants.size()); List<Object> results = Lists.newArrayListWithCapacity(catParticipants.size()); for (CatParticipant catParticipant : catParticipants) { try { final Object result = CatReflector.executor(catParticipant.getTransId(), CatActionEnum.CANCELING, catParticipant.getCancelCatInvocation()); results.add(result); } catch (Exception e) { LogUtil.error(LOGGER, "execute cancel ex:{}", () -> e); success = false; failList.add(catParticipant); } finally { CatTransactionContextLocal.getInstance().remove(); } } executeHandler(success, currentTransaction, failList); return results.get(0); } return null; } /** * transaction preNotice. * * @param point cut point. * @return TccTransaction cat transaction */ public CatTransaction preNotice(final ProceedingJoinPoint point) { LogUtil.debug(LOGGER, () -> "......cat transaction starter...."); //build tccTransaction final CatTransaction catTransaction = buildCatTransaction(point, CatRoleEnum.START.getCode(), null); //save tccTransaction in threadLocal CURRENT.set(catTransaction); //publishEvent catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.SAVE.getCode()); //set TccTransactionContext this context transfer remote CatTransactionContext context = new CatTransactionContext(); //set action is try context.setAction(CatActionEnum.NOTICEING.getCode()); context.setTransId(catTransaction.getTransId()); context.setRole(CatRoleEnum.START.getCode()); CatTransactionContextLocal.getInstance().set(context); return catTransaction; } /** * this is Participant transaction preNoticeParticipant. * * @param context transaction context. * @param point cut point * @return CatTransaction cat transaction */ public CatTransaction preNoticeParticipant(final CatTransactionContext context, final ProceedingJoinPoint point) { LogUtil.debug(LOGGER, "participant cat transaction start..:{}", context::toString); final CatTransaction catTransaction = buildCatTransaction(point, CatRoleEnum.PROVIDER.getCode(), context.getTransId()); //cache by guava CatTransactionGuavaCacheManager.getInstance().cacheCatTransaction(catTransaction); //Nested transaction support context.setRole(CatRoleEnum.LOCAL.getCode()); CatTransactionContextLocal.getInstance().set(context); return catTransaction; } /** * update transaction status by disruptor. * * @param catTransaction {@linkplain CatTransaction} */ public void updateStatus(final CatTransaction catTransaction) { catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.UPDATE_STATUS.getCode()); } /** * delete transaction by disruptor. * * @param catTransaction {@linkplain CatTransaction} */ public void deleteTransaction(final CatTransaction catTransaction) { catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.DELETE.getCode()); } /** * update Participant in transaction by disruptor. * * @param catTransaction {@linkplain CatTransaction} */ public void updateParticipant(final CatTransaction catTransaction) { catTransactionEventPublisher.publishEvent(catTransaction, EventTypeEnum.UPDATE_PARTICIPANT.getCode()); } /** * acquired by threadLocal. * * @return {@linkplain CatTransaction} */ public CatTransaction getCurrentTransaction() { return CURRENT.get(); } /** * clean threadLocal help gc. */ public void remove() { CURRENT.remove(); } /** * add participant. * * @param catParticipant {@linkplain CatParticipant} */ public void enlistParticipant(final CatParticipant catParticipant) { if (Objects.isNull(catParticipant)) { return; } Optional.ofNullable(getCurrentTransaction()) .ifPresent(c -> { c.registerParticipant(catParticipant); updateParticipant(c); }); } /** * when nested transaction add participant. * * @param transId key * @param catParticipant {@linkplain CatParticipant} */ public void registerByNested(final String transId, final CatParticipant catParticipant) { if (Objects.isNull(catParticipant) || Objects.isNull(catParticipant.getCancelCatInvocation()) || Objects.isNull(catParticipant.getConfirmCatInvocation())) { return; } final CatTransaction catTransaction = CatTransactionGuavaCacheManager.getInstance().getCatTransaction(transId); Optional.ofNullable(catTransaction) .ifPresent(transaction -> { transaction.registerParticipant(catParticipant); updateParticipant(transaction); }); } public void executeHandler(final boolean success, final CatTransaction currentTransaction, final List<CatParticipant> failList) { CatTransactionGuavaCacheManager.getInstance().removeByKey(currentTransaction.getTransId()); if (success) { deleteTransaction(currentTransaction); } else { currentTransaction.setCatParticipants(failList); updateParticipant(currentTransaction); throw new CatRuntimeException(failList.toString()); } } private List<CatParticipant> filterPoint(final CatTransaction currentTransaction) { final List<CatParticipant> catParticipants = currentTransaction.getCatParticipants(); if (CollectionUtils.isNotEmpty(catParticipants)) { if ( (currentTransaction.getStatus() == CatActionEnum.TRYING.getCode() || currentTransaction.getStatus() == CatActionEnum.NOTICEING.getCode()) && currentTransaction.getRole() == CatRoleEnum.START.getCode()) { return catParticipants.stream() .limit(catParticipants.size()) .filter(Objects::nonNull).collect(Collectors.toList()); } } return catParticipants; } private CatTransaction buildCatTransaction(final ProceedingJoinPoint point, final int role, final String transId) { CatTransaction catTransaction; if (StringUtils.isNoneBlank(transId)) { catTransaction = new CatTransaction(transId); } else { catTransaction = new CatTransaction(); } catTransaction.setStatus(CatActionEnum.PRE_TRY.getCode()); catTransaction.setRole(role); Method method = JoinPointUtils.getMethod(point); Class<?> clazz = point.getTarget().getClass(); Object[] args = point.getArgs(); final Cat cat = method.getAnnotation(Cat.class); final TransTypeEnum pattern = cat.pattern(); if(Objects.isNull(pattern)) { LOGGER.error("事务补偿模式必须在TCC,SAGA,CC,NOTICE中选择"); } catTransaction.setTargetClass(clazz.getName()); catTransaction.setTargetMethod(method.getName()); catTransaction.setPattern(pattern.getCode()); catTransaction.setRetryMax(cat.retryMax()); catTransaction.setTransType(cat.pattern().getDesc()); catTransaction.setTimeoutMills(cat.timeoutMills()); String targetMethod = method.getName(); String confirmMethodName = cat.confirmMethod(); String cancelMethodName = cat.cancelMethod(); //判断是否是通知模式 if(cat.pattern().getCode()==TransTypeEnum.NOTICE.getCode()) { CatInvocation noticeInvocation = null; if (StringUtils.isNoneBlank(targetMethod)) { catTransaction.setTargetMethod(targetMethod); noticeInvocation = new CatInvocation(clazz, targetMethod, method.getParameterTypes(), args); } final CatParticipant catParticipant = new CatParticipant(catTransaction.getTransId(), noticeInvocation); catTransaction.registerParticipant(catParticipant); catTransaction.setStatus(CatActionEnum.NOTICEING.getCode()); catTransaction.setRole(role); return catTransaction; }else { CatInvocation confirmInvocation = null; CatInvocation cancelInvocation = null; if (StringUtils.isNoneBlank(confirmMethodName)) { catTransaction.setConfirmMethod(confirmMethodName); confirmInvocation = new CatInvocation(clazz, confirmMethodName, method.getParameterTypes(), args); } if (StringUtils.isNoneBlank(cancelMethodName)) { catTransaction.setCancelMethod(cancelMethodName); cancelInvocation = new CatInvocation(clazz, cancelMethodName, method.getParameterTypes(), args); } final CatParticipant catParticipant = new CatParticipant(catTransaction.getTransId(), confirmInvocation, cancelInvocation); catTransaction.registerParticipant(catParticipant); return catTransaction; } } /** * EN: notice transaction. * CN:消息通知事务补偿 * @param currentTransaction {@linkplain CatTransaction} * @return the object */ public Object notice(final CatTransaction currentTransaction) { LogUtil.debug(LOGGER, () -> "notice compensate...........start!"); if (Objects.isNull(currentTransaction) || CollectionUtils.isEmpty(currentTransaction.getCatParticipants())) { return null; } currentTransaction.setStatus(CatActionEnum.NOTICEING.getCode()); updateStatus(currentTransaction); final List<CatParticipant> catParticipants = filterPoint(currentTransaction); boolean success = true; if (CollectionUtils.isNotEmpty(catParticipants)) { List<CatParticipant> failList = Lists.newArrayListWithCapacity(catParticipants.size()); List<Object> results = Lists.newArrayListWithCapacity(catParticipants.size()); for (CatParticipant catParticipant : catParticipants) { try { Long startTime = System.currentTimeMillis(); final Object result = CatReflector.executor(catParticipant.getTransId(), CatActionEnum.NOTICEING, catParticipant.getNoticeCatInvocation()); Long endTime = System.currentTimeMillis(); if(currentTransaction.getTimeoutMills()>0 && endTime-startTime>currentTransaction.getTimeoutMills()) { throw new CatException("method "+currentTransaction.getTargetMethod()+" timeout.."); } results.add(result); } catch (Exception e) { LogUtil.error(LOGGER, "execute notice ex:{}", () -> e); success = false; failList.add(catParticipant); } finally { CatTransactionContextLocal.getInstance().remove(); } } //删除补偿 executeHandler(success, currentTransaction, failList); return results.get(0); } return null; } }
Simulation of an oil immersion objective lens: a simplified ray-optics model considering Abbe's sine condition. In this paper, a simplified mathematical ray-optics model for an oil immersion objective lens, considering Abbe's sine condition, is presented. Based on the given parameters of the objective lens, the proposed model utilizes an approach based on a paraxial thin lens formulation. This is done to simplify the complexity of the objective lens by avoiding the consideration of many lens elements inside a single objective lens. To demonstrate the performance of the proposed model, comparisons with exact ray tracing method, based on the specification of real objective lens, are presented in terms of several different criteria including the variation of shape of the light cone, the extent of vignetting and the focus displacement. From the exemplary simulations, it was demonstrated that the proposed model can describe the focusing of light through the objective lens precisely, even when the incident beam rotates.
1. Field of the Invention The present invention relates to a power and signal transmission system which makes signal transmission via lines and permits transmission of power by using lines such as those used in a public telephone network. 2. Description of the Related Art In general, in exchanges, etc., power transmission is made via signal-transmitting lines. In a typical exchange, first and second communication devices are connected to each other via communication lines. A digital signal is applied to the input terminal of the transmitting circuit of the first communication device and is converted by a transmitting circuit, which is powered from a power source, to a signal having no direct current component. The converted signal is, in turn, transmitted on the lines via a signal-source resistor and a transformer. The receiving circuit of the second communication device receives the signal transmitted over the lines. In the first communication device, a high-voltage source delivers a high-voltage from the center tap of the secondary winding of a transformer, connected by a signal-short-circuiting capacitor, to the lines. The high voltage supplied to the lines is lowered by line resistance and then applied to a DC-to-DC conversion circuit in the second communication device. The conversion circuit converts the input high voltage to a power supply voltage required with a receiving circuit in the second communication device. However, the use of transformers and choke coils for power transmission will increase the cost and make the system large because they are costly and large. In addition, there are disadvantages in that the assembly of the transformers and the choke coils takes a lot of time and labor, and the assembly cost also increases.
import FlowDispatchTypes from '../enums/FlowDispatchTypes'; import { IConstants } from '../interfaces/IConstants'; import { AuthOption } from '../interfaces/AuthOptionInterfaces'; import { Flow } from '../interfaces/FlowSelectorInterfaces'; export default getFlow; function getFlow(index: number, CONSTANTS: IConstants): Flow { const options: AuthOption[] = CONSTANTS.verification_options; const useMenu: boolean = options.length > 1; return createFlow(index, options, useMenu); } function createFlow( index: number, options: AuthOption[], useMenu: boolean ): Flow { const initial: any = createInitialSteps(index, options, useMenu); injectAuthMethod(index, initial, options, useMenu); return initial; } function injectAuthMethod( index: number, flow: any, options: AuthOption[], useMenu: boolean ) { const beginAt: string = useMenu ? 'menu' : 'confirmation'; const sequence: string[] = options[index].sequence; if (!sequence.length) throw new Error(`The sequence array for ${options[index].title} must contain at least one element, and it contains zero elements right now.`); const currentPoint: string = sequence[0]; flow[beginAt][FlowDispatchTypes.NEXT] = currentPoint; flow[currentPoint] = { [FlowDispatchTypes.BACK]: beginAt }; foldSequence(currentPoint, options[index], flow); } function foldSequence(currentPoint: string, option: AuthOption, flow: any) { const sequence = option.sequence; for (let i = 1; i < sequence.length; i++) { const temp: string = currentPoint; currentPoint = sequence[i]; flow[temp][FlowDispatchTypes.NEXT] = currentPoint; flow[currentPoint] = { [FlowDispatchTypes.BACK]: temp }; } if ('verify' === option.type) { flow[currentPoint][FlowDispatchTypes.NEXT] = 'details'; flow['details'] = { [FlowDispatchTypes.BACK]: currentPoint }; } } function createInitialSteps( index: number, options: AuthOption[], useMenu: boolean ) { const firstScreen = options[index].sequence[0]; const ret: any = { confirmation: { [FlowDispatchTypes.NEXT]: firstScreen } }; if (useMenu) { ret.confirmation[FlowDispatchTypes.NEXT] = 'menu'; ret['menu'] = { [FlowDispatchTypes.BACK]: 'confirmation', [FlowDispatchTypes.NEXT]: firstScreen }; } return ret; }
<reponame>haleyga/fixinator<filename>src/messaging/fields/advertisement-id/advertisement-id.ts import { FixIntField, IFixIntField } from '../base/fix/fix-int-field/fix-int-field'; import { Tag } from '../base/tag'; export interface IAdvertisementIdField extends IFixIntField {} /** * Field ID (TAG): 2 * Field Name: AdvId * Format: int * Description: Unique identifier of advertisement message */ export class AdvertisementIdField extends FixIntField implements IAdvertisementIdField { constructor(raw: string) { super(Tag.AdvId, raw); } }
<gh_stars>100-1000 package ngsi import ( "encoding/json" "testing" ) func TestContextMetadata(t *testing.T) { registerCtxReq := RegisterContextRequest{} registerCtxReq.Duration = "10M" registerCtxReq.RegistrationId = "0" registerCtxReq.ContextRegistrations = make([]ContextRegistration, 0) registeration := ContextRegistration{} registeration.ProvidingApplication = "http://127.0.0.1:8080/ngsi10" registeration.EntityIdList = make([]EntityId, 0) eid := EntityId{} eid.ID = "001" eid.IsPattern = false eid.Type = "Test" registeration.EntityIdList = append(registeration.EntityIdList, eid) registeration.Metadata = make([]ContextMetadata, 0) point := Point{} point.Latitude = 86.0 point.Longitude = 30.0 meta := ContextMetadata{} meta.Name = "location" meta.Type = "point" meta.Value = point registeration.Metadata = append(registeration.Metadata, meta) meta2 := ContextMetadata{} meta2.Name = "layer" meta2.Type = "integer" meta2.Value = 3 registeration.Metadata = append(registeration.Metadata, meta2) registerCtxReq.ContextRegistrations = append(registerCtxReq.ContextRegistrations, registeration) jsonText, _ := json.Marshal(registerCtxReq) t.Logf("%+v\n", registerCtxReq) t.Log(string(jsonText)) testObj := RegisterContextRequest{} err := json.Unmarshal(jsonText, &testObj) if err == nil { t.Logf("%+v\n", testObj) t.Log(testObj) } else { t.Fatal(err) } }
Abstracts from the Literature s of Literature Associate Editor for Abstracts Jane Etherington We are indebted to the following contributors from the University of Pittsburgh for their evaluations: Benjamin H. Eidelman Joseph A. Horton Maximo Kiok Patrick M. Kochanek Lewis H. Kuller Edwin M. Nemoto Walter D. Obrist Donald Rezek Laligam N. Sekhar Kim Sutton-Tyrrell Lawrence R. Wechsler CEREBRAL ANEURYSM / SUBARACHNOID HEMORRHAGE AB-11026-91 Perioperative Management and Outcome After Surgical Treatment of Anterior Cerebral Artery Aneurysms Awad IA (Department of Neurological Surgery, Desk S80, The Cleveland Clinic Foundation, 9500 Euclid Avenue, Cleveland, OH 44195), Little 3R-CanJNeurol Sci 1991;18:120-125 The authors present clinical experience with 28 cases of ruptured anterior cerebral artery (ACA) aneurysms managed personally during a 36 month period, and 10 unruptured ACA aneurysms. The cases included five giant aneurysms and four distal ACA aneurysms. Management strategy was uniform and included early operative intervention (except in the setting of deteriorating neurologic deficit, not attributable to hydrocephalus or hematoma), and vasospasm prophylaxis including calcium channel blockers and hypervolemic hemodilution and arterial hypertension. Modern diagnostic adjuncts including transcranial doppler were used as they became available. Good outcome (outcome grade 1 or 2) was observed at 6 months in 71% (20/28) of ruptured cases and in 90% (9/10) of unruptured cases; fair outcome (outcome grade 3) was observed in 14% (4/28) of ruptured cases and in 10% of unruptured cases; bad outcome (outcome grade 4 or 5) was observed in 14% (4/28) of ruptured cases. There were no instances of rebleeding after admission to the hospital. There was a single mortality in a patient moribund on admission. Delayed ischemic deterioration (DID) was documented in 46% (13 of 28) of the ruptured cases, and was a major source of morbidity in 7 of the 9 instances of fair or poor outcome in the series. Management outcome, including the occurrence of subtle neuropsychological difficulties commonly described in cases with ACA aneurysms, is discussed with relation to the incidence of DID, the clinical course of DID, and the possible impact of various therapeutic strategies. AB-11027-91 Treatment of Cerebral Arteriovenous Malformations With PVA-Schumacher M (Department of Radiology, University of Freiburg, Hauptstrasse 5, W-7800 Freiburg, Federal Republic of Germany), Horton JA-Neuroradiology 1991;33:101-105 35 Patients with cerebral arteriovenous malformations treated by endovascular embolization were analyzed. The treatment was performed in most cases with polyvinyl alcohol with additional applications of silk, coils, gelfoam or detachable balloon in some patients. 8 patients developing mild to moderate neurological deficits persisting in three patients (8.6%). No correlation of complications with history of bleeding, neurological deficit, AVM localization, AVM size, angioarchitecture, amount of occlusion and duration of the procedure could be found. Technical factors of the procedure itself are assumed to be responsible for the rate of complications. AB-11028-91 Growth of a Thrombosed Giant Vertebral Artery Aneurysm After Parent Artery Occlusion Hecht ST (Departments of Radiology and Neurological Surgery, University of California, Davis, 2516 Stockton Boulevard, Ticon II, Sacramento, CA 95817), Horton JA, Yonas H-AJNR 1991;12:449-451 © American Society of Neuroradiology Parent artery ligation is an accepted treatment for intracranial aneurysms that are not amenable to a direct surgical approach. Parent artery ligation is one of the oldest effective surgical means of aneurysm therapy (the "Hunterian principle"). Recently it has become possible to perform parent artery occlusion of the carotid or vertebral artery percutaneously by using detachable balloon technology. We report a case of a patient with a vertebral artery giant aneurysm, which was treated by parent artery occlusion of the vertebral artery, resulting in thrombosis of the aneurysm. In spite of thrombosis of the aneurysm and the parent artery, the aneurysm continued to grow. This case suggests that giant aneurysm growth is not always dependent on pulsatile blood flow as a driving force, and that recurrent mural hemorrhage into the highly vascularized aneurysm wall is a more likely mechanism. Giant aneurysms can be unstable lesions even when they (and their parent arteries) are thrombosed. Continued surveillance with CT and/or MR imaging is prudent following thrombosis of giant aneurysms by parent artery occlusion. Abstracts of Literature 1333s of Literature 1333
<reponame>paulosergio-jnr/java-fluent-validator<gh_stars>10-100 package br.com.fluentvalidator.builder; import br.com.fluentvalidator.exception.ValidationException; public interface WithValidator<T, P, W extends When<T, P, W, N>, N extends Whenever<T, P, W, N>> extends RuleBuilder<T, P, W, N> { /** * * @return */ Critical<T, P, W, N> critical(); /** * * @param clazz * @return */ Critical<T, P, W, N> critical(final Class<? extends ValidationException> clazz); }
#ifndef H_LinkedListIterator #define H_LinkedListIterator #include "Node.h" template <class Type> class linkedListIterator { public: linkedListIterator() {current = nullptr;} linkedListIterator(nodeType<Type> *ptr) {current = ptr;} Type operator *() {return current->info;} linkedListIterator<Type> operator++() { current = current->link; return *this; } bool operator==(const linkedListIterator<Type>& right ) const {return (current == right.current);} bool operator!=(const linkedListIterator<Type>& right ) const {return (current != right.current);} private: nodeType<Type> *current; }; #endif
It is well established that SO.sub.2 and NO.sub.x emissions from coal combustion, such as occurring at electrical power plants, promotes acid deposition and the phenomenon known as acid rain. More particularly, the rainfall may be acidified to a pH in the range of 3.5-4.5. This acid rain damages vehicles, buildings and other personal property. It also collects in lakes and streams lowering the pH level of those bodies of water and in some cases adversely effecting those ecosystems. Accordingly, SO.sub.2 and NO.sub.x emissions are a major environmental concern. Atmospheric fluidized bed combustion (AFBC) is one of a few commercially available technologies presently capable of simultaneously controlling SO.sub.2 and NO.sub.x emissions and maintaining them at acceptable levels when burning relatively high sulfur eastern United States coal. More particularly, SO.sub.2 emissions are limited by capturing sulfur (S) in an appropriate calcium sorbent such as limestone or dolomite. Additionally, NO.sub.x formation is restricted by the lower combustion temperatures inherent to AFBC systems. Recent AFBC research efforts have focused on further reducing NO.sub.x formation while attempting to maintain high sulfur capture rates and hence reduced SO.sub.2 emissions by utilizing the principals of staged combustion. An example of such an approach is disclosed in U.S. Pat. No. 4,962,711 to Yamouchi et al. In this patent, a state of the art AFBC apparatus is modified by incorporating a set of tertiary air nozzles in the free board area; that is, the area directly above the fluid or dense phase fluid bed region. Advantageously, due to the reducing conditions provided in the dense phase fluid bed region, NO.sub.x compounds are more efficiently and effectively reduced to N.sub.2 +H.sub.2 O. Accordingly, NO.sub.x emissions are advantageously reduced. It should be appreciated however, that free board burning is increased with the introduction of the additional air through the tertiary nozzles. As there is less sorbent and fuel contact in the free board area than in the dense phase fluid bed region, the reduction in NO.sub.x emissions is obtained at the expense of decreased sulfur capture. Accordingly, SO.sub.2 emissions increase. In fact, studies have shown that sulfur capture may decrease by up to 30% due to the increased coal burning in the free board area. This leads to a proportional increase in SO.sub.2 emissions. A further problem with the staged AFBC systems that provide additional over fire air in the free board area relates to the extreme reducing conditions that are then maintained within the fluid bed region. More particularly, these reducing conditions often result in reduced combustion efficiencies leading to an increase in pollutants in the form of incomplete combustion products and also a reduction in power production. Further, calcium sulfide (CaS) is formed during coal firing. CaS is an undesirable reaction product. More particularly, CaS has a propensity to react with water vapor and release hydrogen sulfide (H.sub.2 S). Accordingly, spent sorbent including CaS is not suitable for disposal in a landfill. Consequently, the staged delivery of air into the free board area proposed in the prior art creates further environmental concerns and disposal problems. While other research has indicated that it is possible to simultaneously lower NO.sub.x and SO.sub.2 emissions with staged AFBC systems wherein additional over fire air is delivered to the free board area, these approaches have all required the utilization of excessively high Ca/S molar ratios. This means that the sorbent is not utilized efficiently or effectively in these systems. Accordingly, these systems require significant additional quantities of sorbent beyond what is desired for economic operation. More specifically, the costs of obtaining and conveying the additional sorbent to the site of the AFBC system and of disposing of the sorbent in an environmentally acceptable manner materially adversely effect the feasibility of commercial operation of this type of system. A need is therefore identified for an improved approach to AFBC.
Thomas Newton Biography Newton was educated at Trinity College, Cambridge and was subsequently elected a fellow of Trinity. He was ordained in the Church of England and continued scholarly pursuits. His more remembered works include his annotated edition of Paradise Lost, including a biography of John Milton, published in 1749. In 1754 he published a large scholarly analysis of the prophecies of the Bible, titled Dissertations on the Prophecies. In his 1761 edition of Milton's poetry, he gave the title On His Blindness to Sonnet XIX, When I Consider How My Light is Spent. Newton was appointed the Bishop of Bristol in 1761 and in 1768 became the Dean of St Paul's Cathedral in London. He has been considered a Christian universalist. One of Newton's famous quotes concerns the Jewish people: The preservation of the Jews is really one of the most signal and illustrious acts of divine Providence... and what but a supernatural power could have preserved them in such a manner as none other nation upon earth hath been preserved. Nor is the providence of God less remarkable in the destruction of their enemies, than in their preservation... We see that the great empires, which in their turn subdued and oppressed the people of God, are all come to ruin... And if such hath been the fatal end of the enemies and oppressors of the Jews, let it serve as a warning to all those, who at any time or upon any occasion are for raising a clamor and persecution against them.
Tying Beauty to Truth: Visual Mnemonics Add Meaning to Perceived Patterns he information visualization community has made great strides in understanding and engaging human sensory and perceptual mechanisms over the last decade, essentially back- fitting them by designing displays that take advantage of human vision. I will present an abstraction of the human visual system that follows a "Knowledge Acquisition Pipeline" from photons to contextualized ideas at just the granularity needed by designers and engineers. My students and I have found it valuable in the analysis of visualizations and the design of visualization-like user interfaces: interfaces with non-standard widgets or spatial organization. This pipeline does more than help us sort out and connect data to the appropriate perceptual mechanisms; it helps us explore the final stages in knowledge acquisition: the stages where patterns exposed by good visualization tools get integrated into the individual ideas and shared metaphors of a knowledge domain. By letting questions from domain experts define the goals of a view, and letting their shared metaphors inform the structure of the view space and shapes of the glyphs, we can streamline the task of interpretation and memory embellishment that anchors ideas. Though many of the techniques I will share are well known, I hope this pipeline abstraction will help designers sort out which data to present to what perceptual/cognitive process, and evaluate designs to see whether they are missing expressive opportunities by ignoring one or more human "input channels." These techniques are more effective in some domains than others, but the approach can also help to identify where visual metaphors should not be used, helping prevent unintentionally misleading displays. The approach also seems extremely well suited to alternate displays such as large-format prints and the pixel-dense meter-wide displays we will see in the near future. Perhaps most important: tying the tool more firmly to the representations experts have in their minds makes each tool more of a toy, work more like intellectual play, and might even add the depth of human meaning to our pretty patterns. T
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.actions import IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import LaunchConfiguration def generate_launch_description(): # ROS packages pkg_kohm_gazebo = get_package_share_directory('kohm_gazebo') pkg_robot_state_controller = get_package_share_directory('robot_state_controller') pkg_white_line_detection = get_package_share_directory('white_line_detection') pkg_teleop_twist_joy = get_package_share_directory('teleop_twist_joy') # Config joy_config = os.path.join(pkg_kohm_gazebo, 'config/joystick', 'xbone.config.yaml') # Launch arguments drive_mode_switch_button = LaunchConfiguration('drive_mode_switch_button', default='8') use_sim_time = LaunchConfiguration('use_sim_time', default='true') use_rviz = LaunchConfiguration('use_rviz', default='true') follow_waypoints = LaunchConfiguration('follow_waypoints', default='false') state_publishers = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/state_publishers/state_publishers.launch.py' ]), launch_arguments={'use_sim_time': use_sim_time}.items(), ) ign_gazebo = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/gazebo/gazebo.launch.py' ]), ) joy_with_teleop_twist = IncludeLaunchDescription( PythonLaunchDescriptionSource( os.path.join(pkg_teleop_twist_joy, 'launch', 'teleop-launch.py')), launch_arguments={ 'joy_config': 'xbox', 'joy_dev': '/dev/input/js0', 'config_filepath': joy_config }.items(), ) rviz = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/rviz/rviz.launch.py' ]), launch_arguments={ 'use_rviz': use_rviz, 'use_sim_time': use_sim_time }.items(), ) lidar_processor = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/lidar_processor/lidar_processor.launch.py' ]), launch_arguments={'use_sim_time': use_sim_time}.items(), ) sensor_processor = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/sensor_processor/sensor_processor.launch.py' ]), launch_arguments={'use_sim_time': use_sim_time}.items(), ) pointcloud_to_laserscan = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/pointcloud_to_laserscan/pointcloud_to_laserscan.launch.py' ]), launch_arguments={'use_sim_time': use_sim_time}.items(), ) navigation = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/navigation/navigation.launch.py' ]), launch_arguments={'use_sim_time': use_sim_time}.items(), ) waypoint_publisher = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_kohm_gazebo, 'launch'), '/include/waypoint_publisher/waypoint.launch.py' ]), launch_arguments={ 'use_sim_time': use_sim_time, 'follow_waypoints': follow_waypoints }.items(), ) robot_state_controller = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_robot_state_controller, 'launch'), '/rsc_with_ipp.launch.py' ]), launch_arguments={ 'switch_button': drive_mode_switch_button, 'use_sim_time': use_sim_time }.items(), ) white_line_detection = IncludeLaunchDescription( PythonLaunchDescriptionSource([ os.path.join(pkg_white_line_detection, 'launch'), '/white_line_detection.launch.py' ]), launch_arguments={ 'use_sim_time': use_sim_time }.items(), ) return LaunchDescription([ # Launch Arguments DeclareLaunchArgument( 'drive_mode_switch_button', default_value='8', description='Which button is used on the joystick to switch drive mode. (In joy message)' ), DeclareLaunchArgument( 'use_sim_time', default_value='true', description='Use simulation (Gazebo) clock if true'), DeclareLaunchArgument('use_rviz', default_value='true', description='Open rviz if true'), DeclareLaunchArgument('follow_waypoints', default_value='false', description='follow way points if true'), # Nodes state_publishers, ign_gazebo, joy_with_teleop_twist, lidar_processor, sensor_processor, pointcloud_to_laserscan, navigation, rviz, waypoint_publisher, robot_state_controller, white_line_detection ])
<filename>src/contrib.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <ctype.h> #include <math.h> #include <float.h> #include <errno.h> #include "trealla.h" #include "internal.h" #include "builtins.h" const struct builtins g_contrib_funcs[] = { {0} };
Problems of Development of Innovative Economy in Germany and Spain and Possible Ways of Their Solution The following article is focused on the issues of development of innovative economy based on statistics and sythesis of previously conducted scientific researches. These challenges are analysed through the case study of Germany and Spain as they represent different groups of countries in terms of innovation and feature various approaches to overcome the problems.Such problems as: inability to adapt to the objective trend to slow down the widespread introduction of innovations, underfunding of high-tech industries, lack of radical innovations, narrow scope of higher education specializations, lack of mechanisms to protect investors in innovative projects and inconsistency of legislation regulating innovative activity are considered typical for Germany. The issues of underestimation of the innovative potential of the state, lack of infrastructure and coordination between its facilities, high level of bureaucracy, insufficient training and inefficient use of resources are the ones that Spainish economy faces. Detection of the above listed challenges allows to develop recommendations to resolve the issues of German and Spanish innovative economics. Their expirience would to be useful in identifying the challenges of the current situation and in formulating development strategies for states with similar problems, including Russia.
A Mongrel Mob member attacked a teenager at a KFC restaurant in Blenheim because he was wearing a blue rugby uniform, a court has heard. Kahutia Mita, 34, a vineyard worker, punched the 15-year-old in the head, fracturing his nose and breaking one of his teeth. Police said the high school student walked to the fast food outlet on December 9 with two of his friends after playing touch rugby. The boy was wearing a blue team uniform and was of a typical height and build for a boy of his age, a police summary of facts said. Mita, in comparison, was large and tall, and wearing red, the gang's colour, the summary said. Mita appeared to be agitated when he walked in, and clenched his fists and verbally abused the student for wearing blue. He then punched the student twice to the head, shouting "that's what you get". The student was dazed and confused from the punches, and his mouth and nose were bleeding, the summary said. Mita then left the restaurant. After the assault, the student had a fractured nose, a broken tooth that required surgery, a hematoma on each eye, bruises and a concussion. When spoken to by police, Mita declined to comment. He was charged with injuring with intent to injure and taken into police custody. He admitted the charge at the Blenheim District Court on Monday. Judge Jan Kelly convicted him and remanded him in custody to January 24 so his home address could be assessed for an electronically monitored sentence.
<filename>src/main/java/duke/logic/command/shortcut/SetShortcutCommand.java package duke.logic.command.shortcut; import duke.logic.command.Command; import duke.logic.command.CommandResult; import duke.logic.command.exceptions.CommandException; import duke.model.Model; import duke.model.shortcut.Shortcut; /** * A command to remove or add a {@code Shortcut}. */ public class SetShortcutCommand extends Command { public static final String COMMAND_WORD = "short"; private static final String MESSAGE_COMMIT = "Set shortcut"; private static final String MESSAGE_COMMIT_REMOVE = "Remove shortcut"; private static final String MESSAGE_SET_SUCCESS = "Shortcut [%s] is set."; private static final String MESSAGE_REMOVE_SUCCESS = "Shortcut [%s] is removed."; private static final String MESSAGE_EMPTY_SHORTCUT = "Shortcut is not found and thus cannot be removed."; private static final String MESSAGE_CANNOT_CONTAIN_DO_COMMAND = "Commands cannot contain do commands."; private final Shortcut shortcut; private final boolean isEmptyShortcut; /** * Creates a {@code SetShortCutCommand}. * @param shortcut to add or remove. * If {@code shortcut} has empty {@code userInputs} and it is in * the Shortcut List, it will be removed. * If {@code shortcut} has non-empty {@code userInputs}, it will be added to Shortcut List, * or override an existing shortcut in Shortcut List. */ public SetShortcutCommand(Shortcut shortcut) { this.shortcut = shortcut; isEmptyShortcut = shortcut.getCommandStrings().isEmpty(); } @Override public CommandResult execute(Model model) throws CommandException { //If shortcut has empty user inputs and it is in the Shortcut List if (isEmptyShortcut && model.hasShortcut(shortcut)) { model.removeShortcut(shortcut); model.commit(MESSAGE_COMMIT_REMOVE); return new CommandResult(String.format(MESSAGE_REMOVE_SUCCESS, shortcut.getName())); } else if (isEmptyShortcut) { throw new CommandException(MESSAGE_EMPTY_SHORTCUT); } else { checkShortcutEligibility(); model.setShortcut(shortcut); model.commit(MESSAGE_COMMIT); return new CommandResult(String.format(MESSAGE_SET_SUCCESS, shortcut.getName())); } } /** * Prevents possible dead loops when a shortcut has a reference to another shortcut command in its user inputs. * @throws CommandException if the shortcut has a reference to another shortcut command. */ private void checkShortcutEligibility() throws CommandException { for (String line : shortcut.getCommandStrings()) { if (line.split(" ")[0].equals(ExecuteShortcutCommand.COMMAND_WORD)) { throw new CommandException(MESSAGE_CANNOT_CONTAIN_DO_COMMAND); } } } }
MORE rain could fall this weekend in some parts of the region than has fallen in the past two months, Weatherzone meteorologist Kim Westcott says. With 100 per cent of NSW declared in drought, many primary producers are hopeful of some rain heading into spring. Saturday will be the best chance of rain, with lighter falls expected on Sunday. Ms Westcott said the trough moving across the state will bring the region much-needed rain. “For most places it’s going to be the most rain in two months,” she said. “Start expecting rain from Saturday morning, it might be patchy in some areas, but continuous in others. “It’s quite a large system and for areas further north, [they can] expect more rain, but there will be some people who miss out entirely.” Parkes is predicted to be the wettest location across the region, with 30 millimetres of rain expected across the weekend. Around 25mm is expected in Bathurst, Cowra, Dubbo, Mudgee, Nyngan, Oberon, Orange and Wellington. While Forbes, Grenfell, Lithgow and Young should receive around 15mm if predictions are correct. Thunderstorms may occur in some areas across the weekend and Ms Westcott urged people to clear out leaves from the gutters and storm pipes of their home before the rain starts. The entire region has received well below average rainfall so far this year, with some locations receiving just one quarter of the usual long-term average. Dubbo has received the lowest rainfall when compared to the long-term average, with just 86.4mm of rain received when compared to the average rainfall to August of 395.1mm. Parkes and Wellington have received just 30 per cent of the average rainfall to this time of year – with 133.6mm compared to 406.5mm, and 108.5mm compared to 380.1mm respectively. Less than 50 per cent of the average rainfall to August has also been received in Cowra, Forbes and Orange. MORE rain could fall this weekend in some parts of the region than has fallen in the past two months, Weatherzone meteorologist Kim Westcott says. With 100 per cent of NSW declared in drought, many primary producers are hopeful of some rain heading into spring. Saturday will be the best chance of rain, with lighter falls expected on Sunday. Ms Westcott said the trough moving across the state will bring the region much-needed rain. “For most places it’s going to be the most rain in two months,” she said. “Start expecting rain from Saturday morning, it might be patchy in some areas, but continuous in others. Parkes is predicted to be the wettest location across the region, with 30 millimetres of rain expected across the weekend. Around 25mm is expected in Bathurst, Cowra, Dubbo, Mudgee, Nyngan, Oberon, Orange and Wellington. While Forbes, Grenfell, Lithgow and Young should receive around 15mm if predictions are correct. Thunderstorms may occur in some areas across the weekend and Ms Westcott urged people to clear out leaves from the gutters and storm pipes of their home before the rain starts. The entire region has received well below average rainfall so far this year, with some locations receiving just one quarter of the usual long-term average. READ ALSO: It’s Daffodil Day, but where does your donated money go to? Dubbo has received the lowest rainfall when compared to the long-term average, with just 86.4mm of rain received when compared to the average rainfall to August of 395.1mm. Parkes and Wellington have received just 30 per cent of the average rainfall to this time of year – with 133.6mm compared to 406.5mm, and 108.5mm compared to 380.1mm respectively. Less than 50 per cent of the average rainfall to August has also been received in Cowra, Forbes and Orange. For emergency help in a flood or storm call the NSW State Emergency Service on 132 500.
<gh_stars>1-10 package io.skysail.server.app.designer.fields.resources.url; import io.skysail.server.ResourceContextId; import io.skysail.server.app.designer.fields.DbEntityTrixeditorField; import io.skysail.server.app.designer.fields.resources.PutFieldResource; public class PutUrlFieldResource extends PutFieldResource<DbEntityTrixeditorField> { public PutUrlFieldResource() { addToContext(ResourceContextId.LINK_TITLE, "update Editor Field (Trix)"); } }
/* * MIT License * * Copyright (c) i509VCB<<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.i509.fabric.creativekeybinds; import org.lwjgl.glfw.GLFW; import net.minecraft.client.util.InputUtil.Type; import net.minecraft.util.Identifier; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.keybinding.FabricKeyBinding; import net.fabricmc.fabric.api.client.keybinding.KeyBindingRegistry; public final class CreativeKeybindsMod implements ClientModInitializer { private static final boolean KEYBIND_CATEGORY = KeyBindingRegistry.INSTANCE.addCategory("Creative Keybindings"); public static final FabricKeyBinding CREATIVE_TAB_PG_LEFT = FabricKeyBinding.Builder.create(new Identifier("creativekeybinds", "page_left"), Type.KEYSYM, GLFW.GLFW_KEY_LEFT, "Creative Keybindings").build(); public static final FabricKeyBinding CREATIVE_TAB_PG_RIGHT = FabricKeyBinding.Builder.create(new Identifier("creativekeybinds", "page_right"), Type.KEYSYM, GLFW.GLFW_KEY_RIGHT, "Creative Keybindings").build(); private static final boolean TAB_LEFT = KeyBindingRegistry.INSTANCE.register(CREATIVE_TAB_PG_LEFT); private static final boolean TAB_RIGHT = KeyBindingRegistry.INSTANCE.register(CREATIVE_TAB_PG_RIGHT); @Override public void onInitializeClient() { } }
<reponame>cancech/CORM #define BOOST_TEST_DYN_LINK #ifdef STAND_ALONE # define BOOST_TEST_MODULE Main #endif #include <boost/test/unit_test.hpp> #include "corm/BeanProvider.h" #include "DummyClass.h" struct BeanProviderTestCreator { corm::ValueWrapper<DummyClass>* create() { return new corm::ValueWrapper<DummyClass>(DummyClass(789)); } }; BOOST_AUTO_TEST_SUITE(BeanProvider_Test_Suite) BOOST_AUTO_TEST_CASE(Bean_creator_provider) { corm::BeanCreatorProvider<DummyClass, BeanProviderTestCreator> provider; DummyClass bean = provider.getBean(); BOOST_CHECK_EQUAL(789, bean.getValue()); // The result need not be exactly the class name, so only need to make sure that the class name is contained/represented BOOST_CHECK(provider.getType().find("DummyClass") != std::string::npos); } BOOST_AUTO_TEST_CASE(Bean_singleton_provider_reference) { corm::BeanCreatorProvider<int&, corm::SingletonBeanCreator<int&>> provider; int& bean1 = provider.getBean(); // @suppress("Method cannot be resolved") int& bean2 = provider.getBean(); // @suppress("Method cannot be resolved") BOOST_CHECK_EQUAL(&bean1, &bean2); } BOOST_AUTO_TEST_CASE(Bean_singleton_provider_pointer) { corm::BeanCreatorProvider<DummyClass*, corm::SingletonBeanCreator<DummyClass*>> provider; DummyClass* bean1 = provider.getBean(); DummyClass* bean2 = provider.getBean(); BOOST_CHECK_EQUAL(bean1, bean2); } BOOST_AUTO_TEST_CASE(Bean_factory_provider_scalar) { corm::BeanCreatorProvider<DummyClass, corm::FactoryBeanCreator<DummyClass>> provider; DummyClass bean1 = provider.getBean(); DummyClass bean2 = provider.getBean(); BOOST_CHECK(&bean1 != &bean2); } BOOST_AUTO_TEST_CASE(Bean_factory_provider_pointer) { corm::BeanCreatorProvider<int*, corm::FactoryBeanCreator<int*>> provider; int* bean1 = provider.getBean(); int* bean2 = provider.getBean(); BOOST_CHECK(bean1 != bean2); delete(bean1); delete(bean2); } BOOST_AUTO_TEST_CASE(Bean_instance_provider) { DummyClass instance(987); corm::BeanInstanceProvider<DummyClass*> provider(&instance); DummyClass* bean = provider.getBean(); BOOST_CHECK_EQUAL(instance.getValue(), bean->getValue()); BOOST_CHECK_EQUAL(&instance, bean); } BOOST_AUTO_TEST_SUITE_END()
Angular reflectance model for ridged specular surfaces, with comprehensive calculation of inter-reflections and polarization. The color of a surface structured at the mesoscopic scale differs from the one of a flat surface of the same material because of the light inter-reflections taking place in the concavities of the surface, as well as shadowing effects. The color variation arises not only in scattering materials, but also in the absence of scattering, e.g., in metals and clear dielectrics, just as a consequence of multiple specular reflections between neighboring flat facets of the surface. In this paper, we investigate such color variation in the case of an infinitely long V-shaped groove, having in mind the visual appearance of a surface composed of many structures of that sort, all parallel and identical. We develop a full model of multiple specular reflections, accounting for the ray position and orientation and the polarization effects occurring at each reflection. We compare that situation with two approximate models, more usual and easier to compute, where light is assumed to remain unpolarized all along, or where the $p$p- and $s$s-polarized components are treated separately. Spectral reflectances were predicted for various materials and angles of cavities, under diffuse illumination. In most cases, the three models predict very similar bi-hemispherical reflectances, but the hemispherical-directional reflectances can vary noticeably in certain observation directions. This study might help achieve a more physically realistic rendering of dielectric or metallic ridged surfaces in computer graphics.
def tokenize_website(self, text_chunks): tokens = self.tokenize_document(self.text_aggregator(self.delete_short_sents(text_chunks))) return tokens
package eu.qrobotics.roverruckus.teamcode.opmode.test; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; import eu.qrobotics.roverruckus.teamcode.util.StickyGamepad; @TeleOp(name = "Double Servo Programmer", group = "Test") @Disabled public class DoubleServoProgrammer extends OpMode { enum ProgrammerMode { Low, Medium, High; public double getRawValue() { switch (this) { case Low: return 0.001; case Medium: return 0.025; case High: return 0.05; default: return 0.05; } } public ProgrammerMode nextMode() { switch (this) { case Low: return ProgrammerMode.Medium; case Medium: return ProgrammerMode.High; case High: return ProgrammerMode.Low; default: return ProgrammerMode.High; } } public String stringValue() { switch (this) { case Low: return "Low"; case Medium: return "Medium"; case High: return "High"; default: return "Unknown"; } } } private Servo leftServo = null; private Servo rightServo = null; private StickyGamepad stickyGamepad = null; private boolean isLeftServoDisabled = true; private boolean isRightServoDisabled = true; private ProgrammerMode programmerMode = ProgrammerMode.High; // initial servo positions private double currentPositionLeft = 0.935; private double currentPositionRight = 0.065; private Servo scorpionLeft = null; private Servo scorpionRight = null; @Override public void init() { scorpionLeft = hardwareMap.get(Servo.class, "carutaLeft"); scorpionRight = hardwareMap.get(Servo.class, "carutaRight"); scorpionLeft.setPosition(0.55); scorpionRight.setPosition(0.435); leftServo = hardwareMap.get(Servo.class, "leftScorpion"); rightServo = hardwareMap.get(Servo.class, "rightScorpion"); stickyGamepad = new StickyGamepad(gamepad1); telemetry.addData("Initial Left Servo Position", currentPositionLeft); telemetry.addData("Initial Right Servo Position", currentPositionRight); } @Override public void loop() { stickyGamepad.update(); // set precision if (stickyGamepad.x) { programmerMode = programmerMode.nextMode(); } // set position to both servos if (stickyGamepad.right_bumper) { currentPositionLeft -= programmerMode.getRawValue(); currentPositionRight += programmerMode.getRawValue(); } else if (stickyGamepad.left_bumper) { currentPositionLeft += programmerMode.getRawValue(); currentPositionRight -= programmerMode.getRawValue(); } updateLeftServo(); updateRightServo(); updateTelemetry(); } private void updateLeftServo() { // set servo position if (stickyGamepad.dpad_down && currentPositionLeft >= programmerMode.getRawValue()) { currentPositionLeft -= programmerMode.getRawValue(); } else if (stickyGamepad.dpad_up && currentPositionLeft + programmerMode.getRawValue() <= 1) { currentPositionLeft += programmerMode.getRawValue(); } // toggle pwm if (stickyGamepad.dpad_right) { isLeftServoDisabled = !isLeftServoDisabled; // update pwm and servo position if (isLeftServoDisabled) { leftServo.getController().pwmDisable(); } else { leftServo.getController().pwmEnable(); } } leftServo.setPosition(currentPositionLeft); } private void updateRightServo() { // set servo position if (stickyGamepad.a && currentPositionRight >= programmerMode.getRawValue()) { currentPositionRight -= programmerMode.getRawValue(); } else if (stickyGamepad.y && currentPositionRight + programmerMode.getRawValue() <= 1) { currentPositionRight += programmerMode.getRawValue(); } // toggle pwm if (stickyGamepad.b) { isRightServoDisabled = !isRightServoDisabled; // update pwm and servo position if (isRightServoDisabled) { rightServo.getController().pwmDisable(); } else { rightServo.getController().pwmEnable(); } } rightServo.setPosition(currentPositionRight); } private void updateTelemetry() { telemetry.addData("Programmer Mode", programmerMode.stringValue()); telemetry.addData("Precision", programmerMode.getRawValue()); telemetry.addData("Left Servo Position", leftServo.getPosition()); telemetry.addData("Right Servo Position", rightServo.getPosition()); telemetry.addData("Left Servo Running", !isLeftServoDisabled); telemetry.addData("Right Servo Running", !isRightServoDisabled); telemetry.update(); } }
<reponame>renatoathaydes/keepup<filename>keepup-core/src/main/java/com/athaydes/keepup/api/KeepupException.java package com.athaydes.keepup.api; import java.util.function.Consumer; /** * Error that may occur during a Keepup update cycle. * <p> * Applications should handle this exception in the {@link Keepup#onError(Consumer)} callback. */ public class KeepupException extends RuntimeException { /** * Simple error codes describing at a high level what kind of issues may cause a {@link KeepupException}. */ public enum ErrorCode { APP_HOME, DOWNLOAD, LATEST_VERSION_CHECK, NO_UPDATE_CALLBACK, DONE_CALLBACK, UNPACK, VERIFY_UPDATE, CREATE_UPDATE_SCRIPT, CURRENT_NOT_JLINK_APP, UPDATE_NOT_JLINK_APP, CANNOT_REMOVE_UPDATE_ZIP, } private final ErrorCode errorCode; public KeepupException(ErrorCode errorCode, Throwable cause) { super(cause); this.errorCode = errorCode; } public KeepupException(ErrorCode errorCode, String message) { super(message); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } @Override public String toString() { return "KeepupException{" + "errorCode=" + errorCode + ", cause=" + getCause() + ", message=" + getMessage() + '}'; } }
<gh_stars>0 interface Props { children(text: string): void; } const RenderPropsComponent = (props: Props) => { return <>{props.children("render props")}</>; }; export { RenderPropsComponent };
The Molecular Basis of Glucose Galactose Malabsorption in a Large Swedish Pedigree Abstract Glucose-galactose malabsorption (GGM) is due to mutations in the gene coding for the intestinal sodium glucose cotransporter SGLT1 (SLC5A1). Here we identify the rare variant Gln457Arg (Q457R) in a large pedigree of patients in the Vsterbotten County in Northern Sweden with the clinical phenotype of GGM. The functional effect of the Q457R mutation was determined in protein expressed in Xenopus laevis oocytes using biophysical and biochemical methods. The mutant failed to transport the specific SGLT1 sugar analog -methyl-D-glucopyranoside (MDG). Q457R SGLT1 was synthesized in amounts comparable to the wild-type (WT) transporter. SGLT1 charge measurements and freeze-fracture electron microscopy demonstrated that the mutant protein was inserted into the plasma membrane. Electrophysiological experiments, both steady-state and presteady-state, demonstrated that the mutant bound sugar with an affinity lower than the WT transporter. Together with our previous studies on Q457C and Q457E mutants, we established that the positive charge on Q457R prevented the translocation of sugar from the outward-facing to inward-facing conformation. This is contrary to other GGM cases where missense mutations caused defects in trafficking SGLT1 to the plasma membrane. Thirteen GGM patients are now added to the pedigree traced back to the late 17th century. The frequency of the Q457R variant in Vsterbotten County genomes, 0.0067, is higher than in the general Swedish population, 0.0015, and higher than the general European population, 0.000067. This explains the high number of GGM cases in this region of Sweden. Introduction Next-generation sequencing has rapidly improved the ability to identify novel monogenic disorders, including congenital diarrheas and enteropathies (CODE) in young infants. 1,2 Chronic CODE disorders are generally classified as either secretory diarrheas resulting from abnormal electrolyte transport or malabsorptive diarrheas caused by failure to absorb nutrients. Malabsorption may be generalized, caused by impaired assimilation of numerous nutrients associated with abnormalities of enteroendocrine function or epithelial trafficking and polarity abnormalities. 3,4 In contrast, selective malabsorption is caused by abnormalities in the digestion or absorption of specific nutrients. The first CODE disorder described at both a clinical and molecular level was glucose-galactose malabsorption (GGM), a potentially lethal defect in intestinal sugar absorption, was independently reported in 1962. 5,6 Subsequently, this clinical phenotype was identified in 6 cases within a pedigree located in Northern Sweden. 7,8 A simple therapy, removing glucose, galactose, and lactose (and starch from older infants) from the diet, effectively treated these patients. We established that GGM is due to mutations in the gene coding for the intestinal brush border sodium glucose cotransporter SGLT1 (SLC5A1). In over 80 GGM patients, most mutations were missense, but nonsense, frameshift, splice-site, and promoter mutations were identified. The most common defect of Na + /glucose cotransport amongst the missense mutations is a failure to insert the transporter into the plasma membrane. 14 We were intrigued about the cause of GGM in the Vsterbotten pedigree traced back to the end of the 17 th century ( Figure 1). 7,8 We were fortunate to obtain a blood sample from the first case identified on the pedigree, 8 others diagnosed with the disorder and a few first-degree relatives. A common Q457R mutation was responsible for the defect in glucose and galactose transport, and subsequent studies of Q457C and Q457E mutants showed that the positive charge on Q457R is responsible. Examining whole-genome sequences of a control Vsterbotten population revealed a higher frequency of the Q457C variant than in the general Swedish and European populations. Cases We focused on identifying the mutation(s) that caused GGM in the pedigree first identified by Melin and Meewuisse in northern Sweden ( Figure 1). 7,8 Amongst the 6 patients in this pedigree, we obtained a blood sample from case 1 for genetic analysis. Ultimately, we identified an additional 16 GGM cases referred to the Department of Pediatrics at the University of Ume for diagnosis or consultation and blood samples from 9, including cases 1, 9, 10, 11, 12, 15, 16, and 17. In two cases, 9 and 11, duodenal biopsies were taken as part of their clinical care, but immunohistochemistry on patient 11 was unsuccessful for technical reasons. Patients were born between 1961 and 2004, except case 3, born in 1926 and related to cases 1 and 2. Meeuwisse and Melin reported on the diagnosis of patients 1-6. 7,8 This research was conducted in accordance with ethical standards of University of California at Los Angeles, under the jurisdiction of the Chancellor's Human Research Committee and subject to the 1964 Declarations of Helsinki and its later amendments. Written informed consent was obtained from each subject, or the parents of each minor child, for the collection of a blood sample and for sharing intestinal biopsies collected for clinical diagnosis. The newly diagnosed cases had symptoms in common with previous ones in that they presented with diarrhea within days after birth. Glucose was in their stools, and diarrhea ceased immediately when carbohydrates, apart from fructose, were removed from their diet. In addition, blood glucose levels remained flat following oral glucose tolerance tests (2 g/kg). In all cases, the diarrhea was controlled by reducing the carbohydrate content of their diet, initially by feeding an infant formula with fructose as the only carbohydrate. The parents of GGM patients were healthy, and those able to be tested had normal oral glucose tolerance tests. Interviews amongst relatives and examination of parish registers (available in the Umea City Library) were used to add new cases on the pedigree. The Northern Swedish Pedigree of GGM patients. The original pedigree, containing cases 1-6, filled symbols (square male, circle female), were traced back to a couple in the late 17 th century. 7, 8 Four suspected cases were also identified in a family with 12 children (hatched symbol) of a distant relative to case 3. Six additional GGM patients: 7, 9-12, and 14, have now been placed on this pedigree, but DNA was only obtained for 6 identified cases in all: 1, 9-12, and 3 others not placed in the pedigree. The known GGM cases were traced to 4 of the 13 siblings born between 1719 and 1724. Identification of the Mutation, Site-Directed Mutagenesis and cRNA Synthesis Genomic DNA was extracted from the blood sample of patients 1, 9, 10, 11, 12, 15, 16, and 17, and single-stranded conformational polymorphism (SSCP) screened abnormalities in the SGLT1 gene in each exon, and mutations identified by Sanger sequencing, as previously described. All patients had a mutation in exon 12, a homozygote mutation of glutamine 457 to arginine. In later cases, exon 12 of the SGLT1 gene was polymerase chain reaction (PCR) amplified and Sanger sequenced. PCR site-directed mutagenesis was performed using wild-type (WT) human SGLT1 cDNA as a template. 9,10 The sequence of the synthetic oligonucleotide used to produce the Q457R mutation in the sense orientation was 5 -CGATTACATCCGGTCCATCACCAGT-3, where the bold letter represents the mutated nucleotide. The mutant plasmid was linearized with XbaI, and in vitro transcription was performed with MEGAscript TM transcription kit from Ambion by standard methods. 9,12 Uptake and Electrophysiology Experiments on Xenopus Oocytes Mature female Xenopus laevis were anesthetized with 0.1% tricaine (Sigma-Aldrich, St Louis, MO) buffered with 0.1% NaHCO 3 to harvest a portion of the ovary. Stage V-VI oocytes were selected and maintained at 18 C in modified Barth's solution, supplemented with 50 mg l −1 gentamicin (Sigma), 5.75 mg l −1 ciprofloxacin (Bayer), and 100 mg l −1 streptomycin sulphate/100000 units l −1 penicillin G sodium (Invitrogen, Carlsbad, CA). One day after isolation, oocytes were injected with 50 ng of cRNA coding for WT hSGLT1 or mutants and incubated at 18 C for 4-7 days. Experiments were performed at 20-22 C. Noninjected (NI) oocytes from the same donor frog served as controls. All animal protocols followed guidelines approved by the University of California Chancellor's Committee on Animal Research and the ARRIVE (Animal Research: Reporting of In Vivo Experiments) guidelines 2.0. Oocytes obtained from adult X. laevis were injected with 50 nl (1g/l) of cRNA coding for WT or Q457R mutant human SGLT1. After 3 days, 50 M 14 C--methyl-D-glucoside (MDG) uptake was measured. 17,18 SGLT1 membrane currents were measured in the oocytes expressing either WT or mutant Q457R proteins, using a 2electrode voltage clamp method. 17,19,20 The steady-state sugardependent currents were obtained for each membrane voltage as the difference between the current measured at steady state in the presence and absence of sugar in 100 mM Na +. At each voltage, the currents recorded at different sugar concentrations were used to obtain the transporter's apparent affinity (K 0.5 ) for the sugar. 21 The transient SGLT1 charge movements (Q), with each 100 ms voltage pulse from the holding potential of −50 mV to each test membrane potential V m between +50 and −150 mV, were calculated by integrating the presteady-state current (current obtained at 100 mM Na + in the absence of sugar). The data were fitted to the Boltzmann equation: (Q-Q qhy )/Q max = 1/, where maximal charge Q max = Q dep -Q hyp (Q dep and Q hyp are the charges at depolarizing and hyperpolarizing limits), F is the Faraday constant, R is the gas constant, T is absolute temperature, V 0.5 is midpoint voltage, and z is the apparent valence of the voltage sensor. 20,21 The time constant ( ) of the SGLT1 transient currents (or presteady-state currents) at each membrane potential was estimated for the ON-currents when membrane potential was stepped to the test potential from the holding potential (−50 mV). The transient ON currents were fitted to a single exponential equation: I = I o exp(-t/ ), where I is the transient current (total current after subtraction of the oocyte capacitive and steady-state current), I o is the maximum current at the beginning of the pulse, and t is time after the onset of the voltagestep. 19,20,22 All the experiments were performed at 22 C. Western Blot Analysis The WT and Q457R mutant SGLT1 proteins were extracted from cRNA-injected oocytes as previously described. 11,12,23 The volume equivalent of 1/3 of oocyte was run on a 12% sodium dodecyl-sulfate polyacrylamide gel electrophoresis (SDS-PAGE) mini-gel and electro-transferred to nitrocellulose membrane. As controls, NI oocytes extracts and rabbit brush border membrane vesicles samples were loaded in the same gel. SGLT1 was detected using an anti-peptide polyclonal antibody raised to residues 602-613 in the C-terminal portion of rabbit SGLT1 at a dilution of 1:1000. 12 Freeze-fracture and Immunohistochemistry Oocytes expressing WT or Q457R mutant SGLT1 and NI oocytes were fixed and freeze-fractured as previously described. 11,24,25 Small intestinal biopsies from GGM patient 9 ( Figure 1) and a standard control subject were fixed for 2 hr in Carnoy's solution (60% absolute alcohol, 30% chloroform, 10% acetic acid) and embedded, sectioned, and immune-probed as previously described. 23 Incubation with the primary antibody was performed overnight in an anti-peptide antibody raised to residues 564-575 of the rabbit SGLT1 amino acid sequence at 1:100 dilution. 26 After washing with phosphate-buffered saline (PBS) 3 10 min, sections were covered with 10 g/ml rhodaminelabeled affinity-purified goat anti-rabbit IgG (Jackson Immuno Research Laboratories, Inc.) for 40 min and then washed with PBS 3 10 min. Nuclei were further stained with 2mg/ml DAPI (4',6-Diamidino-2-phenylindole dihydrochroride, Research Organics Inc)-for 40 min. As controls, normal tissue sections were incubated with normal rabbit serum and labeled secondary antibody, or incubated with PBS but not with primary antibody before staining with the secondary antibody. Results Molecular analysis of the SGLT1 (SLC5A1) gene in 9 GGM patients (1,9,10,11,12,15,16, and 17) revealed a variant exon 12 by SSCP, and sequencing of the exon in both alleles showed a CAG to CGG mutation at nucleotide 1380 resulting in a Q457R mutation ( Figure 2). Where genomic samples were available, parents of cases 9, 15, 16, and 17 were heterozygotes, and unaffected siblings of cases 12, 16, and 17 were either heterozygotes or normal. This confirms the autosomal recessive mode of inheritance previously noted. 7 To investigate if the Q457R mutant was functional, we measured the uptake of 50 M 14 C-MDG by oocytes injected with WT and Q457R SGLT1 cRNA ( Figure 3). Uptake by the mutant protein was 1.7% of WT uptake (180 pmoles/h/oocyte) and not different from NI oocytes (3.1 ± 0.1 and 3.4 ± 0.1 pmol/h/oocyte, respectively). These results indicate either that the mutant protein was not synthesized or that it was not trafficked correctly between the endoplasmic reticulum and the plasma membrane or functionally defective. To distinguish between these alternatives, we determined the expression of the mutant protein in oocytes using western blotting and the density of Q457R SGLT1 in the oocyte plasma membrane using freeze-fracture electron microscopy, and functional properties of Q457R using electrophysiology. Na + /glucose cotransport generates an inward Na + Figure 4. Western blot analysis of WT and Q457R mutant SGLT1 expressed in oocytes. Seven days after injection with WT or Q457R mutant cRNA, protein was extracted from 2 oocytes each. The equivalent to 1/3 oocyte was run in a 12% SDS-PAGE gel and after transfer to a nitrocellulose membrane, and was probed with an SGLT1 antipeptide antibody raised to residues 602-613, at 1:1000 dilution. Both WT and Q457R mutant proteins ran as 2 broad bands, one 70 kDa band which corresponds to the complex glycosylated form, less intense in the mutant, and another of ∼60 kDa which corresponds to core glycosylated form. 11, 23 current directly proportional to glucose transport, and SGLT1 in the plasma membrane exhibits charge movements Q that are directly proportional to the density of the protein in the membrane. 14 Western blotting shows that the mutant protein was synthesized and glycosylated, as was the WT protein ( Figure 4). The complex and core glycosylated Q457R protein pattern at 70 and 60 kD was similar for WT and mutant protein, even though the level of complex glycosylation was lighter for the mutant than WT. We have previously shown that N-linked glycosylation is not required for the functional expression of SGLT1. 27 Freezefracture electron microscopy revealed that SGLT1 was inserted into the P-face of the plasma membrane of oocytes, and the density of the 7 particles was directly proportional to SGLT1 functional expression. 24,25 Figure 5 shows representative freezefracture images of NI oocytes and oocytes injected with WT and Q457R SGLT1 cRNA. All oocytes were processed in parallel from the same donor frog after measuring SGLT1 steady-state and pre-steady-state currents (see below). The density of the SGLT1 particles in the P-face of the control oocyte was 200/m 2, and this increased to 1000/m 2 for the oocyte injected with WT SGLT1 cRNA, and 600/m 2 for Q457R SGLT1. These results for control oocytes and those injected with human WT SGLT1 cRNA agreed with previous results. 12,25 The density of Q457R in the Figure 6. Immunolocalization of SGLT1 protein in human small intestine of a normal (control) (A) and a GGM patient with the Q457R missense mutation (B). Double staining procedures shows SGLT1 (red) as a sharp line localized to the brush border of the enterocytes and the basal nucleus stained in blue. Goblet cells between the enterocytes were unstained for SGLT1. There were no differences in location of SGLT1 in enterocytes from the normal and the GGM (magnification x125). In a separate case of GGM, C292Y, the mutant protein did not reach the brush border membrane and was trapped just above the nuclei. 14 Scale bar 30 micrometers. plasma membrane was lower than for WT, and this is consistent with the lower level of functional expression of the mutant protein (on average, Q max 3.7 nC for Q457R vs. 8.8 nC for WT, see below). These results suggest that the defect in MDG uptake ( Figure 3) is not due to defective mutant Q457C SGLT1 synthesis or trafficking from the ER (endoplasmic reticulum) to the plasma membrane but to an incompetent transporter. Does the expression of mutant SGLT1 in the oocyte reflect the expression in the patient's enterocytes? Small bowel biopsies from GGM patient 9 was examined by immunohistochemistry ( Figure 6). The mutant protein was detected as a thin red line over the brush border membrane of enterocytes, just as in a biopsy from a control subject. No immunofluorescence of SGLT1 protein was detected in control sections incubated with control rabbit serum. However, given the low resolution of light microscopy, the immunofluorescence does not actually show that the mutant SGLTs are inserted into the plasma membrane of the enterocyte brush border in the GGM patient, but only close to it. Electrophysiological studies provided insight into the functional defects of Q457R SGLT1 in the plasma membrane. Figure 7 shows examples of the steady-state currents recorded in oocytes expressing the WT and Q457R proteins. The currents elicited by 25 mM MDG and 0.1 mM phlorizin for WT SGLT1 depend on voltage: inward Na + current increased in a sigmoid fashion from 0 nA at +50 mV to 1500 nA at −150 mV ( Figure 7A). This Figure 7. Steady-state currents induced by MDG and phlorizin in WT and Q457R mutant proteins. Seven days after injection with cRNA, oocytes expressing WT and mutant SGLT1 were perfused with 100 mM NaCl buffer and currents were measured using a 2-electrode voltage clamp. The difference in steady-state currents measured in the absence and in the presence of MDG or phlorizin (Pz) is plotted at each test potential from −150 to +50 mV. A. In WT, 25 mM MDG induced Na + inward current (1500 nA at −150 mV) whereas 0.1 mM Pz blocked the Na + leak current (+143 nA at −150 mV). B. In Q457R mutant, both 100 mM MDG and 0.5 mM Pz inhibited the Na + leak current (+180 and + 360 nA at −150 mV, respectively). Similar results were obtained on oocytes from 3 different frog donors. The oocyte expressing Q457R-cRNA is the same one as shown in the oocyte in Figure 8B (Q/V with and without sugar) and Figure 5 (freeze-fracture). current required the presence of external Na + and was reversibly blocked by the addition of 0.1 mM phlorizin, the specific, nontransported competitive inhibitor (not shown). The Na + /glucose current is directly proportional to the rate of glucose transport, with a coupling of 2 Na + and 1 glucose. 14 The addition of 0.1 mM phlorizin in the absence of external glucose (closed circles) produced a small outward current that reached a value of 143 nA at −150 mV. This so-called SGLT1 leak current was not observed in NI oocytes. In contrast, no inward sugar-stimulated Na + currents were observed for the mutant even when the external MDG concentration was raised to 100 mM, but instead, MDG inhibited the Na + -leak current ( Figure 7B). This leak current was blocked by 0.5 mM phlorizin and amounted to 360 nA at −150 mV. MDG reduced the Q457R leak current in a concentrationdependent manner, with an apparent inhibitory constant K i of 52 ± 4 mM, 2 orders of magnitude higher than the apparent K m for Na + /glucose cotransport (0.34 ± 0.02 mM). The K i for phlorizin, based on the concentration needed to inhibit the Q457R leak, was an order of magnitude higher than that for the WT leak. These results suggest that MDG and phlorizin bind to Q457R, albeit at low affinities. In the presence of Na + and absence of sugar, SGLT1 exhibits presteady-state currents after step changes in membrane potential. These reflect the conformational changes of the transporter in the membrane (charge movement, Q). Voltage-jump experiments showed that the mutant exhibited presteady-state currents characteristic of WT, indicating that it was in the plasma membrane. Figure 8 shows the charge/voltage relationship Q/V for WT and Q457R mutant transporters. The data were fitted to a Boltzmann relation, and the curves were similar except that Q max for Q457R was only 60% on average of that for WT, 3.7 ± 0.2 nC vs. 8.8 ± 0.3 nC. Q max is related to the number N of SGLTs in the plasma membrane: N = Q max /ze, where z is the apparent valence of the moveable charge (the limiting slope of the Q/V curve), and e is the elementary charge. 11,12,20,23,24 There were no differences in the apparent valence (z) or the V 0.5 (membrane potential for 50% maximal charge), which were 1.4 ± 0.1 and −46 ± 4 mV for the mutant, and 1.4 ± 0.1 and −50 ± 6 mV for WT. The 40% reduction in Q max for the mutant relative to the WT agrees with the freeze-fracture electron micrographs shown in Figure 5. In WT, the addition of external sugar blocked the presteadystate currents. 14,21,22 Sugar reduced Q max and shifted V 0.5 to positive values with K 0.5 values of 1 mM. Phlorizin also blocked Q max with a K i of 0.1 uM but with no shift in V 0.5. In contrast, sugar did not abolish the presteady-state currents of Q457R but instead increased Q max with a positive shift in V 0.5 ( Figure 8B). Q max, at 50 mM MDG, was 15.5 nC relative to 11.5 nC in the absence of sugar. In this experiment, V 0.5 shifted from −27 mV in the absence of sugar to +7 mV in the presence of 50 mM MDG. There was no change in z (1.1). These sugar-induced changes in capacitive current were accompanied by a shift in the voltage dependence of the relaxation time constants. The time constant was independent of voltage between +50 and −100 mV at 4 ms but increased steeply between −100 and −150 mV to 40 ms, while the time constant for WT SGLT1 increased steadily between +50 and −150 mV from 4 to 28 ms. Discussion In 1969, Meeuwisse and Melin identified 6 GGM patients in Northern Sweden, and another 4 suspected cases, who are pedigree members traced back to the 17 th century. 7,8 We have extended this discovery with an additional 11 GGM cases and placed 6 on the pedigree (Figure 1). In addition, we have identified the mutation in the SGLT1 (SLC5A1) gene responsible for the malabsorption syndrome, Q457R, in 8 cases (6,. This variant is relatively frequent, 0.0067, in the genome of 300 Vsterbotten residents over 80 years of age in the ACpop genomic database. 28 This frequency is 4.5-times higher than a cross-section of the Swedish population, 0.0015, in the SweGen genomic database, 29 and an order of magnitude higher than both the European (non-Finnish) and Finish genomes, 0.00011 and 0.00014, and 0.000067 in the GnomAD databases. 30 The high frequency of the Q457R in Vsterbotten genomes and the pedigree dating back to the 17 th century (Figure 1) is probably due to a founder effect, combined with the historic low population density and large distances between towns and villages. The Q457R mutant expressed in oocytes is defective in Na + /glucose cotransport, as judged by the lack of MDG-uptakes and absence of glucose-stimulated Na + inward currents ( Figures 3 and 7B). This defect is not due to the common trafficking defect as in other GGM mutants where the protein is trapped between the endoplasmic reticulum and the plasma membrane (D28N, L149R, C292Y, A304V, G318R, C355S, A468V, and R499H), 9,12,13 but instead a defect in glucose transport across the plasma membrane. As evident from freeze-fracture electron microscopy ( Figure 5), and current and charge movements (Figures 7 and 8A), Q457R is inserted into the plasma membrane and retains partial function. Namely, MDG blocks the Q457R Na + -leak and binds to the transporter, shifting the Q/V curves ( Figure 8B). Likely, the defective Q457R SGLT1 is also inserted into the brush border membrane of enterocytes in patients (Figure 6), unlike the C292Y GGM mutant that is trapped between the nuclei and brush border membrane. 14 For mutant Q457R, translocation of sugar across the membrane from state 3 to state 4 is blocked (k 34 = k 43 = 0). The lower affinity for sugar and phlorizin binding to C2Na2 is accounted for by reducing the ratios k 23 /k 32 and k 27 /k 72. In the absence of external glucose, there is an increase in Na + -leak due to increases in the rate-constants (k 25, k 52 ) for the transition between C2 and C5. Subsequently, the state distribution at −150 mV changes to 34 Computational and experimental approaches were used to validate the homology models. A sugar-binding site in outward open conformation. The sugar coordinating residues Q457, H83, Y290, N78, and E102 are not shown. Note that Q457R does not interact with sugar in this conformation. B. The sugar-binding site in the inward conformation. Note that the inward tilt of TM10 positions Q457 to interact with the pyranose oxygen and the C#6 -OH of glucose. C. Sugar binding site for mutant Q457R in the inward conformation. Note that in this conformation the side-chain of Arg457 encounters steric hindrance to binding with glucose. 45% C2 and 50% C5 at −150 mV, and 100% in C6 at +50 mV. The increase in Na + leak (k 25 ) reduces the charge transfer by ∼20% when membrane voltage is rapidly jumped from −150 to + 50 mV. On addition of external glucose, occupancy in C3 is increased to 90% at the expense of C5 at −150 mV and 100% in C6 at +50 mV. Thus, when voltage is jumped between −150 and +50 mV, there is a shift of V 0.5 to positive values and an increase in Q max ( Figure 8B). Molecular Basis for Q457R Transport Defect What is the molecular basis for the Q457R transport defect? Clues emerge from functional studies of other Q457 mutants expressed in oocytes: First, the Q457C-mutant, unlike Q457R, transports MDG with a K 0.5 of 13 mM compared to 0.5 mM for WT, and a Na + /glucose coupling coefficient of 6 vs. 2 for WT. 31 The latter reflects a large Na + -leak through Q457C. Phlorizin blocked transport with a K i 30-fold higher than WT; second, chemical alkylation of Q457C with MTSEA + (2-aminoethyl methanethiosulfonate hydrobromide), MTSHE 0 (2-hydroxyethyl methanethiosulfonate), and TMR6M (tetramethylrhodamine-6maleimide), but not MeMTS 0 (methyl methanethiosulfonate) or iodoacetamide, blocks transport but not sugar binding ; and third, Q457E supports Na + /glucose cotransport with an MDG K 0.5 of 2.8 mM. 33 These data suggest that the positively-charged and bulky arginine at position 457 blocks the translocation of glucose bound from the outward-facing conformation to the inward-facing conformation. Finally, inspection of structural models of human SGLT1 indicates that glucose is not bonded with Q457 on the outer end of helix 10 in the outward-open conformation but is in the inward-facing conformation with Hbonding to the pyranose oxygen and the C6 hydroxyl group. 34,35 This is facilitated by the inward movement of the outer ends of transmembrane helix 10 (TM10) toward the glucose binding site, bringing Q457 within range for H-bonding. 14,34 However, due to the bulky arginine, there is an obstruction to the inward movement of Q457R on helix 10 towards the sugar-binding site ( Figure 10). We propose the bulky positively-charged arginine at position 457 prohibits the inward tilt of TM10, thereby blocking glucose translocation. Summary We have increased the number of GGM cases assigned to an extensive pedigree in Vsterbotten County, Sweden, traced to the late 17 th century to 21, and identified the mutation Q457R in the SGLT1 (SLC5A1) gene responsible for malabsorption. In a heterologous expression system, X. laevis oocytes, we have found that the mutant protein is inserted into the plasma. In a duodenal biopsy from a GGM patient the mutant protein is in the brush border membrane of enterocytes. Among GGM patients, the insertion of Q457R protein into the plasma membrane is unique as other mutations result in trafficking defects between the ER and the membrane. The defect in glucose transport by Q457R is due to a failure in the translocation of bound glucose across the membrane. This is likely caused by the positive charge on the bulky arginine side chain restricting a key conformation change in the outer end of transmembrane helix 10, preventing occlusion of the glucose binding site. In conclusion, studies of this isolated pedigree of GGM patients confirm the autosomal recessive mode of inheritance and provides unique insight into the molecular mechanism of glucose transport by SGLT1. Acknowledgments We appreciate the technical assistance of Mike Freeman and Professor Guido Zampighi in freeze-fracture electron microscopy, advice from Dr Eric Turk and Dr Bruce Hirayama, and we thank Professor K Takata for his gift of the SGLT1 antibody used for immuno-location of SGLT1 in biopsy samples. We are grateful for the pedigree work done by the late Professor Gsta Holmgren, Department of Clinical Genetics, Ume University, Sweden. Finally, we are indebted to the patients and their families for providing blood and biopsy samples that made this study possible. MPL carried out functional assays and western blots on oocytes, immunohistochemistry on biopsy samples, and drafted the manuscript. DDL analyzed electrophysiology results, modeled the kinetics, and carried out a structural analysis of the mutant. GM and OH diagnosed the patients and added to the GGM pedigree. MGM screened patient DNA for mutations, constructed mutant plasmid for functional experiments, and drafted the manuscript. EMW directed the project, planned the experiments, analyzed all results, and wrote the final manuscript. Data Availability The data underlying this article will be shared on reasonable request to the corresponding authors. Disclosure EMW holds the position of Editorial Board Member for Function, and was blinded from reviewing or making decisions on the manuscript. Funding This study was supported by grants from the NIH (EMW, DK19567 and MGM, DK118640) and funds from the Mellinkoff Endowment. MPL was supported by a Fellowship from the Ministry of Education and Science, Spain.
<reponame>arvidhuss/qi4j-sdk /* * Copyright 2012 <NAME>. * * 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.qi4j.api.activation; /** * Assemble Activators to hook Services Activation. * * @param <ActivateeType> Type of the activatee. * * @see ActivatorAdapter * @see ServiceActivation */ public interface Activator<ActivateeType> { /** * Called before activatee activation. */ void beforeActivation( ActivateeType activating ) throws Exception; /** * Called after activatee activation. */ void afterActivation( ActivateeType activated ) throws Exception; /** * Called before activatee passivation. */ void beforePassivation( ActivateeType passivating ) throws Exception; /** * Called after activatee passivation. */ void afterPassivation( ActivateeType passivated ) throws Exception; }
<gh_stars>0 /******************************************************************************** * * * Assembler optimized operations * * * *********************************************************************************/ #ifndef ASSEMBLER_OPTIMIZED_OPERATIONS_H #define ASSEMBLER_OPTIMIZED_OPERATIONS_H #include "types.h" #ifdef __cplusplus extern "C" { #endif #if defined(_MSC_VER) && ((defined(_M_IX86) && _M_IX86>=400) || (defined(_M_AMD64) || defined(_M_X64))) // Get the intrinsic definitions #if defined(_M_X64) || _M_IX86_FP>=1 #include "xmmintrin.h" // For mm_prefetch #endif #if defined(_M_X64) || _M_IX86_FP>=2 #include "emmintrin.h" #endif #ifndef BitScanForward // Try to avoid pulling in WinNT.h #ifdef __cplusplus extern "C" unsigned char _BitScanForward(unsigned long *index, unsigned long mask); extern "C" unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); #else unsigned char _BitScanForward(unsigned long *index, unsigned long mask); unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); #endif #define BitScanForward _BitScanForward #define BitScanReverse _BitScanReverse #pragma intrinsic(_BitScanForward) #pragma intrinsic(_BitScanReverse) #if defined(_M_AMD64) || defined(_M_X64) #ifdef __cplusplus extern "C" unsigned char _BitScanForward64(unsigned long *index, unsigned __int64 mask); extern "C" unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask); #else unsigned char _BitScanForward64(unsigned long *index, unsigned long mask); unsigned char _BitScanReverse64(unsigned long *index, unsigned long mask); #endif #define BitScanForward64 _BitScanForward64 #define BitScanReverse64 _BitScanReverse64 #pragma intrinsic(_BitScanForward64) #pragma intrinsic(_BitScanReverse64) #endif #endif #include <stdlib.h> // For byteswap // unsigned short __cdecl _byteswap_ushort(unsigned short); // unsigned long __cdecl _byteswap_ulong (unsigned long); // unsigned __int64 __cdecl _byteswap_uint64(unsigned __int64); #pragma intrinsic(_byteswap_ushort) #pragma intrinsic(_byteswap_ulong) #pragma intrinsic(_byteswap_uint64) /* One has a choice of increments: 32 for P6, 64 for Athlon and 128 for P4, so we choose 64 */ INLINE void myprefetchmemT(const void *ptr) { #if defined(_M_X64) || _M_IX86_FP>=1 _mm_prefetch((const char *) ptr, _MM_HINT_T2); #endif } INLINE void myprefetchmemNT(const void *ptr) { #if defined(_M_X64) || _M_IX86_FP>=1 _mm_prefetch((const char *) ptr, _MM_HINT_NTA); #endif } INLINE u32 _mybitscan(u32 x) { u32 m; #if defined(BitScanForward) unsigned long _m; BitScanForward(&_m, x); m=(unsigned int) _m; #else #error Unknown implementation #endif return m; } INLINE u32 mybitscan(u32 x) { return (0==x)?32:_mybitscan(x); } INLINE u32 _mybitscan64(u64 x) { u32 m; #if defined(BitScanForward64) unsigned long _m; BitScanForward64(&_m, x); m=(unsigned int) _m; #else u32 *_x=(u32 *) &x; m=mybitscan(_x[0]); if(32==m) m=32+mybitscan(_x[1]); #endif return m; } INLINE u32 mybitscan64(u64 x) { return (0==x)?64:_mybitscan64(x); } INLINE u32 _mybitscanrev(u32 x) { u32 m; #if defined(BitScanReverse) unsigned long _m; BitScanReverse(&_m, x); m=(unsigned int) _m; #else #error Unknown implementation #endif return m; } INLINE u32 mybitscanrev(u32 x) { return (0==x)?32:_mybitscanrev(x); } INLINE u32 mybitscanrev_add1(u32 x) { return (0==x)?0:(_mybitscanrev(x)+1); } INLINE u32 _mybitscanrev64(u64 x) { u32 m; #if defined(BitScanReverse64) unsigned long _m; BitScanReverse64(&_m, x); m=(unsigned int) _m; #else u32 *_x=(u32 *) &x; m=32+mybitscanrev(_x[1]); if(64==m) { m=mybitscanrev(_x[0]); if(32==m) m=64; } #endif return m; } INLINE u32 mybitscanrev64(u64 x) { return (0==x)?64:_mybitscanrev64(x); } INLINE u32 mybitscanrev64_add1(u64 x) { return (0==x)?0:(_mybitscanrev64(x)+1); } // INLINE void myendianswap16(u16 &v) // { // Can't improve on this // v=((v & 0xff)<<8)|(v>>8); // } // INLINE void myendianswap(u32 &v) // { // v=_byteswap_ulong(v); // Invokes bswap x86 instruction // } // INLINE void myendianswap64(u64 &v) // { // v=_byteswap_uint64(v); // Invokes bswap x86 instruction // } #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) #if defined(__x86_64__) || defined(__SSE__) #include "xmmintrin.h" #endif #if defined(__x86_64__) || defined(__SSE2__) #include "emmintrin.h" #endif INLINE void myprefetchmemT(const void *ptr) { __builtin_prefetch(ptr, 0, 3); } INLINE void myprefetchmemNT(const void *ptr) { __builtin_prefetch(ptr, 0, 0); } INLINE u32 mybitscan(u32 x) { return (u32) __builtin_ctz(x); } INLINE u32 mybitscan64(u64 x) { return (u32) __builtin_ctzl(x); } INLINE u32 mybitscanrev(u32 x) { return (u32) sizeof(x)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(x); } INLINE u32 mybitscanrev64(u64 x) { return (u32) sizeof(x)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clzl(x); } INLINE void myendianswap(u16 &v) { // Can't improve on this v=((v & 0xff)<<8)|(v>>8); } INLINE void myendianswap(u32 &v) { v=__builtin_bswap32(v); } INLINE void myendianswap64(u64 &v) { v=__builtin_bswap64(v); } #else /*! \ingroup myassemblerops Pretches a cache line into the processor cache temporally (ie; it will be used multiple times) */ INLINE void myprefetchmemT(const void *ptr) { } /*! \ingroup myassemblerops Pretches a cache line into the processor cache non-temporally (ie; it will be used only once) */ INLINE void myprefetchmemNT(const void *ptr) { } /*! \ingroup myassemblerops Forward scans an unsigned integer, returning the index of the first set bit. Compiles into 21 x86 cycles with no branching, though on x86 and x64 it directly uses the bsl instruction */ INLINE u32 mybitscan(u32 x) { x = ~x & (x - 1); x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x = x + (x << 8); x = x + (x << 16); return x >> 24; } INLINE u32 mybitscan64(u64 x) { u32 m; union { u64 l; u32 i[2]; } _x; _x.l=x; m=mybitscan(_x.i[!FOX_BIGENDIAN]); if(32==m) m=32+mybitscan(_x.i[!!FOX_BIGENDIAN]); return m; } /*! \ingroup myassemblerops Backward scans an unsigned integer, returning the index of the first set bit. Compiles into roughly 24 x86 cycles with no branching, though on x86 and x64 it directly uses the bsr instruction. You should note that this implementation uses illegal C++ which may fail with aggressive enough optimisation - in this situation, enable the alternative 36 x86 cycle implementation in the source code. */ INLINE u32 mybitscanrev(u32 x) { #if 1 union { unsigned asInt[2]; double asDouble; }; int n; asDouble = (double)x + 0.5; n = (asInt[!FOX_BIGENDIAN] >> 20) - 1023; return n; #else const u32 allbits1=~(u32)0; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); x = ~x; x = x - ((x >> 1) & (allbits1/3)); x = (x & (allbits1/15*3)) + ((x >> 2) & (allbits1/15*3)); x = ((x + (x >> 4)) & (allbits1/255*15)) * (allbits1/255); x = (8*sizeof(x)-1) - (x >> (8*(sizeof(x)-1))); return (unsigned) x; #endif } INLINE u32 mybitscanrev64(u64 x) { const u64 allbits1=~(u64)0; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); x = x | (x >>32); x = ~x; x = x - ((x >> 1) & (allbits1/3)); x = (x & (allbits1/15*3)) + ((x >> 2) & (allbits1/15*3)); x = ((x + (x >> 4)) & (allbits1/255*15)) * (allbits1/255); x = (8*sizeof(x)-1) - (x >> (8*(sizeof(x)-1))); return (unsigned) x; } /*! \ingroup myassemblerops Endian swaps the two bytes at \em v */ INLINE void myendianswap16(u16 &v) { // Can't improve on this v=((v & 0xff)<<8)|(v>>8); } /*! \ingroup myassemblerops Endian swaps the four bytes at \em v */ INLINE void myendianswap(u32 &v) { u8 *p=(u8 *) &v, t; t=p[0]; p[0]=p[3]; p[3]=t; t=p[1]; p[1]=p[2]; p[2]=t; } /*! \ingroup myassemblerops Endian swaps the eight bytes at \em v */ INLINE void myendianswap64(u64 &v) { u8 *p=(u8 *) &v, t; t=p[0]; p[0]=p[7]; p[7]=t; t=p[1]; p[1]=p[6]; p[6]=t; t=p[2]; p[2]=p[5]; p[5]=t; t=p[3]; p[3]=p[4]; p[4]=t; } #endif #ifdef __cplusplus } #endif #endif // ASSEMBLER_OPTIMIZED_OPERATIONS_H
A Systematic Pipelaying Control Method Based on the Sliding Matrix for Dynamically Positioned Surface Vessels A pipelaying control method is presented in this paper which includes path planning, path guidance, and path tracking controller for dynamically positioned (DP) surface vessels based on the characteristics of the predefined path in marine pipelaying operation. The pipelaying control method depends on path coding, path selection logic system, and a sliding matrix. The sliding matrix contains a vessel local path and its specified control requirements, which can be updated by sliding down the waypoint table line by line as the vessel is traveling from one path to the next. A line of sight (LOS) algorithm is developed to calculate the desired vessel position and heading on a circular arc path. The motion controller, which can simultaneously control the vessel speed at the directions of surge and sway, is designed by decomposing the desired inertial resulting velocity into the desired body velocity components. A DP simulator for pipelaying operation is developed, and in order to verify the proposed method, a pipelaying simulation is carried out. The simulation results show that the proposed method enables the vessel to move along the desired path while maintaining a set crab angle, a specified speed, and a turning radius. The pipeline can be laid onto the specified waypoints even when the vessel is subjected to drift forces caused by ocean currents, wind, and waves.
The Scarborough storm and flood, August 1857: the Cinderella of the record book W ether M ay 215, ol. 0, o. 5 of 2013 the author was given permission to measure the device. Figure 1 shows the instrument as a whole, while Figure 2 shows the inner collecting can. The diameter of the top funnel was measured as 8 inches (203mm) as described by Symons, who states: The well known 8-inch Glaishers gauge seems to be the nearest approach we have yet to perfection. Some 43 years later Mill remarks: it is an extremely ingenious instrument, and when new and carefully handled it gives results of incomparable accuracy. But when carelessly used, and especially when it begins to fall out of repair, it is subject to errors. Measurements of the Science Museum Glaisher rain gauge showed that when overflowing it would have collected 10.8 inches (274mm) of rainfall. Thus, although it is not identical to the quoted value for the Scarborough event, it does prove that one of the Glaisher models could have caught 9.5 inches. The storm rainfall of 9.5 inches was first published in the Scarborough Gazette for 13 August. The date of the storm was printed as the 9th August, a Thursday, but this is a mistake because the previous Thursday was 6 August: the typesetter had put a six upside down. A search It was George Symons who, at his own expense, set up the British Rainfall Organisation in 1860. In spite of poor health at times, Symons personally went around much of the country inspecting the sites of observers. By 1862 he had inspected the Scarborough site, listing the keeper as Mr Roberts. The monthly rainfall totals for Scarborough are now kept in the Met Office archive, where we read a note for 1857: Aug 67 during the night waterspout burst over the town and in the morning the gauge which holds 9.50 was running over. These facts alone explain the knowledge that Symons had of the event in 1892. In 1857 the rain gauge was kept by the subcurator Arthur Roberts at his home in King Street, only a short distance from the museum in Scarborough. The original rain gauge no longer exists (Scarborough Museum, pers. comm.). The illustration of the Glaisher gauge in Negretti and Zambra does not give details of the lower canister, nor the size of the inner collecting can. The 1850s were a time of experimenting with different designs of rain gauge, so the exact design of the model bought in 1855 is unknown. However, a model exists in the Science Museum store near Wroughton (Wiltshire) and in the summer Colin Clark Charldon Hill Research Station, Bruton