content
stringlengths
7
2.61M
The reversal of anticoagulation in clinical practice Authors: A NIHR clinical lecturer in haematology, Department of Oncology and Metabolism, University of Sheffield, Sheffield, UK ; B honorary specialist registrar in haematology, Department of Haematology, Royal Hallamshire Hospital, Sheffield, UK ; C professor of haemostasis and thrombosis, Department of Infection, Immunity and Cardiovascular Disease, University of Sheffield, Sheffield, UK ; D professor of haemostasis and thrombosis, Department of Haematology, Royal Hallamshire Hospital, Sheffield, UK Authors: Sally Thomas A, B and Michael Makris C, D Introduction Since the earliest clinical investigation of heparin in the 1930s, 1 the indications for anticoagulant drugs and the number of commonly encountered agents has increased (Table 1 ). These drugs act by inhibiting different stages of the coagulation cascade that culminates in the formation of cross-linked fibrin (Fig 1 ). It is common in clinical practice to encounter patients requiring anticoagulation reversal. Indications for anticoagulation reversal include: For elective procedures and surgery, the need for anticoagulation reversal should be avoided by determining whether cessation of anticoagulant is required, and by following local bridging protocols In patients bleeding while on anticoagulants, supportive treatment including blood components and local measures should be employed alongside the steps taken to reverse the anticoagulant effect INR and APTT can be used to assess anticoagulant activity of vitamin K antagonists and unfractionated heparin respectively, but therapeutic ranges for these drugs cannot be used to interpret clotting tests in patients on other anticoagulants Specific reversal agents exist for vitamin K antagonists (vitamin K and prothrombin complex concentrate), heparins (protamine sulphate) and dabigatran (Idarucizumab) but there is currently no specific reversal agent for fondaparinux or for the oral factor Xa inhibitors KEYWORDS : anticoagulants, direct acting oral anticoagulants, reversal, haemorrhage, surgery ■ of thrombosis while anticoagulation is reversed. This can be particularly challenging in situations such as bleeding in patients with mechanical heart valves. This article will focus on urgent reversal of anticoagulation. It is important that care of patients on anticoagulant drugs is optimised so that the need for urgent reversal is minimised. The benefits should be weighed against a patient's individual bleeding risk when deciding to anticoagulate and in choice of anticoagulant, and factors including potential drug-drug interactions and the need for dose reduction considered. 2 Antiplatelet agents should be discontinued when an anticoagulant is used, except in certain circumstances. 3 An anticoagulation plan should be prepared in advance of elective procedures so that urgent reversal is not required. Table 2 summarises the length of time for which different anticoagulants should be stopped prior to an invasive procedure. Some procedures (eg joint injections, CME Haematology endoscopic procedures with a low risk of bleeding and cataract surgery) can be performed without stopping anticoagulants. If anticoagulation is not lifelong, consideration should be given to deferring the procedure until treatment is completed. If anticoagulant treatment must be interrupted, bridging protocols should be employed that take into account drug pharmacokinetics and bleeding and the thrombotic risk. 4 In urgent situations where reversal is required a combination of general measures which apply regardless of which anticoagulant a patient is taking, and drug-specific management is used. Drug specific reversal strategies are summarised in Table 3. General measures include making an assessment of the dose and timing of the drug, considering its rate of elimination, and in the case of bleeding resuscitating the patient and identifying and treating the source of bleeding. The efficacy and evidence base for specific reversal strategies varies between anticoagulants, and an understanding of this, is important when making choices about reversal. Baseline information and investigations It is important to establish what anticoagulant a patient is taking, the dose, frequency, timing of last dose and indication. The anticoagulant should be stopped. Other drugs that can affect bleeding (eg antiplatelet agents and non-steroidal antiinflammatory drugs) should also be noted. Blood tests must include a full blood count and clotting screen (prothrombin time , activated partial thromboplastin time , thrombin time and fibrinogen). Additional clotting samples for drug-specific tests may be requested, guided by discussion with haematology or the coagulation laboratory. Liver function tests and renal function tests are essential to provide information on drug elimination. Supportive measures Bleeding patients should receive appropriate resuscitation and blood-component support, which in the situation of major haemorrhage should follow national guidelines. 5 Pharmacological measures Tranexamic acid 1 g every 8 hours should be considered for patients requiring reversal of anticoagulation. Tranexamic acid is beneficial in patients bleeding following trauma, although these Vitamin K antagonists Vitamin K antagonists exert their anticoagulant effect by inhibiting the vitamin K dependent carboxylation of coagulation factors II, VII, IX and X (Fig 1 ). In the UK, warfarin is the most commonly prescribed vitamin K antagonist and we will focus on reversal of warfarin in this article. Acenocoumarol and phenindione may be encountered, and urgent reversal of all three agents follows similar principles. 8 Where cessation or dosereduction is insufficient, reversal can be achieved with oral or intravenous vitamin K or by replacement of the affected factors, a choice determined by the desired rapidity and depth of reversal. In patients with a moderately elevated international normalised ratio (INR) without bleeding, reversal is usually achieved by withholding one or two doses of warfarin, followed by dose reduction. INRs above 8 confer a substantially increased bleeding risk so anticoagulation should be reversed with oral vitamin K 1-5 mg. Oral vitamin K could also be considered in INRs of 5-8 when additional bleeding risk factors are present. 9 Oral or intravenous vitamin K administration achieves a similar INR after 24 hours, but a more rapid initial effect occurs with the intravenous route, making it preferable in bleeding patients. 10 For non-major bleeding, anticoagulation reversal can be managed with 1-3 mg intravenous vitamin K. 9 In major bleeding or for emergency procedures which cannot be delayed until vitamin K has taken effect, rapid reversal of warfarin can be achieved using four-factor prothrombin complex concentrates (PCC) at a dose of 25-50 units/kg. These contain factors II, VII, IX and X and the vitamin K dependant anticoagulant proteins protein C and protein S. PCC containing lower levels of factor VII are termed three-factor PCC. They do not data do not relate specifically to those taking anticoagulants. 6 It is reasonable to consider tranexamic acid for patients on anticoagulants with non-traumatic bleeding, provided there are not contraindications. Consideration of tranexamic acid is recommended prior to urgent surgery 4 and in adults having surgery who are expected to have moderate blood loss. 7 Local measures and intervention Attempts should be made to identify the site of bleeding and where possible apply local measures to stop it eg pressure, endoscopy, surgery and interventional radiology. Drug elimination The extent to which an anticoagulant drug is contributing to bleeding or bleeding risk should be considered. If the timing, 9 PCC is superior to fresh-frozen plasma in achieving rapid correction of INR in patients with bleeding 11 and those requiring urgent warfarin reversal for surgery or procedures. 12 5 mg vitamin K should be given concurrently to maintain reversal when factor levels fall. PCCs should be avoided outside emergency situations; they carry risks associated with plasma-derived products (such as viral infection) and are associated with a risk of thrombosis. The limited data on thrombosis suggests the risk is relatively low and it is difficult to distinguish from other patient risk factors. 13,14 Nonetheless, caution is advised in patients with recent thrombosis or surgery, cardiovascular disease, or liver disease. Unfractionated heparin Unfractionated heparin (UFH) enhances the activity of antithrombin, an endogenous negative regulator of the clotting cascade that inactivates thrombin and factor Xa (Fig 1 ) as well as factors IXa, XIa, XIIa. UFH has a short half-life (Table 1 ) so rapid reversal is achievable by stopping the infusion. 15 Protamine sulphate is licensed for reversal of UFH, acting by preventing its interaction with antithrombin. Protamine sulphate is given as a slow intravenous bolus at a dose calculated from the number of units of UFH received in the last 2 hours, with 1 mg protamine sulphate neutralising approximately 80-100 units of UFH. In excess, protamine itself acts as an anticoagulant. Protamine is derived from fish sperm and there is a risk of allergic reactions, especially in individuals with previous protamine exposure, fish allergies and following vasectomy. Low molecular weight heparin Low-molecular-weight heparins (LMWH) contain shorter polymers than UFH, and their interaction with antithrombin affects Xa more than thrombin. 1 Protamine sulphate is less effective at reversing anti-Xa activity than antithrombin activity but is recommended for LMWH reversal based on an absence of alternatives and evidence from animal studies and small retrospective studies. 16 Up to 8 hours from LMW heparin administration protamine sulphate 1 mg/100 units can be considered, with a further dose of 0.5 mg/100 units if there is ongoing bleeding. If LMWH was given over 8 hours earlier, lower doses may be used. 15 Fondaparinux Fondaparinux is a synthetic pentasaccharide not a LMWH but is considered here as it is used in similar indications and has a similar mechanism of action, by promoting the interaction of antithrombin and factor Xa (Fig 1 ). Protamine sulphate has no activity against fondaparinux. Recombinant activated factor VII can be considered for critical bleeding, 17 but this is an unlicensed indication. Direct thrombin antagonists Dabigatran and argatroban are direct thrombin antagonists. Dabigatran is given as an oral pro-drug dabigatran etexilate. Argatroban is given intravenously, its main use being in heparininduced thrombocytopaenia. By inhibiting thrombin these drugs reduce the conversion of fibrinogen to fibrin (Fig 1 ). Argatroban has a short half-life of around 45 minutes -stopping the infusion and initiating general measures should achieve reversal. There is a licensed antidote, idarucizumab, for rapid reversal of dabigatran for emergency surgery and procedures or in lifethreatening or uncontrolled bleeding. It is an engineered antibody fragment that mimics structural features of thrombin to bind dabigatran with high affinity, without binding other thrombin substrates. 18 In an open-label study, idarucizumab rapidly and completely reversed laboratory measures of anticoagulation in patients taking dabigatran. 19 Factor Xa inhibitors Rivaroxaban, apixaban and edoxaban act by inhibiting Xa (Fig 1 ). Minor bleeding should be managed using local measures and delaying the next dose or discontinuing the drug. For more severe bleeding, tranexamic acid and supportive measures should be used but there no licensed reversal agent. For life-threatening bleeding PCC may be considered; 17 however, this is an unlicensed indication and should be discussed with a haematologist. The rationale is that elevation of factor levels above normal will promote haemostasis, but there is limited evidence to suggest an improvement in laboratory measures of clotting and in bleeding from studies in animals and healthy individuals. 20 Prospective cohort studies have reported effective haemostasis using PCC, with rates of thromboembolic complications comparable to patients receiving PCC for warfarin reversal. 21,22 What is the role of laboratory measurement? Vitamin K antagonists and UFH are routinely monitored using the INR and APTT respectively. Anti Xa activity is a measure of LMWH anticoagulant effect, which may guide protamine doses. 16 The effect of direct thrombin antagonists and factor Xa inhibitors on routine clotting tests, and the utility of these tests in guiding reversal of anticoagulation is more complex. Therapeutic ranges for vitamin K antagonists and UFH should not be used to interpret clotting results in the presence of other agents. Drug-specific assays may not be available in all laboratories or out of hours. It is important to inform the laboratory of the type of anticoagulant and the timing of the last dose. The effect on routine clotting tests can depend upon which laboratory reagents are used. 23,24 Furthermore, the degree of intra-individual variation in drug levels (between peak and trough levels) and the degree of variation between individuals taking therapeutic doses must be taken into account when interpreting drug levels. 25 Table 4 summarises possible interpretations of normal and prolonged PT, APTT and TT in the presence of thrombin antagonists and Xa inhibitors, and the commonest drug-specific assays for each agent. Whether and when to restart anticoagulant drugs following reversal The bleeding risk associated with restarting a drug must be balanced against the thrombotic risk while off anticoagulation. If haemostasis is secured following a procedure or an intervention for bleeding, a pragmatic approach is to restart anticoagulation following local bridging protocols and monitoring for further bleeding. 4 Often a prophylactic dose of LMWH or a direct oral anticoagulant (DOAC) can be started 6-8 hours post procedure. Decisions are more challenging following reversal for bleeding when no procedure to achieve haemostasis is performed, for example in intracranial haemorrhage. For some patients, especially those with traumatic intracranial haemorrhage and a persistent risk of falls, consideration may be given to discontinuing anticoagulation. Data on the optimal time to reintroduce anticoagulation following intracranial haemorrhage is minimal and conflicting, with suggested times ranging from 4-7 days 26 to 10-30 weeks. 27 Future prospects Two 'universal' reversal agents are under development. Andexanet alfa, recently licensed in America, is a recombinant Xa modified to lack catalytic and membrane-binding activity but retain affinity to Xa inhibitors, LMWH, fondaparinux and antithrombin. 28 It corrects laboratory measures of coagulation in patients with major bleeding taking direct Xa inhibitors or the LMWH enoxaparin. Rates of thrombosis are higher than in studies examining PCC, but it is unclear to what extent this reflects interruption of anticoagulation and underlying pathology. 29 Ciraparantag is a synthetic molecule that binds UFH, LMWH, fondaparinux, Xa inhibitors and dabigatran. It has been examined in healthy volunteers given edoxaban where it corrected laboratory measures of clot formation. 30 ■
<reponame>NZMinusDev/frontend-core import { BEMModifier } from '@utils/devTools/scripts/ComponentCreationHelper'; import type { FormDropdownItemQuantityList } from '../form-dropdown__item-quantity-list'; abstract class FormDropdownItemQuantityListOpeningMethodModifier extends BEMModifier< FormDropdownItemQuantityList > { constructor(formDropdownItemQuantityList: FormDropdownItemQuantityList) { super(formDropdownItemQuantityList, 'formDropdownItemQuantityListOpeningMethodModifier'); } } export type { FormDropdownItemQuantityList }; export { FormDropdownItemQuantityListOpeningMethodModifier as default };
<gh_stars>100-1000 import { OpaqueToken } from '@angular/core'; import { Notify } from './notify'; import { NotificationStatic, NotificationOptions } from './notification'; import { NotificationPermission } from './notification-permission'; declare var Notification: NotificationStatic; export const NOTIFY_GLOBAL_OPTIONS = new OpaqueToken('[@ngrx/notify] Global Options'); export const NOTIFICATION_STATIC = new OpaqueToken('[@ngrx/notify] Notification Static Constructor'); const NOTIFICATION_STATIC_PROVIDER = { provide: NOTIFICATION_STATIC, useValue: Notification }; const NOTIFICATION_PERMISSION_PROVIDER = { provide: NotificationPermission, deps: [ NOTIFICATION_STATIC ], useFactory(Notification: NotificationStatic) { return new NotificationPermission(Notification); } }; const NOTIFY_PROVIDER = { provide: Notify, deps: [ NOTIFICATION_STATIC, NOTIFY_GLOBAL_OPTIONS, NotificationPermission ], useFactory(Notification: NotificationStatic, options: NotificationOptions[], permission$: NotificationPermission) { return new Notify(Notification, options, permission$); } }; const DEFAULT_GLOBAL_OPTIONS_PROVIDER = { provide: NOTIFY_GLOBAL_OPTIONS, multi: true, useValue: {} }; export const NOTIFY_PROVIDERS: any[] = [ NOTIFICATION_STATIC_PROVIDER, NOTIFICATION_PERMISSION_PROVIDER, NOTIFY_PROVIDER, DEFAULT_GLOBAL_OPTIONS_PROVIDER ];
Shoppers will have more time to return unwanted items and will be protected from hidden fees following new consumer rights rules that come into force on Friday. Under the Consumer Rights Directive, which applies across the European Union, consumers can no longer be charged high fees for buying online with their debit or credit cards. It also extends the "cooling off period", when they can cancel an order and return an item bought online, by phone or at home from seven working days to 14 calendar days. This 14-day limit starts from the moment the consumer receives the goods, rather than at the time of purchase, which was previously the case. Shoppers buying music, films and books in digital format can also use the cooling off period for the first time, although once they begin downloading the item they will lose their right to cancel. Do retailers have to honour pricing mistakes? Traders must refund customers for the product within 14 days of cancellation, including the costs of delivery. "As of today every consumer in the European Union can claim his or her rights under the Consumer Rights Directive meaning: no more pre-ticked boxes when you buy a plane ticket, no more extra charges for paying with your credit card online and no more traders telling you that you can't return a good you bought online," said Vice-President Viviane Reding, the EU's Justice Commissioner. The directive bans all hidden fees and charges, with sellers obliged to give all price information upfront. There will also be a ban on traders pre-ticking boxes for additional purchases, such as travel insurance or car rental when purchasing a flight online. Card fees must not be “excessive” and reflect the actual cost of processing a payment. Customer calling company helplines will also be charged the basic rate for calls, rather than the higher rate premium numbers. "The Consumer Rights Directive will give people greater protection against rogue traders and strengthen their rights when shopping online,” said Which? executive director Richard Lloyd. A separate bill on consumer rights is currently going through Parliament. Consumer minister Jenny Willott said: "What we want to see are empowered, savvy shoppers who know their rights, look around for the best deals and drive competition.
GLENCOE — Lee Ozmint had a good feeling about his Glencoe Yellow Jackets leading up to Friday night’s kickoff against Ashville. All that was on the minds of his team was getting a win and securing a spot in the playoffs. When the game started, the Yellow Jackets backed up the talk. Glencoe rolled to a 44-14 win over the Ashville Bulldogs for a Class 3A, Region 5 win. The victory meant a trip to the postseason for the fifth straight year. The Yellow Jackets will travel in two weeks to play Hanceville in the first round. The coach’s son, Thomas Ozmint, ran for 216 yards and two touchdowns, helping lead the Yellow Jackets to 410 yards on the ground. Quartertback Dylan Stone ran for 121 yards and a touchdown, and added two scores through the air — one to Andrew Willis and the other Dalton Roberts. While Stone and Thomas Ozmint — both juniors — may have been the standouts, on this particular night, it was all about the seniors. The Yellow Jackets (6-3, 4-3) have 10 of them — Houston Word, Chase Livingston, Tyler Johnson, Andrew Pentocost, Logan Guest, Luke Betteron, Brandon Macon, Samuel Swann, Jamon Phillips and Branton Schomburg — and Ozmint challenged his team to play for them. This one was all but over in the first quarter. Stone connected with Willis for a 14-yard TD on the Yellow Jackets’ first drive, and Joseph Bright’s first of five extra points made it 7-0. Thomas Ozmint ran for a pair of touchdowns — 5 and 27 — which were sandwiched around Stone’s 32-yard scoring sprint on a quarterback keeper. Bright made it 30-0 at halftime on a 33-yard field goal with just 1:16 remaining in the second quarter. Stone found Roberts for a 9-yard touchdown connection early in the third quarter, and Hunter Nunnally capped the Yellow Jacket scoring with a 2-yard dive with 11:53 remaining in the game. Ashville got on the board when Ryan Whisenhunt picked up a fumble and returned it 31 yards for a score at the 8:50 mark of the fourth quarter. DJ Cook scored late in the game on a 7-yard run. Ashville (1-7, 1-6), which was held to just 65 yards of offense, didn’t pick up a first down until the 5:01 mark of the fourth quarter. Cook led Ashville with 47 yards rushing and also made 15 tackles. Mason Brown led the defensive charge for Glencoe, recording nine tackles and two stops for losses. Livingston had five tackles and three stops for losses.
Comorbid depression and anxiety in later life: patterns of association, subjective well-being, and impairment. OBJECTIVE Very little epidemiological work has examined comorbidity between depression and anxiety disorders in community-dwelling older adults, despite the fact these disorders are known to co-occur in younger adults and that this co-occurrence is associated with greater clinical severity. In this study, the authors examine psychiatric comorbidity and associated impairment of four disorders (major depression, panic disorder, social phobia, and agoraphobia) in a community-based sample of adults aged 55 and older. SETTING Population-based sample of older adults (N=12,792) from the Canadian Community Health Survey-Mental Health and Well-Being (CCHS 1.2). METHOD The World Mental Health Composite International Diagnostic Interview was used to identify cases of 12-month disorder. Descriptive analysis and regression analysis is used to examine patterns of association between disorders and related impairment. RESULTS Among adults aged 55 years and older, 4.4% met the criteria for at least one disorder and 0.8% had two or more. Social phobia was the most common comorbid disorder among respondents with depression, and depression was the most common comorbid disorder among respondents with any of the anxiety disorders. Respondents who report comorbid disorders reported significantly lower well-being and greater impairment. CONCLUSION Although comorbidity between physical health conditions and depression, and between dementias and depression, are well documented among older adults, these results suggest that comorbid depression and anxiety are also prevalent in later life. The significant impact of comorbidity on function and well-being underlines the need to screen for comorbid disorders in this population.
By Mike E. Yeager Mike is the CEO of CODE and a skilled .NET and cloud developer. Mike excels at evaluating business requirements and turning them into results from development teams. He's been the Project Lead on many projects and promotes the use of modern best practices. Before coming to CODE, Mike was a business owner developing a high-profile software business in the leisure industry. He grew the business from 2 employees to over 30 before selling the company and looking for new challenges. He continues speaking at conferences and writing for trade magazines. In his spare time, Mike enjoys skiing, golfing, flying and playing ice hockey and his latest project is teaching development skills to kids in his home town of Taos, NM. Skills Maintainable code. We all want it. We all try to write it. We all suck at it. When was the last time you were asked to work on some legacy code and found it pleasant? Yeah, me either! Well, actually, that’s not entirely true. Where I work, we have standard architectures, processes and coding practices that we adhere to. I find that with very few exceptions, any time I have to go into apps written here, I have a relatively easy time of it. It’s when I have to work on code written outside the company that things get unpleasant. Even when the developer uses standard patterns and practices, working my way through the labyrinth of code is like an Odyssey. Every coder has their own style. Every app is so very different! What’s so different about the code written where I work? I know what to expect. I know where to find things. The code looks familiar. It takes minutes, not hours or days to get it built and running. The code is relatively flat and I’m in and out pretty quickly. The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well. From Lewis Carroll’s "Alice’s Adventures in Wonderland I recently had the pleasure of making a change to some code written a couple of years ago by another company. The code did some screen scraping from a website on a repeating schedule, an ugly task no matter how well it’s coded. The website was changed one day without notice and the work stopped getting done. Every hour the app wasn’t working made the problem bigger and bigger. We didn’t have much time. I was lucky in that I had previously installed and built the source code a few months back and configured it for testing. That had taken a couple of very long days because the system was entirely over-engineered and had a LOT of working parts and interactions. We found the source code in the more than two dozen projects by searching for some of the screen scraping keywords. We understood the problem and how we were going to fix it. There was a single method where the failure occurred. The code was easy enough to fix, but we would have to add a couple of parameters to the method signature. That’s when the rabbit hole dipped suddenly down. A quick look at all the places the method was called from and in turn all of the methods those methods were called from (thanks strong typing!) revealed that our code changes would touch 23 different methods in seven different classes and many of the code changes would be substantial. Furthermore, calling methods used this code for several different purposes. It was one generic method, re-used and re-cycled. Our minor code change had spider-webbed into a major change that would require substantial testing in several areas of the application. Ever optimistic, the new parameters we needed were readily available in all but two of those methods. In fact, in almost every case, the existing parameters were picked out of a class that also contained the values we needed for the new parameters. In many cases, this was all we needed to do. In some cases, we found out that the class being used wasn’t fully populated. Some of the values we needed were missing. The developers had simply re-used and re-cycled this existing class because it contained the properties they needed. Instead of creating a new, purpose-built class, they had re-used something that was close to what they needed. Of course, this isn’t something you can easily find out until run-time. Once our solution was complete, we ran a couple of test runs against the live site (there was no test system or sandbox we could use). And that’s when we found out about the missing values. More code, more testing. We did make the fix and get it into production, but it wasn’t at all easy. Not all of the issues we ran into could have been alleviated completely, but this could have gone a whole lot better and a whole lot faster. Big, flashy red flags went up when we realized that it takes about two days to configure a development environment and each time the app is deployed to a new server, but that’s a topic for a different day. Deep inheritance hierarchies were the second red flag. The partially filled class we found inherited a base class (which inherited from, which inherited from…) as well as implementing several interfaces. The class had obviously become a catch-all for lots of different purposes and in no case could we see that any process used all of what was in that class. The class was widely used, not just in the methods we would be working with and had to have all of that inheritance in order to function as it did. We were stuck with this class and all of its oddities. Deep call stacks were the third red flag. The more we worked with the code, the more we saw very deep call stacks. Everything that was done in the system seemed to drill through dozens of methods. It was easy to get lost in a debugging session trying to remember what we had started out to do. In addition, every change rippled through the call stack impacting a lot of code. Sometimes that’s a good thing. In this case, the app didn’t do all that much. In this and many other cases, the word "deep" keeps popping up on the What Went Wrong side of the ledger. Deep (and wide) inheritance hierarchies and deep call stacks especially. The very word deep implies that changes can (and usually do) ripple through every one of those layers. One of the key differences I’ve discovered is that the systems we create in-house tend to be quite flat. Things tend to be purpose-built. These systems use certain building blocks, but rarely, rarely, rarely is there more than one level of inheritance. Most classes inherit directly from Object (the .NET default). Interfaces are used sparingly except as contracts for services. If we find an existing class that is close to what we need, but not exactly what we need, we create a new class that’s exactly what we need. In return, I find that the maintenance phase of the system’s life is much more straightforward and that fallout from changes tend to be far smaller and more contained. Yes, I’ve had to make the same change in more than one place on occasion. On the other hand, I know those changes won’t snowball through the system. It’s the reason we’re all scared to touch the code in the "framework" or "foundation" classes of our mature systems. We created that code with the noble goal of putting that code in one place where we could maintain and improve it easily. But now we’re far too afraid to touch it because every change could mean drastic and far-reaching consequences. Whatever your beliefs, my experience is that flatter and more purpose-built code is easier to understand and maintain.
<filename>ui/src/shared/components/CheckPlot.tsx // Libraries import React, {FunctionComponent} from 'react' import {connect} from 'react-redux' import {Config, Table} from '@influxdata/giraffe' import {flatMap} from 'lodash' // Components import EmptyGraphMessage from 'src/shared/components/EmptyGraphMessage' import GraphLoadingDots from 'src/shared/components/GraphLoadingDots' import ThresholdMarkers from 'src/shared/components/ThresholdMarkers' // Utils import {getFormatter, filterNoisyColumns} from 'src/shared/utils/vis' // Constants import {VIS_THEME} from 'src/shared/constants' import {INVALID_DATA_COPY} from 'src/shared/copy/cell' // Types import {RemoteDataState, CheckViewProperties, TimeZone, Check} from 'src/types' import {updateTimeMachineCheck} from 'src/timeMachine/actions' import {useCheckYDomain} from 'src/alerting/utils/vis' const X_COLUMN = '_time' const Y_COLUMN = '_value' interface DispatchProps { updateTimeMachineCheck: typeof updateTimeMachineCheck } interface OwnProps { table: Table check: Partial<Check> fluxGroupKeyUnion: string[] loading: RemoteDataState timeZone: TimeZone viewProperties: CheckViewProperties children: (config: Config) => JSX.Element } type Props = OwnProps & DispatchProps const CheckPlot: FunctionComponent<Props> = ({ updateTimeMachineCheck, table, check, fluxGroupKeyUnion, loading, children, timeZone, viewProperties: {colors}, }) => { const thresholds = check && check.type === 'threshold' ? check.thresholds : [] const [yDomain, onSetYDomain, onResetYDomain] = useCheckYDomain( table.getColumn(Y_COLUMN, 'number'), thresholds ) const columnKeys = table.columnKeys const isValidView = columnKeys.includes(X_COLUMN) && columnKeys.includes(Y_COLUMN) if (!isValidView) { return <EmptyGraphMessage message={INVALID_DATA_COPY} /> } const groupKey = [...fluxGroupKeyUnion, 'result'] const xFormatter = getFormatter(table.getColumnType(X_COLUMN), { timeZone, trimZeros: false, }) const yFormatter = getFormatter(table.getColumnType(Y_COLUMN), { timeZone, trimZeros: false, }) const legendColumns = filterNoisyColumns( [...groupKey, X_COLUMN, Y_COLUMN], table ) const thresholdValues = flatMap(thresholds, (t: any) => [ t.value, t.minValue, t.maxValue, ]).filter(t => t !== undefined) const yTicks = thresholdValues.length ? thresholdValues : null const config: Config = { ...VIS_THEME, table, legendColumns, yTicks, yDomain, onSetYDomain, onResetYDomain, valueFormatters: { [X_COLUMN]: xFormatter, [Y_COLUMN]: yFormatter, }, layers: [ { type: 'line', x: X_COLUMN, y: Y_COLUMN, fill: groupKey, interpolation: 'linear', colors, }, { type: 'custom', render: ({yScale, yDomain}) => ( <ThresholdMarkers key="custom" thresholds={thresholds || []} onSetThresholds={thresholds => updateTimeMachineCheck({thresholds})} yScale={yScale} yDomain={yDomain} /> ), }, ], } return ( <div className="time-series-container time-series-container--alert-check"> {loading === RemoteDataState.Loading && <GraphLoadingDots />} {children(config)} </div> ) } const mdtp: DispatchProps = { updateTimeMachineCheck: updateTimeMachineCheck, } export default connect<{}, DispatchProps, {}>( null, mdtp )(CheckPlot)
<filename>vendor/github.com/gogo/protobuf/test/filedotname/file.dot.pb.go<gh_stars>0 // Code generated by protoc-gen-gogo. // source: file.dot.proto // DO NOT EDIT! /* Package filedotname is a generated protocol buffer package. It is generated from these files: file.dot.proto It has these top-level messages: M */ package filedotname import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" import compress_gzip "compress/gzip" import bytes "bytes" import io_ioutil "io/ioutil" import strings "strings" import reflect "reflect" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type M struct { A *string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *M) Reset() { *m = M{} } func (*M) ProtoMessage() {} func (*M) Descriptor() ([]byte, []int) { return fileDescriptorFileDot, []int{0} } func init() { proto.RegisterType((*M)(nil), "filedotname.M") } func (this *M) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return FileDotDescription() } func FileDotDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{} var gzipped = []byte{ // 3519 bytes of a gzipped FileDescriptorSet 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x5b, 0x70, 0x1c, 0xe5, 0x95, 0x56, 0xcf, 0x45, 0x9a, 0x39, 0x33, 0x1a, 0xb5, 0x5a, 0x42, 0x1e, 0x0b, 0x18, 0xcb, 0xe2, 0x26, 0x60, 0x91, 0x29, 0x63, 0x1b, 0x7b, 0xbc, 0xe0, 0x1a, 0x49, 0x63, 0x21, 0x97, 0x6e, 0xdb, 0x92, 0xc0, 0xc0, 0x43, 0xd7, 0xaf, 0xee, 0x7f, 0x46, 0x6d, 0xf7, 0x74, 0xcf, 0x76, 0xf7, 0xd8, 0x96, 0x9f, 0x4c, 0xb1, 0x97, 0xa2, 0xa8, 0xbd, 0x6f, 0xd5, 0x72, 0x5f, 0x96, 0xaa, 0x5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x77, 0xe6, 0x1d, 0x76, 0xad, 0x06, 0x6f, 0x49, 0x90, 0xab, 0x98, 0x16, 0x9e, 0x36, 0x1c, 0x9f, 0xdf, 0x81, 0x65, 0xc8, 0xda, 0x70, 0x7c, 0x12, 0xef, 0xf1, 0xbd, 0xdd, 0x9f, 0x4d, 0x0e, 0x83, 0xb4, 0xa4, 0x64, 0x41, 0x42, 0xfc, 0x3f, 0x46, 0x48, 0x68, 0x66, 0xf1, 0x83, 0xab, 0x85, 0xbe, 0x0f, 0xaf, 0x16, 0xfa, 0x7e, 0x74, 0xb5, 0xd0, 0xf7, 0xf1, 0xd5, 0x82, 0xf4, 0xe9, 0xd5, 0x82, 0xf4, 0xf9, 0xd5, 0x82, 0xf4, 0xc5, 0xd5, 0x82, 0x74, 0x65, 0xa7, 0x20, 0xbd, 0xb1, 0x53, 0x90, 0xde, 0xde, 0x29, 0x48, 0xdf, 0xdd, 0x29, 0x48, 0xef, 0xed, 0x14, 0xa4, 0x0f, 0x76, 0x0a, 0x7d, 0x1f, 0xee, 0x14, 0xfa, 0x3e, 0xde, 0x29, 0x48, 0x9f, 0xee, 0x14, 0xfa, 0x3e, 0xdf, 0x29, 0x48, 0x5f, 0xec, 0x14, 0xfa, 0xae, 0xfc, 0xa4, 0xd0, 0xf7, 0x87, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc9, 0xfe, 0xb6, 0x8b, 0xd7, 0x2d, 0x00, 0x00, } r := bytes.NewReader(gzipped) gzipr, err := compress_gzip.NewReader(r) if err != nil { panic(err) } ungzipped, err := io_ioutil.ReadAll(gzipr) if err != nil { panic(err) } if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil { panic(err) } return d } func (this *M) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*M) if !ok { that2, ok := that.(M) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *M") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *M but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *M but is not nil && this == nil") } if this.A != nil && that1.A != nil { if *this.A != *that1.A { return fmt.Errorf("A this(%v) Not Equal that(%v)", *this.A, *that1.A) } } else if this.A != nil { return fmt.Errorf("this.A == nil && that.A != nil") } else if that1.A != nil { return fmt.Errorf("A this(%v) Not Equal that(%v)", this.A, that1.A) } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized) } return nil } func (this *M) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*M) if !ok { that2, ok := that.(M) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.A != nil && that1.A != nil { if *this.A != *that1.A { return false } } else if this.A != nil { return false } else if that1.A != nil { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } type MFace interface { Proto() github_com_gogo_protobuf_proto.Message GetA() *string } func (this *M) Proto() github_com_gogo_protobuf_proto.Message { return this } func (this *M) TestProto() github_com_gogo_protobuf_proto.Message { return NewMFromFace(this) } func (this *M) GetA() *string { return this.A } func NewMFromFace(that MFace) *M { this := &M{} this.A = that.GetA() return this } func (this *M) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&filedotname.M{") if this.A != nil { s = append(s, "A: "+valueToGoStringFileDot(this.A, "string")+",\n") } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func valueToGoStringFileDot(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func NewPopulatedM(r randyFileDot, easy bool) *M { this := &M{} if r.Intn(10) != 0 { v1 := string(randStringFileDot(r)) this.A = &v1 } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedFileDot(r, 2) } return this } type randyFileDot interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneFileDot(r randyFileDot) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringFileDot(r randyFileDot) string { v2 := r.Intn(100) tmps := make([]rune, v2) for i := 0; i < v2; i++ { tmps[i] = randUTF8RuneFileDot(r) } return string(tmps) } func randUnrecognizedFileDot(r randyFileDot, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldFileDot(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldFileDot(dAtA []byte, r randyFileDot, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key)) v3 := r.Int63() if r.Intn(2) == 0 { v3 *= -1 } dAtA = encodeVarintPopulateFileDot(dAtA, uint64(v3)) case 1: dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateFileDot(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateFileDot(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *M) Size() (n int) { var l int _ = l if m.A != nil { l = len(*m.A) n += 1 + l + sovFileDot(uint64(l)) } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func sovFileDot(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozFileDot(x uint64) (n int) { return sovFileDot(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *M) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&M{`, `A:` + valueToStringFileDot(this.A) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func valueToStringFileDot(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func init() { proto.RegisterFile("file.dot.proto", fileDescriptorFileDot) } var fileDescriptorFileDot = []byte{ // 179 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x24, 0xcb, 0xaf, 0x6e, 0xc2, 0x50, 0x1c, 0xc5, 0xf1, 0xdf, 0x91, 0xeb, 0x96, 0x25, 0xab, 0x5a, 0x26, 0x4e, 0x96, 0xa9, 0x99, 0xb5, 0xef, 0x30, 0x0d, 0x86, 0x37, 0x68, 0xe9, 0x1f, 0x9a, 0x50, 0x2e, 0x21, 0xb7, 0xbe, 0x8f, 0x83, 0x44, 0x22, 0x91, 0x95, 0x95, 0xc8, 0xde, 0x1f, 0xa6, 0xb2, 0xb2, 0x92, 0x70, 0x71, 0xe7, 0x93, 0x9c, 0x6f, 0xf0, 0x5e, 0x54, 0xdb, 0x3c, 0xca, 0x8c, 0x8d, 0xf6, 0x07, 0x63, 0x4d, 0xf8, 0xfa, 0x70, 0x66, 0xec, 0x2e, 0xa9, 0xf3, 0xaf, 0xbf, 0xb2, 0xb2, 0x9b, 0x26, 0x8d, 0xd6, 0xa6, 0x8e, 0x4b, 0x53, 0x9a, 0xd8, 0x7f, 0xd2, 0xa6, 0xf0, 0xf2, 0xf0, 0xeb, 0xd9, 0xfe, 0x7c, 0x04, 0x58, 0x86, 0x6f, 0x01, 0x92, 0x4f, 0x7c, 0xe3, 0xf7, 0x65, 0x85, 0xe4, 0x7f, 0xd1, 0x39, 0x4a, 0xef, 0x28, 0x57, 0x47, 0x19, 0x1c, 0x31, 0x3a, 0x62, 0x72, 0xc4, 0xec, 0x88, 0x56, 0x89, 0xa3, 0x12, 0x27, 0x25, 0xce, 0x4a, 0x5c, 0x94, 0xe8, 0x94, 0xd2, 0x2b, 0x65, 0x50, 0x62, 0x54, 0xca, 0xa4, 0xc4, 0xac, 0x94, 0xf6, 0x46, 0xb9, 0x07, 0x00, 0x00, 0xff, 0xff, 0x3f, 0x59, 0x32, 0x8a, 0xad, 0x00, 0x00, 0x00, }
Reliability assessment of power system considering the impact of wind energy Power companies around the world are incorporating wind power into their electricity networks. Wind power is an intermittent source of energy and their technical and financial impacts on the transmission and distribution networks are not totally known. Due to this situation, it is necessary to study the influences of wind energy on electric network. The objective of this paper is to investigate the effects of wind energy on power systems reliability and operating reserve associated with wind power. The uncertainty of the wind power output means that operating reserves from conventional sources are needed. Different reliability models of power systems are presented. The paper presents a method of Monte Carlo simulation combined with Frequency & Duration method. The combination has proven to give an effective modeling for estimating system reliability and operating reserves for system with wind power. Computational results of a sample system will be included to support the proposed concept.
def decode_jwt_token(token: str) -> dict: try: data = jwt.decode( token, settings.SECRET_KEY, algorithms=settings.SIMPLE_JWT['ALGORITHM'] ) return data except PyJWTError: return {}
// This reads raw file into the script public String readFile(String path){ String code = ""; String sc = null; try{ BufferedReader br = new BufferedReader(new FileReader(path)); while (( sc = br.readLine()) != null) { if(code.equals("")){ code = sc; }else{ code = code+"\n"+sc; } } }catch (Exception e){ String out = "An error occurred inside makeSourceFile (CodeGenerator.java)"; ReqResLog(out+":\n"); ReqResLog(e.toString()); ReqResLog("\n"); } return code; }
package com.intro.client.module.event; public enum EventType { EVENT_ADD_PLAYER(0), EVENT_JOIN_WORLD(1), EVENT_REMOVE_PLAYER(2), EVENT_RENDER(3), EVENT_RENDER_POST_TICK(4), EVENT_SETTINGS_CHANGE(5), EVENT_SPAWN_ENTITY(6), EVENT_START_GAME(7), EVENT_TICK(8); private final int value; public int getIntVal() { return value; } EventType(int value) { this.value = value; } }
Particle Size Distribution Effects on the Strength Characteristic of Cemented Paste Backfill It is of great significance, for economic, environmental and security reasons, to investigate the strength characteristic of underground cemented paste backfill (CPB). Consequently, an ultrasonic test, uniaxial and triaxial compression experiment, and acoustic emission (AE) monitoring were carried out on CPB, for which the particles satisfied Talbot gradation. The homogeneity of CPB specimens was evaluated by ultrasonic pulse velocity (UPV). The stressstrain behavior and AE characteristic of CPB specimens under different Talbot indices and confining pressures were investigated. The effects of the particle size distribution and the confining pressure on the peak strength of CPB were analyzed. The strength parameter model of CPB under the coupled influence of the particle size distribution and the confining pressure was constructed based on the MohrCoulomb strength criterion. The results show that the peak strength of CPB is positively linear with confining pressure, however, the relationship between its strength parameters and the Talbot index can be characterized by a quadratic polynomial function. This suggests that there is an optimal gradation of particles reflected in the maximum strength of CPB.
Complete genomes, phylogenetic relatedness, and structural proteins of six strains of the hepatitis B virus, four of which represent two new genotypes. The genomes of six hepatitis B viral (HBV) strains were sequenced from 10 overlapping amplificates obtained by the polymerase chain reaction. Four of the strains, specifying subtypes ayw4 and adw4q-, represented on the basis of divergency within the S gene two new genomic groups identified by us. The other two strains, encoding adrq- and of Pacific origin, belonged to genomic group C. The relation of these genomes to 21 published human, 1 chimpanzee, and 4 rodent hepadnaviral genomes was analyzed by constructing a phylogenetic dendrogram. Thereby, the segregation of human HBV strains into six genomic groups was confirmed. A consistent grouping of the genomes compared was also obtained in dendrograms based on the P and S genes, although the branching order differed from that based on the entire genomes. Each of the two representatives of genomic groups E and F differed by 8.1 to 13.6% and by 12.8 to 15.5% from the genomes of the other groups and by 1.5 and 3.7% from each other. The two Pacific group C strains differed by 2.7% from each other and by 4.1 to 5.4% from other group C genomes, suggesting that they diverged early from the other group C genomes. The F strains formed the most divergent group of HBV genomes, which may be explained by their representing the original strains of the New World. Within the structural gene products, 17 and 34 amino acids unique for human HBV strains were recorded in the sequenced E and F strains, respectively. Most notable is the Ser81 to Ala81 substitution in an immunodominant region of HBcAg, and the four extra cysteine residues in HBsAg at residues 19, 183, 206, and 220, which might be engaged in additional disulphide bridges. Five residues shared by E and F strains were also unique for human HBV strains. Two of these, Leu127 and Ser140 in HBsAg, were the only substitutions that may explain the w4 reactivity shared by these HBV strains. Interestingly, the Ser140 substitution occurs in an immunodominant loop of the a determinant claimed to be important for the protective immune response to HBV vaccination.
HALIFAX — Coffee shop workers in Halifax are leading a push to unionize in what could serve as a model for baristas elsewhere in Canada, one national union says. In recent months, employees at one cafe joined a union and workers at two others have launched efforts to do the same. “We’re seeing a real phenomenon in Halifax of coffee shop workers coming together and organizing,” said Tony Tracy, Atlantic representative for the Canadian Labour Congress. “In terms of the coffee shop industry, Halifax has been a bit of an anomaly.” Employees at a Just Us! coffee shop in Halifax successfully joined Local 2 of the Service Employees International Union. The unionization came amid an allegation carried in local media reports that two workers were fired for trying to form a union, an accusation the employer denied, saying it had not been aware of a bid to unionize. Workers at two Second Cup outlets in the city also recently voted whether to join the same union, though the Labour Board has yet to release their results. “I’ve been taking calls from colleagues and co-workers across the country who’ve been following this trend in Halifax very closely and looking at it as a model for talking to young workers in other cities,” said Tracy. “I think we’ll still be analyzing this one for years to come.” Labour organizing in the service industry has been traditionally low for both ideological and economic reasons, said David Doorey, a professor of labour and employment law at York University in Toronto. “It is a highly competitive industry, and employers believe unionization will pose a threat to their profit margins,” he said in an email. “The labour force is often part-time, there is high turnover, and pay and benefits are low. Many of these workers do not have enough commitment to the job to tolerate the inevitable tensions that arise when the employer begins to resist the union campaign.” But that may be changing, Tracy said. “It’s not a temporary job anymore,” he said. “We’re seeing a lot of young workers unable to find work in their field and find themselves working in coffee shops for a period of years.” These usually university-educated workers often realize their stop-gap employment has become more long-term and they are motivated to turn these positions into good jobs, he added. The move seems to mimic a similar trend among janitors across the country, as well as one that saw Halifax’s casino workers unionize in 2007, he said. “It’s really an effort on the part of young workers stepping up and coming to the realization that these are the jobs they have — and they seem to be having for periods of years — and working to make those livable jobs.” Jason Edwards, the union representative working with the Halifax baristas, said the interest to organize came entirely from employees. “A lot of times we’ll go after an industry,” he said. “But this is really more worker-driven. It’s basically us responding to calls that we’re getting and not us cold calling.” Edwards said Local 2 of the Services Employees International Union has received calls from workers from “the entire gamut of cafes” in Halifax who have expressed interest in organizing. He said he believes the high number of students in the city, which is home to six universities with a student body of more than 30,000, is probably a factor behind the recent unionization drive. Shelby Kennedy, who has worked for more than a year at one of the Second Cup outlets in the midst of a union drive, said her interest in organizing stems from a desire to be afforded more rights, regardless of background. “This is our livelihood, whether or not you are educated,” said the 21-year-old. “We just want to be treated with dignity and respect in our jobs.”
#!/usr/bin/env python def count_lines(filename): """given a filename, this function should return a count of the number of lines in the file""" pass def write_file(filename): """given a filename, this function should write at least two lines into the file""" pass
Honestly, I need more than a week to recover from Sunday's episode of Outlander. Claire and Jamie's reunion was tender, a little silly, and a lot sexy. We even needed a special 74-minute episode to get our fill of the couple's first meeting in 20 years. But if you know anything about this show, you'll know that trouble and drama simply cling to this Scotsman and his Sassenach. In the clip above, exclusive to ELLE.com, watch an exquisitely romantic Outlander moment: Something dangerous has clearly happened, and a tearful Claire whispers to Jamie, "I've caused you so much trouble. Just dropped in out of the clear blue sky, and put your livelihood, your life in jeopardy." As for Jamie's passionate reply? You'll just have to see for yourself. Could this be Outlander's most intimate, romantic moment yet? Watch the next installment of Outlander on STARZ this Sunday at 8PM ET.
- A young boy battling a terminal brain tumor got a special visit from his favorite Marvel superhero on Tuesday. “There isn't a treatment for the type of brain cancer he has, it is terminal, so we just really just make the most of everyday and hopefully inspire others,” said Ian's mother, Kara Anderson. WATCH: Boy meets superhero Ian Hopgood was diagnosed in November after exhibiting some behavior issues in school and finally getting physically sick. "Honestly, there really aren't words to express everything he's been going through and lately it's been a little tougher, it's started to wear and tear on him a little bit that he's not like the other kids," said Anderson. His favorite superhero is the Black Panther, which Marvel is current filming in the Atlanta area. Tuesday, Chadwick Boseman, the star of the movie, stopped by to pay the young boy a visit. "We kind of go off the theory of laughter heals and joy heals, and happiness heals, so that's how we live every day because we honestly don't know what tomorrow is going to bring," said Anderson. Boseman brought Ian gifts including Black Panther action figures. The Marvel movie star spent the afternoon talking with the boy and even signed a few autographs. “So, for him to have a moment like this, and be able to jump up, I was afraid he might fall, and run to him and hug his hero, is, there really aren't words,” said Anderson. Anderson started the Facebook page Ian's Journey Of Courage in hopes of encouraging others who may be going through difficult times. “Make the most of each day. It is so easy to get caught up in the negativities. Just really choose to make a mindset of focusing on the positive. It makes all the difference in the world,” said Anderson. Anyone who wishes to help Ian and his family with medical bills can do so at gofundme.com/ians-journey. Black Panther is slated to be released in February 2018.
Probing Metal-Organic Framework Design for Adsorptive Natural Gas Purification. Parent and amine-functionalized analogues of metal-organic frameworks (MOFs), UiO-66(Zr), MIL-125(Ti), and MIL-101(Cr), were evaluated for their hydrogen sulfide (H2S) adsorption efficacy and post-exposure acid gas stability. Adsorption experiments were conducted through fixed-bed breakthrough studies utilizing multicomponent 1% H2S/99% CH4 and 1% H2S/10% CO2/89% CH4 natural gas simulant mixtures. Instability of MIL-101(Cr) materials after H2S exposure was discovered through powder X-ray diffraction and porosity measurements following adsorbent pelletization, whereas other materials retained their characteristic properties. Linker-based amine functionalities increased H2S breakthrough times and saturation capacities from their parent MOF analogues. Competitive CO2 adsorption effects were mitigated in mesoporous MIL-101(Cr) and MIL-101-NH2(Cr), in comparison to microporous UiO-66(Zr) and MIL-125(Ti) frameworks. This result suggests that the installation of H2S binding sites in large-pore MOFs could potentially enhance H2S selectivity. In situ Fourier transform infrared measurements in 10% CO2 and 5000 ppm H2S environments suggest that framework hydroxyl and amine moieties serve as H2S physisorption sites. Results from this study elucidate design strategies and stability considerations for engineering MOFs in sour gas purification applications.
package skin.support.widget; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.v7.appcompat.R; import android.support.v7.widget.AppCompatButton; import android.util.AttributeSet; /** * Created by ximsfei on 17-1-11. */ public class SkinCompatButton extends AppCompatButton implements SkinCompatSupportable { private SkinCompatTextHelper mTextHelper; private SkinCompatBackgroundHelper mBackgroundTintHelper; public SkinCompatButton(Context context) { this(context, null); } public SkinCompatButton(Context context, AttributeSet attrs) { this(context, attrs, R.attr.buttonStyle); } public SkinCompatButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mBackgroundTintHelper = new SkinCompatBackgroundHelper(this); mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr); mTextHelper = SkinCompatTextHelper.create(this); mTextHelper.loadFromAttributes(attrs, defStyleAttr); } @Override public void setBackgroundResource(@DrawableRes int resId) { super.setBackgroundResource(resId); if (mBackgroundTintHelper != null) { mBackgroundTintHelper.onSetBackgroundResource(resId); } } @Override public void setTextAppearance(int resId) { setTextAppearance(getContext(), resId); } @Override public void setTextAppearance(Context context, int resId) { super.setTextAppearance(context, resId); if (mTextHelper != null) { mTextHelper.onSetTextAppearance(context, resId); } } @Override public void setCompoundDrawablesRelativeWithIntrinsicBounds( @DrawableRes int start, @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) { super.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); } } @Override public void setCompoundDrawablesWithIntrinsicBounds( @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) { super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } @Override public void applySkin() { if (mBackgroundTintHelper != null) { mBackgroundTintHelper.applySkin(); } if (mTextHelper != null) { mTextHelper.applySkin(); } } }
<reponame>shreyasvj25/turicreate<filename>deps/src/cmake-3.9.3/Source/CTest/cmCTestUploadHandler.h /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #ifndef cmCTestUploadHandler_h #define cmCTestUploadHandler_h #include "cmConfigure.h" #include "cmCTest.h" #include "cmCTestGenericHandler.h" /** \class cmCTestUploadHandler * \brief Helper class for CTest * * Submit arbitrary files * */ class cmCTestUploadHandler : public cmCTestGenericHandler { public: typedef cmCTestGenericHandler Superclass; cmCTestUploadHandler(); ~cmCTestUploadHandler() CM_OVERRIDE {} /* * The main entry point for this class */ int ProcessHandler() CM_OVERRIDE; void Initialize() CM_OVERRIDE; /** Specify a set of files to submit. */ void SetFiles(cmCTest::SetOfStrings const& files); private: cmCTest::SetOfStrings Files; }; #endif
There are tragedies in life that shake our souls and break our hearts. 100 rounds. Police found the shooter dead. Officers never fired a shot. that was especially true today. children -- beautiful little kids between the ages of 5 and 10 years old. weddings, kids of their own. their lives to helping our children fulfill their dreams. prevent more tragedies like this, regardless of the politics. they need all of us right now. May God bless the memory of the victims. country to its core. And it has. president of the United States to tears. the same feelings that I had back on 9/11, that maybe all of us had. Connecticut Governor Dan Malloy felt the same way. themselves upon this community or the people of Connecticut. be MSNBC`s Chris Jansing, who is in Newtown, Connecticut. community tonight. What`s the latest? what can they do, how can they cope. circumstances and that is, why? turning the gun on himself. assembled media. He walked by me. and told police that his brother had some mental health issues. children would not be coming out of that school alive. to be positively identified -- Ed. how they got them out and kept them from the tragedy as best possible? one area of this school in two separate rooms. a time of great very close and personal tragedy as well, Ed. time to come to grips with tonight is the age of the children. conversation at this point about how do we stop this from happening again. Gabby Giffords and the others were shot there. how someone could do this. to put into words here tonight. leaders. Several churches in Newtown held candlelight vigils tonight. put in perspective the emotional damage facing the people of Newtown. you send your child to school. You think they`re going to be safe. a shooting at your child`s school. of the other staff that really cared about them or their friends? parents, you know, were here to take them home. of them are just absolutely -- they`re devastated. not the day to talk about gun control. SCHULTZ: Continuing coverage of the tragedy in Newtown, Connecticut. York Congressman Jerrold Nadler will weigh in with us next. more tragedies like this, regardless of the politics. legislation that he might support today. today that today is not the day to talk about gun control. out the White House and Congress for their inaction on the issue. people are murdered with guns. Today many of them were 5-year-olds. Congress to fix this problem. Calling for meaningful action is not enough. That statement from Michael Bloomberg, mayor of New York City. gun violence, and also Congressman Jerrold Nadler of New York. even Rupert Murdoch, Bill O`Reilly talking about sensible measures. takes an event like this to catalyze thing. legislation that passed soon after that. American public speaking up and making their voice heard. But this is a conversation that the American public wants to have. and not from the Congress? to pushing their Congress members to do something about this. attack in China today by a maniac on an elementary school with a knife. Twenty-two kids were injured, but not killed because he didn`t have a gun. you think this has curtailed violence in this city? and ship them illegally into New York so they get around the New York laws. more than one -- how many rifles can you have to shoot deer? history where this changes public opinion. Do you think we`re there? otherwise it will go to the next one. be changed. It needs to be voiced to our elected representative. SCHULTZ: And you think there has been a reluctance for that? felt in the halls of Congress. only. And the NRA leadership has been the enablers of the mass murders. president and the leaders of Congress to confront the NRA leadership. As Bob said, NRA members, they`re OK with reasonable gun controls. mass murder, and they`ve got to be stopped on that. GROSS: And we have to face the value of some of the rhetoric. Amendment. I like to hunt. or a target shooter who wants to target shoot. NADLER: You require background checks for sale of guns to anyone. people. There are ways of the doing that. only difference is they have intelligent gun laws and we don`t. dangerously mentally ill can get a gun without any questions asked. SCHULTZ: Well, in this situation, the mother purchased the firearm. maybe some others would actually still slip through the cracks. to have you with us tonight. I appreciate your time. We`ll have more on today`s tragic shooting in Newtown, Connecticut. tonight. I know that this is not an easy time for you. I don`t know how you train for something like this. You`re human too. have been a horrific day for all of your people there at the crime scene. investigators from the state medical examiner`s office on scene. SINKO: No, it has not. As you know, it`s a very sensitive matter. involved, other than the shooter. avenue we can to come to a conclusion here. SCHULTZ: And lieutenant, how long will it take to put this together? How long will this be considered a crime scene? up. And certainly any witnesses or leads will be followed up. the scene is there, and what it`s like for the community this evening. this. It`s going to take a long time for everyone involved. But our efforts are going towards helping the family right now. quickly as we can to try to give them the answers they deserve. about the murder of children. How are they holding up? available if they need it. But we have a strong group, and they`re holding out pretty well. Minnesota when we return. Stay with us. shot 20 children and seven adults in Newtown before 10:00 this morning. the worst in our history. And all of them have happened since Columbine. gun to school and killed nine people in Minnesota. students were either wounded or killed. Georgetown University professor Michael Eric Dyson. seeing unfold before our eyes? Americans. Because it`s not only the immediate event that induces trauma. they look upon it from afar and realize that they are similarly vulnerable. devastation upon our culture, we`re not going to be able to do anything. we need to do that right now, or else this will be repeated. to address what we are seeing, the gun violence in America? are safe in their classroom, that it must stir the heart of the nation. nation. Apparently we haven`t seen any real action in Congress since then. that nobody in Congress is fighting for change. SCHULTZ: Oh, I know. There is just not enough of them. this, though. We`re not afraid of the NRA. We`re ready to confront them. Driving made it uncool to drive drunk. SCHULTZ: And smoking, of course, is now ruled as uncool in society. But what is it going to take to change the gun culture in America? Dr. SCHULTZ: What do we have to do? This is a culture now of violence. are those who are heroic in Congress who will stand up. because it`s an American problem. the wake of the Kansas City Chiefs murder/suicide. that kind of leadership to wake this country up? statistic, which is over 180 school shooting incidents since Columbine. that don`t involve schools and go beyond schools. This is a culture. We`ve got to change it. of Newtown, Connecticut when we return. Stay with us. River runs past the main intersection. happy. It`s a family-oriented community. safest place to live in America. up in. Very quiet, very family-oriented. It`s a phenomenal place to live. Things like this shouldn`t happen here. come and be with God and try to make some sense of this. UNIDENTIFIED FEMALE: If it affects one person, it affects everybody. UNIDENTIFIED FEMALE: It breaks your heart. community has been through today is unthinkable. all the people involved, including the victims. tragedy in that community tonight. country`s gun laws? That discussion is next. Stay with us. assistance, remember all of the victims in their prayers. Bloomberg co-founded the group Mayors Against Illegal Guns. to improve national gun control laws. getting leaders in this country that are trying to forge change? of gunshot victims around the country. And they really never get over it. laws is really awe-inspiring to me. to that podium and say now is not the time to talk about our gun laws. SCHULTZ: When is the time? is the time for him to get it together. all the guns we`d like. see. Appreciate your work. Thank you. no longer be the shield for access. know we can change. I know I have changed. We need to have this discussion now.
<reponame>aaronpowers10/Clarence<gh_stars>0 /* * * Copyright (C) 2017 <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 clarence.key_reader; import java.nio.ByteBuffer; import java.util.ArrayList; public class ExpressionTable { private ArrayList<ExpressionEntry> expressionEntries; private int i1,i2,i3,i4; public ExpressionTable(ByteBuffer buffer, int size, int startIndex){ i1 = buffer.getInt(); i2 = buffer.getInt(); expressionEntries = new ArrayList<ExpressionEntry>(); int index = startIndex+1; while(index < size + startIndex){ ExpressionEntry entry = new ExpressionEntry(buffer,index); expressionEntries.add(entry); index = index + entry.entryLength(); } i3 = buffer.getInt(); i4 = buffer.getInt(); // System.out.println("EXPR TBL I1: " + i1); // System.out.println("EXPR TBL I2: " + i2); // System.out.println("EXPR TBL I3: " + i3); // System.out.println("EXPR TBL I4: " + i4); } public void write(ByteBuffer buffer) { //buffer.putInt(i1); //buffer.putInt(i2); for(ExpressionEntry entry: expressionEntries) { entry.write(buffer); } buffer.putInt(i3); //buffer.putInt(i4); } public int byteSize() { int byteSize = 16; for(ExpressionEntry entry: expressionEntries) { byteSize += entry.byteSize(); } return byteSize; } public ExpressionEntry getByPointer(int index){ for(int i=0;i<expressionEntries.size();i++){ if(expressionEntries.get(i).index() == index){ return expressionEntries.get(i); } } return null; } public String summary(int index) { return expressionEntries.get(index).summary(); } public String summaryByPointer(int pointer) { return this.getByPointer(pointer).summary(); } public int size(){ return expressionEntries.size(); } public String summary(){ String summary = "EXPRESSION TABLE SUMMARY" + System.lineSeparator(); summary = summary + "NUMBER OF ENTRIES: " + size() + System.lineSeparator(); summary = summary + "SIZE ON DISK: " + byteSize() + System.lineSeparator(); return summary; } public String processedSummary(int index) { return expressionEntries.get(index).summaryProcessed(); } public String processedSummaryByPointer(int pointer) { return getByPointer(pointer).summaryProcessed(); } public void offsetExpressions(int offset) { for(ExpressionEntry entry: expressionEntries) { entry.offsetIndex(offset); } } public void keywordAdded(int keyInd) { for(ExpressionEntry entry: expressionEntries) { entry.keywordAdded(keyInd); } } public ExpressionEntry getByIndex(int index) { return expressionEntries.get(index); } }
<reponame>caleberi/LeetCode """ Given two strings s0 and s1, return the two strings interleaved, starting with s0. If there are leftover characters in a string they should be added to the end. Constraints n ≤ 100,000 where n is the length of s0 m ≤ 100,000 where n is the length of s1 Example s0 = "abc" s1 = "xyz" returns "axbycz" """ class Solution: def solve(self, s0, s1): result = "" i = 0 j = 0 while i < len(s0) and j < len(s1): if i==j : result+=s0[i] i+=1 continue result+=s1[j] j+=1 while i < len(s0): result+=s0[i] i+=1 while j < len(s1): result+=s1[j] j+=1 return result
package com.example.misha.myapplication.module.educator; import android.app.SearchManager; import android.content.Context; import android.os.Bundle; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SearchView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.misha.myapplication.R; import com.example.misha.myapplication.common.core.BaseMainFragment; import com.example.misha.myapplication.common.core.BasePresenter; import com.example.misha.myapplication.data.preferences.Preferences; import com.example.misha.myapplication.entity.Audience; import com.example.misha.myapplication.entity.Educator; import com.example.misha.myapplication.entity.Lesson; import com.example.misha.myapplication.entity.LessonsEducator; import com.example.misha.myapplication.module.audience.SearchAudienceFragment; import com.example.misha.myapplication.module.educator.dialog.DialogFragmentListLessons; import com.example.misha.myapplication.module.schedule.edit.page.dialog.DialogFragmentListItems; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import static com.example.misha.myapplication.data.preferences.Preferences.DARK_THEME; import static com.example.misha.myapplication.data.preferences.Preferences.LIGHT_THEME; public class SearchEducatorFragment extends BaseMainFragment implements SearchEducatorFragmentView, SearchEducatorAdapter.SearchEducatorsAdapterListener, View.OnClickListener { private SearchEducatorPresenter presenter; private RecyclerView rvEducator; private SearchView searchView; private SearchEducatorAdapter searchEducatorAdapter; @Override public void onResume() { super.onResume(); getContext().setCurrentTitle(getString(R.string.title_search_educator)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); presenter = new SearchEducatorPresenter(getActivity()); setHasOptionsMenu(true); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search_educator, container, false); RelativeLayout layoutSelectDate = view.findViewById(R.id.rel_date); rvEducator = view.findViewById(R.id.rv_educators); rvEducator.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL)); ImageView imageSearchAudience = view.findViewById(R.id.image_searchAudience); if (Preferences.getInstance().getSelectedTheme().equals(DARK_THEME)) { imageSearchAudience.setImageResource(R.drawable.ic_date_range_white); } if (Preferences.getInstance().getSelectedTheme().equals(LIGHT_THEME)) { imageSearchAudience.setImageResource(R.drawable.ic_date_range_black); } rvEducator.setLayoutManager(new LinearLayoutManager(getActivity())); layoutSelectDate.setOnClickListener(this); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); presenter.init(); } @NonNull @Override protected BasePresenter getSchedulePagePresenter() { return presenter; } @Override public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); SearchManager searchManager = (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE); searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getContext().getComponentName())); searchView.setMaxWidth(Integer.MAX_VALUE); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchEducatorAdapter.getFilter().filter(query); return false; } @Override public boolean onQueryTextChange(String query) { searchEducatorAdapter.getFilter().filter(query); return false; } }); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NotNull MenuItem item) { int id = item.getItemId(); if (id == R.id.action_search) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onBackPressed() { if (!searchView.isIconified()) { searchView.setIconified(true); return false; } super.onBackPressed(); return false; } public void updateListEducators(ArrayList<Educator> requestList) { searchEducatorAdapter = new SearchEducatorAdapter(requestList, this); rvEducator.setAdapter(searchEducatorAdapter); } public void updateTextViewDate(String date) { TextView textView = getView().findViewById(R.id.text_searchAudience); textView.setText(presenter.dateForTextView(date)); } @Override public void onClick(View v) { presenter.onClickDate(v); } @Override public void showLessonsDialog(ArrayList<LessonsEducator> items, String nameEducator) { Bundle args = new Bundle(); args.putParcelableArrayList(LESSON_LIST, items); args.putString(NAME_EDUCATOR,nameEducator); DialogFragmentListLessons dialogFragment = DialogFragmentListLessons.newInstance(args); dialogFragment.show(getChildFragmentManager(), DialogFragmentListLessons.class.getSimpleName()); } @Override public void onItemClick(Educator educator, View v) { presenter.onClickItem(educator.getName()); } }
//Libraries import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; //Root component import { AppComponent } from './app.component'; //Services import { UsersService, GlobalService} from './service/model.service'; import { AppsessionService } from './service/appsession.service'; import { UserAuthenticationGuard } from './service/UserAuthenticationGuard'; import { HttpHeadersInterceptor} from './common/intercerptorservice/HttpHeaders.Interceptor'; //Module import { SharedModule } from './sharedcomponents/shared.module'; import { HomeModule } from './home/home.module'; import { SettingModule } from './setting/setting.module'; import { NotificationModule } from './notification/notification.module' import { PropertypageModule } from './property/home/propertypage.module'; import { ManagementModule } from './management/management.module'; import { SelectedPropertyResolver } from './property/service/propertInfo.resolver'; import { ReviewService} from './review/service/review.service'; //Routing import { AppRoutingModule } from "./app.routing.module"; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, SharedModule, HomeModule, SettingModule, PropertypageModule, ManagementModule, NotificationModule, AppRoutingModule, ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }) ], providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpHeadersInterceptor, multi: true, },UsersService, GlobalService, AppsessionService,ReviewService, UserAuthenticationGuard, SelectedPropertyResolver ], bootstrap: [AppComponent] }) export class AppModule { }
def job_unarchive(cls, archive_filename, check_archive_filename=True): if os.path.exists('jobspec.json'): raise IOError('jobspec.json exists, aborting job unarchiving.') with tarfile.open(archive_filename, "r:gz") as archive: archive.extract('jobspec.json') job = cls.load('jobspec.json') if check_archive_filename: archive_filename = job.output_archive_filename job.output_unarchive(archive_filename)
from __future__ import absolute_import, division, print_function import torch import torch.nn as nn from transformers import BertTokenizer, BertModel, BertPreTrainedModel, AdamW, BertConfig, BertForSequenceClassification from transformers import RobertaTokenizer, RobertaModel, RobertaConfig, RobertaForSequenceClassification from keras.preprocessing.sequence import pad_sequences from torch.nn import CrossEntropyLoss, MSELoss class BertMRC(BertPreTrainedModel): config_class = BertConfig def __init__(self, config): super(BertMRC, self).__init__(config) self.num_labels = config.num_labels self.hidden_size = config.hidden_size self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) # self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.init_weights() def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None, cls_pos=None): # print("input_ids.size(): ", input_ids.size()) # print("attention_mask.size(): ", attention_mask.size()) # print("labels.size(): ", labels.size()) # print("cls_pos.size(): ", cls_pos.size()) # Get the embedding for paraphrase # outputs = self.bert(input_ids[:, 0, :], attention_mask=attention_mask[:, 0, :]) outputs = self.bert(input_ids, attention_mask=attention_mask) # outputs = self.bert(input_ids_new, attention_mask=attention_mask_new) sequence_output = outputs[0] pooled_output = outputs[1] # print("sequence_output.size(): ", sequence_output.size()) # print("pooled_output.size(): ", pooled_output.size()) # # print("sequence_output[0][5]: ", sequence_output[0][5]) # print("sequence_output[0][23]: ", sequence_output[0][23]) # print("sequence_output[0][31]: ", sequence_output[0][31]) # print("cls_pos: ", cls_pos) # Take select the representation from coresponding index cls_output = torch.cat([torch.index_select(a, 0, i).unsqueeze(0) for a, i in zip(sequence_output, cls_pos)]) # print("cls_output.size()", cls_output.size()) # print("cls_output: ", cls_output) cls_output = self.dropout(cls_output) logits = self.classifier(cls_output) outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here # print("logits.size(): ", logits.size()) # print("labels.size(): ", labels.size()) # # print("logits: ", logits) # print("labels: ", labels) # # print("logits.view(-1, self.num_labels): ", logits.view(-1, self.num_labels)) # print("labels.view(-1, 1): ", labels.view(-1, 1)) # print("labels.view(-1): ", labels.view(-1)) if labels is not None: if self.num_labels == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) outputs = (loss,) + outputs # print("outputs: ", outputs) return outputs # (loss), logits, (hidden_states), (attentions) # class RobertaMRC(RobertaPreTrainedModel): class RobertaMRC(BertPreTrainedModel): config_class = RobertaConfig # pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "roberta" def __init__(self, config): super(RobertaMRC, self).__init__(config) self.num_labels = config.num_labels self.hidden_size = config.hidden_size self.roberta = RobertaModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) # self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.init_weights() def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None, cls_pos=None): # print("input_ids.size(): ", input_ids.size()) # print("attention_mask.size(): ", attention_mask.size()) # print("labels.size(): ", labels.size()) # print("cls_pos.size(): ", cls_pos.size()) # Get the embedding for paraphrase # outputs = self.bert(input_ids[:, 0, :], attention_mask=attention_mask[:, 0, :]) outputs = self.roberta(input_ids, attention_mask=attention_mask) # outputs = self.bert(input_ids_new, attention_mask=attention_mask_new) sequence_output = outputs[0] pooled_output = outputs[1] # print("sequence_output.size(): ", sequence_output.size()) # print("pooled_output.size(): ", pooled_output.size()) # # print("sequence_output[0][5]: ", sequence_output[0][5]) # print("sequence_output[0][23]: ", sequence_output[0][23]) # print("sequence_output[0][31]: ", sequence_output[0][31]) # print("cls_pos: ", cls_pos) # Take select the representation from coresponding index cls_output = torch.cat([torch.index_select(a, 0, i).unsqueeze(0) for a, i in zip(sequence_output, cls_pos)]) # print("cls_output.size()", cls_output.size()) # print("cls_output: ", cls_output) cls_output = self.dropout(cls_output) logits = self.classifier(cls_output) outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here # print("logits.size(): ", logits.size()) # print("labels.size(): ", labels.size()) # # print("logits: ", logits) # print("labels: ", labels) # # print("logits.view(-1, self.num_labels): ", logits.view(-1, self.num_labels)) # print("labels.view(-1, 1): ", labels.view(-1, 1)) # print("labels.view(-1): ", labels.view(-1)) if labels is not None: if self.num_labels == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) outputs = (loss,) + outputs # print("outputs: ", outputs) return outputs # (loss), logits, (hidden_states), (attentions)
Warburg effect in Gynecologic cancers Mammalian cells produce energy by oxidative phosphorylation under aerobic conditions. However, in the 1920s, Otto Warburg reported the socalled Warburg effect in which cancer cells produce ATP that is biased toward glycolysis rather than mitochondrial oxidative phosphorylation not only in anaerobic environment but also in aerobic environment. Glucose is converted into lactate without going into mitochondria after being metabolized in glycolysis. Compared with oxidative phosphorylation, the glycolysis has a faster ATP production rate but it is very inefficient, resulting in cancer cells consuming a large amount of glucose. Increased glucose metabolism has become a biomarker for cancer cells and has led to the development of positron emission tomography with fluorodeoxyglucose. Till date, the Warburg effect has been an inefficient system for cancer cells with regard to efficient energy production, but since the consumption of oxygen can be suppressed as the tumor grows in mass, it is thought that the Warburg effect is advantageous in this situation wherein the tumor can increase despite the lack of vessels. In addition, an increased lactate by the glycolysis causes acidosis in the microenvironment of tissues, which is thought to damage the surrounding normal tissues and favor the invasion and metastasis of cancer. Thus, Warburg effect is one of the key mechanisms for cancer development and will be the next promising target. In this review, we introduce key players that can be targeted in the Warburg effect and outline the prospects of treatment, targeting the Warburg effect in gynecological cancer.
/// Auto-detected speech configuration payload pub fn default_speech_config() -> ConfigPayload { #[cfg(target_os = "windows")] let platform = "Windows"; #[cfg(target_os = "osx")] let platform = "macOS"; #[cfg(target_os = "linux")] let platform = "Linux"; #[cfg(target_os = "freebsd")] let platform = "FreeBSD"; #[cfg(target_os = "dragonfly")] let platform = "DragonflyBSD"; #[cfg(target_os = "bitrig")] let platform = "Bitrig"; #[cfg(target_os = "openbsd")] let platform = "OpenBSD"; #[cfg(target_os = "netbsd")] let platform = "NetBSD"; #[cfg(target_os = "ios")] let platform = "iOS"; #[cfg(target_os = "android")] let platform = "Android"; ConfigPayload { context: ConfigPayloadContext { system: ConfigPayloadContextSystem { version: "0.0.2".to_string(), }, os: ConfigPayloadContextOs { platform: platform.to_string(), name: "Unknown".to_string(), version: "Unknown".to_string(), }, device: ConfigPayloadContextDevice { manufacturer: "Unknown".to_string(), model: "Unknown".to_string(), version: "Unknown".to_string(), }, }, } }
In Italy they are known as "bamboccioni" – or big babies – where nearly 60 per cent of 18-34 year old adults still live in their parents' home, up from almost 50 per cent since 1983. Once kept there by a love for mama's home-cooked pasta, the economic crisis has seen a boom in adults left unable to hold down a steady job or afford a home of their own. Last year a government minister, who admitted his mother washed his underwear and made his bed for him until he was 30, demanded a law obliging young Italians to leave the parental nest at 18 to stop them becoming hopelessly dependent on their parents. In the UK, the government has coined the term NEETS – not in employment, education or training. In England alone the proportion of NEETS aged 19-24 surged to 18.8 per cent of the age group, in the last quarter of 2010, up 1.4 per cent on the same period a year before. And those British adults who still live at home during their twenties and into their thirties have been somewhat cruelly dubbed KIPPERS, an acronym for "kids in parents' pockets eroding retirement savings". The proportion of British men in their 20s living with their parents has risen from 59 per cent to 80 per cent in the past 15 years, while the number of women has risen from 41 per cent to 50 per cent. The age of the average first-time buyer is now 38. In the US the phenomenon has been labelled "full nest syndrome" where adults are left struggling to support "boomerang children" who have sought refuge at home laden with student debts and facing few job prospects in a weak economy. A recent study showed almost a third of American adults age 34 and under are living with their parents. The 2006 film "Failure to Launch" told the story of a 35-year old man, played by actor Matthew McConaughey, who had it so good at home his parents feared he would never leave. They hired relationship expert (Sarah Jessica Parker) to lure him away to a life of independence.
<reponame>wofwiki/Delta<filename>src/scripts/getBannedWord.ts /** @format */ import { Message, PartialMessage } from "discord.js"; import bannedWords from "../config/bannedWords.json"; const bannedWordsArray = Object.keys(bannedWords); const exceptionWords = ["jap", "coon", "ree", "psycho"]; const whitelist = ["japanese", "japan", "raccoon", "tycoon", "cocoon"]; export function getBannedWord( message: Message | PartialMessage ): keyof typeof bannedWords | undefined { if (!message.content) { return; } const newContent = message.content.toLowerCase().replace(/[^a-zA-Z]+/g, " "); const bwOriginal = bannedWordsArray.find((bw) => message.content?.toLowerCase().includes(bw) ) as keyof typeof bannedWords; if (bwOriginal) { if (exceptionWords.includes(bwOriginal)) { // Get all the words of the content const word = newContent .split(" ") .find((w) => w.includes(bwOriginal)) as string; if (bwOriginal === "ree" && word !== bwOriginal) { // If there are trailing Es, fail it, otherwise don't because it's likely a word that isn't offensive if (word.charAt(word.indexOf(bwOriginal) + 3) === "e") { return bwOriginal; } return; // Psycho and psychopath are really the only words containing "psycho" that are offensive } else if (bwOriginal === "psycho" && word !== bwOriginal) { return; } else { // Whitelist some words if (whitelist.includes(word)) { return; } return bwOriginal; } } else { return bwOriginal; } } else { return; } }
/* * 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 brooklyn.enricher; import groovy.lang.Closure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.catalog.Catalog; import brooklyn.enricher.basic.AbstractTypeTransformingEnricher; import brooklyn.entity.Entity; import brooklyn.event.AttributeSensor; import brooklyn.event.Sensor; import brooklyn.event.SensorEvent; import brooklyn.util.GroovyJavaMethods; import brooklyn.util.flags.SetFromFlag; import brooklyn.util.javalang.JavaClassNames; import brooklyn.util.time.Duration; import com.google.common.base.Function; import com.google.common.base.Functions; /** * Converts an absolute sensor into a delta sensor (i.e. the diff between the current and previous value), * presented as a units/timeUnit based on the event timing. * <p> * NB for time (e.g. "total milliseconds consumed") use {@link TimeFractionDeltaEnricher} */ //@Catalog(name="Time-weighted Delta", description="Converts an absolute sensor into a delta sensor " // + "(i.e. the diff between the current and previous value), presented as a units/timeUnit " // + "based on the event timing.") public class TimeWeightedDeltaEnricher<T extends Number> extends AbstractTypeTransformingEnricher<T,Double> { private static final Logger LOG = LoggerFactory.getLogger(TimeWeightedDeltaEnricher.class); Number lastValue; long lastTime = -1; /** unitMillis is the number of milliseconds to apply for the conversion from input to output; * e.g. 1000 for counting things per second; * NB for time (e.g. "total milliseconds consumed") use {@link TimeFractionDeltaEnricher} */ @SetFromFlag int unitMillis; @SetFromFlag Function<Double,Double> postProcessor; // default 1 second public static <T extends Number> TimeWeightedDeltaEnricher<T> getPerSecondDeltaEnricher(Entity producer, Sensor<T> source, Sensor<Double> target) { return new TimeWeightedDeltaEnricher<T>(producer, source, target, 1000); } public TimeWeightedDeltaEnricher() { // for rebind } public TimeWeightedDeltaEnricher(Entity producer, Sensor<T> source, Sensor<Double> target, int unitMillis) { this(producer, source, target, unitMillis, Functions.<Double>identity()); } public TimeWeightedDeltaEnricher(Entity producer, Sensor<T> source, Sensor<Double> target, int unitMillis, Closure<Double> postProcessor) { this(producer, source, target, unitMillis, GroovyJavaMethods.<Double,Double>functionFromClosure(postProcessor)); } public TimeWeightedDeltaEnricher(Entity producer, Sensor<T> source, Sensor<Double> target, int unitMillis, Function<Double,Double> postProcessor) { super(producer, source, target); this.unitMillis = unitMillis; this.postProcessor = postProcessor; if (source!=null && target!=null) this.uniqueTag = JavaClassNames.simpleClassName(getClass())+":"+source.getName()+"/"+Duration.millis(unitMillis)+"->"+target.getName(); } @Override public void onEvent(SensorEvent<T> event) { onEvent(event, event.getTimestamp()); } public void onEvent(SensorEvent<T> event, long eventTime) { Number current = event.getValue(); if (current == null) { // Can't compute a delta; // don't assume current=zero because then things like requestCount->requestsPerSecond is negative! // instead assume same as last time, so delta == 0 double deltaPostProcessed = postProcessor.apply(0d); entity.setAttribute((AttributeSensor<Double>)target, deltaPostProcessed); if (LOG.isTraceEnabled()) LOG.trace("set {} to {}, {} -> {} at {}", new Object[] {this, deltaPostProcessed, lastValue, current, eventTime}); return; } if (eventTime > lastTime) { if (lastValue == null) { // cannot calculate time-based delta with a single value if (LOG.isTraceEnabled()) LOG.trace("{} received event but no last value so will not emit, null -> {} at {}", new Object[] {this, current, eventTime}); } else { double duration = (lastTime < 0) ? unitMillis : eventTime - lastTime; if (eventTime == lastTime) duration = 0.1; // 0.1 of a millisecond is a relatively small number: double delta = (current.doubleValue() - lastValue.doubleValue()) / (duration / unitMillis); double deltaPostProcessed = postProcessor.apply(delta); entity.setAttribute((AttributeSensor<Double>)target, deltaPostProcessed); if (LOG.isTraceEnabled()) LOG.trace("set {} to {}, {} -> {} at {}", new Object[] {this, deltaPostProcessed, lastValue, current, eventTime}); } lastValue = current; lastTime = eventTime; } } }
George R. R. Martin loves killing off his Game of Thrones characters for no reason and Taylor Swift loves castles! Which is to say: It was only time before the two worlds collided in a "Blank Space" parody video (and yes, there are many). This particular Nerdist spin on "Blank Space" functions as a humorous reminder that if you give Martin a "blank page" he may just kill off your favorite character. "Zombies. Axes. Giants. Blades. So many ways for a gruesome fate!"
<reponame>gnestor/plotly.py from ._stream import Stream from ._hoverlabel import Hoverlabel from plotly.graph_objs.heatmapgl import hoverlabel from ._colorbar import ColorBar from plotly.graph_objs.heatmapgl import colorbar
/** * Handles an HTTP POST request by storing the {@link Flight} specified by the flight request parameters. * It checks the parameters for validity and writes the flight to the HTTP response. */ @Override protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/plain" ); String airlineName = getParameter("name", request); if (airlineName == null) { missingRequiredParameter(response, "name"); return; } String flightNumberAsString = getParameter("number", request); if (flightNumberAsString == null) { missingRequiredParameter(response, "number"); return; } String source = getParameter("src", request); if (source == null) { missingRequiredParameter(response, "src"); return; } String departTime = getParameter("departTime", request); if (departTime == null) { missingRequiredParameter(response, "departTime"); return; } String destination = getParameter("dest", request); if (destination == null) { missingRequiredParameter(response, "dest"); return; } String arriveTime = getParameter("arriveTime", request); if (arriveTime == null) { missingRequiredParameter(response, "arriveTime"); return; } int flightNumber = 0; try { flightNumber = Integer.parseInt(flightNumberAsString); } catch (NumberFormatException e) { response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, "Invalid flight number"); } if (this.airline == null) { this.airline = new Airline(airlineName); } else if (!this.airline.getName().equals(airlineName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Airline names do not match"); return; } if (!isAirportCodeLegal(source) || !isAirportCodeLegal(destination)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Airport code is not valid"); return; } if (!parseAndVerifyDateAndTime(departTime) || !parseAndVerifyDateAndTime(arriveTime)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Date and time format incorrect"); return; } Flight flight = new Flight(flightNumber, source, departTime, destination, arriveTime); this.airline.addFlight(flight); response.setStatus( HttpServletResponse.SC_OK); }
package com.google.challenges; import java.util.Arrays; public class Zombit_Infection { public static void main(String[] args) { int[][] population = new int[][] { new int[] { 1, 2, 3 }, new int[] { 2, 3, 4 }, new int[] { 3, 2, 1 } }; System.out.println(Arrays.deepToString(answer(population, 0, 0, 2))); population = new int[][] { new int[] { 6, 7, 2, 7, 6 }, new int[] { 6, 3, 1, 4, 7 }, new int[] { 0, 2, 4, 1, 10 }, new int[] { 8, 1, 1, 4, 9 }, new int[] { 8, 7, 4, 9, 9 } }; System.out.println(Arrays.deepToString(answer(population, 2, 1, 5))); } public static int[][] answer(int[][] population, int x, int y, int strength) { if (y >= 0 && y < population.length && x >= 0 && x < population[y].length && population[y][x] != -1 && population[y][x] <= strength) { population[y][x] = -1; for (int i = -1; i <= 1; i++) { answer(population, x + i, y, strength); answer(population, x, y + i, strength); } } return population; } }
Chad Mendes’ positive drug test for Growth Hormone-Releasing Hexapeptide (GHRP-6) was triggered by a cream used to treat his lifelong skin condition, a source close to Mendes told BloodyElbow.com. The UFC featherweight contender used the cream without knowing it contained GHRP-6, per the source, who spoke on the condition of anonymity. GHRP-6 is part of a class of drugs called growth hormone releasing peptides. It “is a substance which is designed to increase your body’s natural production of growth hormone,” as written by Iain Kidd in a recent story on the banned substance. It was announced last month that Mendes had failed an out-of-competition drug test administered by USADA, the UFC’s anti-doping partner, on May 17. Mendes was later given a two-year provisional suspension retroactive to June 10. Therefore, Mendes will be eligible to compete again beginning on June 10, 2018. He will be 33 years old. “I didn't do my homework and that was a big mistake,” Mendes tweeted last month. “I own it and I'm going to pay for it.” Mendes (17-4) is a longtime featherweight contender and has fought for UFC gold on three occasions. “Money” is 1-3 in his last four outings, which includes title losses to Jose Aldo and Conor McGregor. In his last fight, he suffered a devastating stoppage loss to Frankie Edgar. His lone win since the start of 2014 is an impressive first-round TKO over Ricardo Lamas. BloodyElbow.com will provide updates on the story as it develops.
import torch import torch.nn as nn import torch.nn.functional as F from .layers import Convx2, DownBlock, UpBlock, WithSE, PreactConvx2 class HEDUNet(nn.Module): """ A straight-forward UNet implementation """ def __init__(self, input_channels, output_channels=2, base_channels=16, conv_block=Convx2, padding_mode='replicate', batch_norm=False, squeeze_excitation=False, merging='attention', stack_height=5, deep_supervision=True): super().__init__() bc = base_channels if squeeze_excitation: conv_block = WithSE(conv_block) self.init = nn.Conv2d(input_channels, bc, 1) self.output_channels = output_channels conv_args = dict( conv_block=conv_block, bn=batch_norm, padding_mode=padding_mode ) self.down_blocks = nn.ModuleList([ DownBlock((1<<i)*bc, (2<<i)*bc, **conv_args) for i in range(stack_height) ]) self.up_blocks = nn.ModuleList([ UpBlock((2<<i)*bc, (1<<i)*bc, **conv_args) for i in reversed(range(stack_height)) ]) self.predictors = nn.ModuleList([ nn.Conv2d((1<<i)*bc, output_channels, 1) for i in reversed(range(stack_height + 1)) ]) self.deep_supervision = deep_supervision self.merging = merging if merging == 'attention': self.queries = nn.ModuleList([ nn.Conv2d((1<<i)*bc, output_channels, 1) for i in reversed(range(stack_height + 1)) ]) elif merging == 'learned': self.merge_predictions = nn.Conv2d(output_channels*(stack_height+1), output_channels, 1) else: # no merging pass def forward(self, x): B, _, H, W = x.shape x = self.init(x) skip_connections = [] for block in self.down_blocks: skip_connections.append(x) x = block(x) multilevel_features = [x] for block, skip in zip(self.up_blocks, reversed(skip_connections)): x = block(x, skip) multilevel_features.append(x) predictions_list = [] full_scale_preds = [] for feature_map, predictor in zip(multilevel_features, self.predictors): prediction = predictor(feature_map) predictions_list.append(prediction) full_scale_preds.append(F.interpolate(prediction, size=(H, W), mode='bilinear', align_corners=True)) predictions = torch.cat(full_scale_preds, dim=1) if self.merging == 'attention': queries = [F.interpolate(q(feat), size=(H, W), mode='bilinear', align_corners=True) for q, feat in zip(self.queries, multilevel_features)] queries = torch.cat(queries, dim=1) queries = queries.reshape(B, -1, self.output_channels, H, W) attn = F.softmax(queries, dim=1) predictions = predictions.reshape(B, -1, self.output_channels, H, W) combined_prediction = torch.sum(attn * predictions, dim=1) elif self.merging == 'learned': combined_prediction = self.merge_predictions(predictions) else: combined_prediction = predictions_list[-1] if self.deep_supervision: return combined_prediction, list(reversed(predictions_list)) else: return combined_prediction
#!/Users/zhiyang/anaconda3/bin/python3 """ This is written by <NAME> to demonstrate how to enumerate multiple lists (of the same length) concurrently. References: + \cite{Chaudhary2019} - indicates how to enumerate two lists concurrently. - can be extended to enumerate more lists concurrently. - this answer also addresses how to enumerate lists of different lengths concurrently. """ import itertools # 3 lists of even length data1 = range(11,20) data2 = range(111,120) data3 = range(211,220) data4 = range(311,330) # Enumerate for index, (value1, value2) in enumerate(zip(data1, data2)): print(index, "value1 is:", value1, ".") print(index, "value2 is:", value2, ".") print(index, value1 + value2) for index, (value1, value2, value3) in enumerate(zip(data1, data2, data3)): print(index, "value1 is:", value1, ".") print(index, "value2 is:", value2, ".") print(index, "value3 is:", value3, ".") print(index, value1 + value2 + value3) for index, (value1, value2, value3) in enumerate(zip(data1, data2, data3)): print("value1 is:", value1, ".") print("value2 is:", value2, ".") print("value3 is:", value3, ".") print(value1 + value2 + value3) print(" Enumerating lists of different lengths, for the longest list.") for i in itertools.zip_longest(data1, data2, data3, data4): print(i) print(" Enumerating lists of different lengths, for the shorter/shortest list, and print results as a tuple.") print(" Print results as a tuple.") for i in enumerate(zip(data1, data2, data3, data4)): print(i) print(" Enumerating lists of different lengths, for the shorter/shortest list.") print(" Print results separately.") for i, (value1, value2, value3, value4) in enumerate(zip(data1, data2, data3, data4)): print(" i=",i,"= and value1",value1,"= and value2",value2,"= and value3",value3,"= and value4",value4)
A survey finds that nearly a third of people say they have been less productive since the election. Months before the election, there were reports of greater political tension in offices than in previous election cycles. In one survey from the American Psychological Association, 10 percent of respondents said that political discussions at work led to stress, feeling cynical, difficulty finishing work, lower work quality, and diminished productivity. Now, a new survey commissioned by BetterWorks—a software company that helps workers with setting and tracking goals—finds that post-election, politics is continuing to take a toll on workplace productivity. The online survey included 500 nationally representative, full-time American workers, and found that 87 percent of them read political social-media posts during the day, and nearly 50 percent reported seeing a political conversation turning into an argument in the workplace. Twenty-nine percent of respondents say they’ve been less productive since the election. While simply reading political posts at work isn’t in itself a cause for concern, it’s the potential negative impact it has on workers that could pose a challenge for employers. The issue of “not working at work” is one most employers were aware of well before the election. And the stress of the 2016 election both at home and at work was already on the radar of many managers. In fact, some companies said that the election result had become a HR challenge, according to BetterWorks. Still, companies attempted to handle the mixing of a tense political climate and workplace norms the best they could: Some held debriefing sessions about how to appropriately process the results while at work, while some managers wrote all-staff emails emphasizing respect for colleagues. Kris Duggan, the CEO of BetterWorks, says that anecdotally he’s seen some changes at the workplace since the election. That’s why the company commissioned the survey in the first place. "People spend time on Facebook, they go and look at cat photos and have some down time, and that's fine. With all the political posts, it seemed like people were getting worked up, argumentative, and distracted," says Duggan. While the survey BetterWorks conducted is small, it reveals a paradox in the productivity culture: The idea of not bringing politics to work is not just old school, it also clashes with another increasingly popular doctrine of modern work—the idea of bringing your “whole self” to the workplace. Even HR professionals admit that making the office a politics-free zone would be pretty hard at this point. In other words, there’s a need for balance that hasn’t yet been found as American politics continues to be so eventful. How managers will deal with that is ultimately up to them, but in a cultural moment where even newspapers are writing about how to manage fatigue and stress from consuming the news, it’s not surprising that workplaces will have to cope with this dynamic, too.
def annotate_datafield(field_name, annotation): try: c = DataField.objects.filter(name__iexact = field_name)[0] c.description = annotation c.save() print('--> Annotated field {}'.format(field_name)) except Exception as E: pass
// Verify a signature using a BLS public key and a message string. func (sign *Sign) Verify(pub *PublicKey, m string) bool { buf := []byte(m) return C.blsVerify(sign.getPointer(), pub.getPointer(), unsafe.Pointer(&buf[0]), C.size_t(len(buf))) == 1 }
def pop(self, k, d=_POP_DEFAULT): if d is _POP_DEFAULT: return self._ingredients.pop(k) else: return self._ingredients.pop(k, d)
The Eagles won the Catholic Conference championship outright as well as a berth in the Eastern Mass. Division 1 playoffs. Time for a little bit of history repeating? Quincy’s Billy Kiley and the rest of the Boston College High School Eagles sure hope not. With a 17-7 victory Thursday over Catholic Memorial, the Eagles (9-1, 4-0 Catholic Conference) clinched their second consecutive Catholic Conference title and set up another postseason showdown Tuesday with Everett. The Crimson Tide ended BC High’s season last year with a 26-6 win in the EMass playoffs and trounced the Eagles this year, 26-0, in a non-conference October game. “I’m thinking about Everett right now,” said Kiley, the senior quarterback who opened the scoring yesterday with a 56-yard touchdown run on BC High’s first play from scrimmage. For three quarters yesterday, the Eagles offered a glimpse at what their best game could look like as they dominated the Knights in front of more than 5,000 fans on a sun-kissed but chilly Cotter Field. After Kiley’s touchdown scamper, Catholic Memorial mustered a 55-yard drive to the Eagles’ 19-yard line but missed a 36-yard field goal in what would be their only visit to the red zone. Led by senior captain Nnamdi Obukwelu, the BC High defense stifled the Knights’ ground game, allowing only 56 rushing yards for the game, and continually harassed senior quarterback Dave Marshall. While the Knights offense sputtered, Horan and senior running back Kyle Ewanouski of Scituate hammered away as the Eagles dominated. Beginning late in the first quarter, the Eagles ran 26 plays compared to six for Catholic Memorial and had the ball for 10:43 of the first half’s final 12:34. After Marshall connected with junior Joe McCarthy to cut BC’s lead to 10-7 with 7:06 left to play, the Eagles iced the game with 65-yard touchdown drive in which Horan and Ewanouski were the only players to touch the ball. Ewanouski capped the drive with a 4-yard touchdown run with 1:46 left in the game.
// Negotiate implements the negotiate step of the SignalR connection sequence. func (c *Client) Negotiate() error { var err error c.ConnectionToken = "" u := makeURL("negotiate", c) errOccurred := false for i := 0; i < c.MaxNegotiateRetries; i++ { var req *http.Request req, err = prepareRequest(u.String(), c.Headers) if err != nil { return errors.Wrap(err, "request preparation failed") } var resp *http.Response resp, err = c.HTTPClient.Do(req) if err != nil { return errors.Wrap(err, "request failed") } switch resp.StatusCode { case 200: case 503: fallthrough case 524: fallthrough default: err = errors.Errorf("request failed: %s", resp.Status) debugMessage("%snegotiate: retrying after %s", prefixedID(c.CustomID), resp.Status) errOccurred = true time.Sleep(c.RetryWaitDuration) continue } err = c.processNegotiateResponse(resp.Body) if errOccurred { debugMessage("%sthe negotiate retry was successful", prefixedID(c.CustomID)) } return err } if errOccurred { debugMessage("%sthe negotiate retry was unsuccessful", prefixedID(c.CustomID)) } return err }
/* Find the first child of a tree. */ kid_t *tree_child( program_t *prg, const tree_t *tree ) { struct lang_el_info *lel_info = prg->rtd->lel_info; kid_t *kid = tree->child; if ( tree->flags & AF_LEFT_IGNORE ) kid = kid->next; if ( tree->flags & AF_RIGHT_IGNORE ) kid = kid->next; long object_length = lel_info[tree->id].object_length; long a; for ( a = 0; a < object_length; a++ ) kid = kid->next; return kid; }
DUBAI, United Arab Emirates – Saudi Arabia&apos;s new monarch isn&apos;t wasting time. Since assuming the throne Jan. 23, King Salman has elevated some of his closest relatives and sidelined previous power-brokers, tightened decision-making and promised lavish payouts designed to win early goodwill. While his new administration gives greater prominence to younger generations, it remains to be seen whether the swift housecleaning will lead to greater political rights and other reforms in the ultraconservative kingdom. One clear winner in the shake-up is Prince Mohammed bin Nayef, who has been interior minister since 2012 and spearheads counterterrorism efforts. King Salman named the 55-year-old as deputy crown prince in one of his first acts as king. That&apos;s a historic change, because for the first time it puts a grandson of Saudi Arabia&apos;s founder, King Abdul-Aziz Al Saud, on course to rule. He becomes second in line to the throne behind Salman&apos;s half brother Crown Prince Muqrin, who is 69. Mohammed bin Nayef, who helped to establish a center for rehabilitating former jihadists, survived a 2009 assassination attempt — a suicide bombing orchestrated by al-Qaida&apos;s branch in neighboring Yemen. He studied in the U.S. state of Oregon and has worked to strengthen American-Saudi ties. Shortly before King Abdullah&apos;s death, Mohammed bin Nayef held talks with President Barack Obama in the Oval Office focused on fighting terrorism and other security issues. Simon Henderson, director of the Gulf and Energy Policy Program at The Washington Institute, described him as "Mr. Security" with favorable reviews from U.S. officials. Another rising star is one of the king&apos;s sons, Prince Mohammed bin Salman, who is in his mid-30s. Salman named the prince as his replacement as defense minister hours after taking the throne. Mohammed bin Salman also oversees royal protocol and is a special adviser to the king, increasing his influence in the royal court. The king elevated another son, Abdulaziz bin Salman, to deputy oil minister as the kingdom weathers a severe slump in the value of its most precious commodity. The long-serving oil minister, Ali Naimi, is one of few Cabinet ministers not to lose his job in the shake-up. He oversees the management of the energy giant&apos;s nearly 270 billion barrels of oil reserves and leads the kingdom&apos;s negotiating team at OPEC meetings, where Saudi policy dominates. Abdulaziz bin Salman&apos;s promotion increases the chances that the prince could succeed Naimi. Salman also opted to retain long-serving Foreign Minister Saud al-Faisal to lead diplomatic relations with Shiite powerhouse Iran, Saudi Arabia&apos;s main regional rival. Al-Faisal last year invited Iranian Foreign Minister Mohammad Javad Zarif to visit Saudi Arabia, but later accused Iran of fomenting unrest throughout the Middle East. Zarif finally visited shortly after King Abdullah&apos;s death, and expressed hopes of greater cooperation with the Sunni-ruled kingdom. Salman also has overhauled policymaking by dissolving a dozen advisory bodies and replacing them with two new ones. One of those sidelined in that shake-up is Prince Bandar bin Sultan, who had led a National Security Council created by King Abdullah in 2005. Bandar, the former intelligence chief who was U.S. ambassador from 1983 to 2005, received no position in either of the two new panels: the Council of Political and Security Affairs, and the Council of Economic and Development Affairs. Mohammed bin Nayef leads the first committee, Abdulaziz bin Salman the second. Mustafa Alani, an expert on security and terrorism at the Geneva-based Gulf Research Center, said he expects the changes to promote better decision-making with an infusion of new political blood as Salman confronts security challenges in Yemen, Iraq, Syria and Iran. "Look at the map," Alani said. "You can see the situation surrounding the country. ... For this sort of environment, you need a new team." Another of Salman&apos;s early acts has been to open the state coffers — a reminder that even in an absolute monarchy, public opinion matters. He promised to pay more than 1 million civil servants and soldiers a bonus equivalent to two months&apos; salary, and offered similarly generous cash gifts to students, pensioners, sports clubs, literary clubs and others. It is too soon to say how the king will deal with those pressing for greater openness at home. He has opened the door for pardoning inmates convicted on what are known as "public rights" charges, which could include political activists. But he has left the decision on who gets pardons to the Interior Ministry, which Amnesty International says is primarily responsible for the kingdom&apos;s crackdown on dissenting voices. Amnesty and other human rights groups are closely following the king&apos;s handling of the case of blogger Raif Badawi, who was sentenced to 10 years in prison, a hefty fine and 1,000 lashes. He was flogged once in January but has not faced any lashes since Salman took charge. Souad al-Shammari, the co-founder of Badawi&apos;s liberal blog, was quietly released last week after three months in detention. Alani said King Salman would likely continue his predecessor&apos;s policy of gradual reform, which included curbing the power of the religious establishment and easing restrictions on women, who are still barred from driving cars. "The direction is to go for more reform, not less," he said. "The environment has changed. You have social media, and nobody can control any society now. And I think this is understood by the leadership."
<reponame>Kale-Ko/Better-Vanilla package com.kale_ko.better_vanilla.config; public class ConfigPair { public ConfigKey key; public Object value; public ConfigPair(ConfigKey key, Object value) { this.key = key; this.value = value; } }
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <ctype.h> #ifndef _POSIX_HOST_NAME_MAX #define _POSIX_HOST_NAME_MAX 255 #endif #ifdef HAVE_EVIL # include <Evil.h> #endif /* define macros and variable for using the eina logging system */ #define EFREET_MODULE_LOG_DOM /* no logging in this file */ #include "Efreet.h" #include "efreet_private.h" EAPI Efreet_Uri * efreet_uri_decode(const char *full_uri) { Efreet_Uri *uri; const char *p; char protocol[64], hostname[_POSIX_HOST_NAME_MAX], path[PATH_MAX]; int i = 0; EINA_SAFETY_ON_NULL_RETURN_VAL(full_uri, NULL); /* An uri should be in the form <protocol>://<hostname>/<path> */ if (!strstr(full_uri, "://")) return NULL; memset(protocol, 0, 64); memset(hostname, 0, _POSIX_HOST_NAME_MAX); memset(path, 0, PATH_MAX); /* parse protocol */ p = full_uri; for (i = 0; *p != ':' && *p != '\0' && i < 64; p++, i++) protocol[i] = *p; protocol[i] = '\0'; /* parse hostname */ p += 3; if (*p != '/') { for (i = 0; *p != '/' && *p != '\0' && i < _POSIX_HOST_NAME_MAX; p++, i++) hostname[i] = *p; hostname[i] = '\0'; } else hostname[0] = '\0'; /* parse path */ /* See http://www.faqs.org/rfcs/rfc1738.html for the escaped chars */ for (i = 0; *p != '\0' && i < PATH_MAX; i++, p++) { if (*p == '%') { path[i] = *(++p); path[i + 1] = *(++p); path[i] = (char)strtol(&(path[i]), NULL, 16); path[i + 1] = '\0'; } else path[i] = *p; } uri = NEW(Efreet_Uri, 1); if (!uri) return NULL; uri->protocol = eina_stringshare_add(protocol); uri->hostname = eina_stringshare_add(hostname); uri->path = eina_stringshare_add(path); return uri; } EAPI const char * efreet_uri_encode(Efreet_Uri *uri) { char dest[PATH_MAX * 3 + 4]; const char *p; int i; EINA_SAFETY_ON_NULL_RETURN_VAL(uri, NULL); EINA_SAFETY_ON_NULL_RETURN_VAL(uri->path, NULL); EINA_SAFETY_ON_NULL_RETURN_VAL(uri->protocol, NULL); memset(dest, 0, PATH_MAX * 3 + 4); snprintf(dest, strlen(uri->protocol) + 4, "%s://", uri->protocol); /* Most app doesn't handle the hostname in the uri so it's put to NULL */ for (i = strlen(uri->protocol) + 3, p = uri->path; *p != '\0'; p++, i++) { if (isalnum(*p) || strchr("/$-_.+!*'()", *p)) dest[i] = *p; else { snprintf(&(dest[i]), 4, "%%%02X", (unsigned char) *p); i += 2; } } return eina_stringshare_add(dest); } EAPI void efreet_uri_free(Efreet_Uri *uri) { if (!uri) return; IF_RELEASE(uri->protocol); IF_RELEASE(uri->path); IF_RELEASE(uri->hostname); FREE(uri); }
<filename>train.py # -*- coding: utf-8 -*- """ Bone Age Assessment BoNet train routine. """ # Standard lib imports import os import csv import glob import time import argparse import warnings import pandas as pd import os.path as osp # PyTorch imports import torch import torch.nn as nn import torch.optim as optim import horovod.torch as hvd from torchvision import transforms from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler # Other imports from tqdm import tqdm import pdb warnings.filterwarnings("ignore") parser = argparse.ArgumentParser() # Dataloading-related settings parser.add_argument('--heatmaps', default=False, action='store_true', help='Train model with gaussian heatmaps') parser.add_argument('--cropped', default=False, action='store_true', help='Train model with cropped images according to bbox') parser.add_argument('--dataset', default='RSNA', type=str,choices=['RSNA','RHPE'], help='Dataset to perform training') parser.add_argument('--data-train', default='data/train/', type=str, help='path to train data folder') parser.add_argument('--ann-path-train', default='train.csv', type=str, help='path to BAA annotations file') parser.add_argument('--rois-path-train', default='train.json', type=str, help='path to ROIs annotations in coco format') parser.add_argument('--data-val', default='data/val/', type=str, help='path to val data folder') parser.add_argument('--ann-path-val', default='val.csv', type=str, help='path to BAA annotations file') parser.add_argument('--rois-path-val', default='val.json', type=str, help='path to ROIs annotations in coco format') parser.add_argument('--save-folder', default='TRAIN/new_test/', help='location to save checkpoint models') parser.add_argument('--snapshot', default='boneage_bonet_weights.pth', help='path to weight snapshot file') parser.add_argument('--optim-snapshot', type=str, default='boneage_bonet_optim.pth', help='path to optimizer state snapshot') parser.add_argument('--eval-first', default=False, action='store_true', help='evaluate model weights before training') parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', help='number of data loading workers (default: 4)') # Training procedure settings parser.add_argument('--batch-size', default=1, type=int, help='Batch size for training') parser.add_argument('--epochs', type=int, default=20, help='upper epoch limit') parser.add_argument('--lr', '--learning-rate', default=1e-5, type=float, help='initial learning rate') parser.add_argument('--patience', default=2, type=int, help='patience epochs for LR decreasing') parser.add_argument('--start-epoch', type=int, default=1, help='epoch number to resume') parser.add_argument('--seed', type=int, default=1111, help='random seed') parser.add_argument('--log-interval', type=int, default=30, metavar='N', help='report interval') parser.add_argument('--gpu', type=str, default='2,3') args = parser.parse_args() args_dict = vars(args) print('Argument list to program') print('\n'.join(['--{0} {1}'.format(arg, args_dict[arg]) for arg in args_dict])) print('\n\n') torch.manual_seed(args.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu if not os.path.exists(args.save_folder): os.makedirs(args.save_folder) # Horovod settings hvd.init() torch.cuda.set_device(hvd.local_rank()) torch.cuda.manual_seed(hvd.size()) args.distributed = hvd.size() > 1 args.rank = hvd.rank() args.size = hvd.size() # CREATE THE NETWORK ARCHITECTURE AND LOAD THE BEST MODEL if args.heatmaps: from models.bonet_heatmap import BoNet else: from models.bonet import BoNet net = BoNet() if args.rank == 0: print('---> Number of params: {}'.format( sum([p.data.nelement() for p in net.parameters()]))) if osp.exists(args.snapshot): model_to_load=args.snapshot else: model_to_load=args.save_folder+'/'+args.snapshot if osp.exists(model_to_load) and args.rank == 0: print('Loading state dict from: {0}'.format(model_to_load)) snapshot_dict = torch.load(model_to_load, map_location=lambda storage, loc: storage) weights= net.state_dict() new_snapshot_dict=snapshot_dict.copy() for key in snapshot_dict: if key not in weights.keys(): new_key='inception_v3.'+key new_snapshot_dict[new_key]=snapshot_dict[key] new_snapshot_dict.pop(key) net.load_state_dict(new_snapshot_dict) net = net.to(device) # Criterion criterion = nn.L1Loss() # Optimizer optimizer = optim.Adam(net.parameters(), lr=args.lr * args.size) annealing = optim.lr_scheduler.ReduceLROnPlateau( optimizer, factor=0.8, patience=args.patience, cooldown=5, min_lr=0.00001, eps=0.00001, verbose=True) if osp.exists(args.optim_snapshot): optim_to_load=args.optim_snapshot else: optim_to_load=args.save_folder+'/'+args.optim_snapshot if osp.exists(optim_to_load): print('loading optim snapshot from {}'.format(optim_to_load)) optimizer.load_state_dict(torch.load(optim_to_load, map_location=lambda storage, loc: storage)) # Horovod hvd.broadcast_parameters(net.state_dict(), root_rank=0) optimizer = hvd.DistributedOptimizer( optimizer, named_parameters=net.named_parameters()) hvd.broadcast_optimizer_state(optimizer, root_rank=0) group = optimizer.param_groups[0] group['betas'] = (float(group['betas'][0]), float(group['betas'][1])) # Dataloaders train_transform = transforms.Compose([transforms.Resize((500, 500)), transforms.RandomAffine( 20, translate=(0.2, 0.2), scale=(1, 1.2)), transforms.RandomHorizontalFlip(), transforms.ToTensor()]) val_transform = transforms.Compose([transforms.Resize((500, 500)), transforms.ToTensor()]) if args.heatmaps: from data.data_loader import Boneage_HeatmapDataset as Dataset else: from data.data_loader import BoneageDataset as Dataset train_dataset = Dataset(args.data_train, args.ann_path_train,args.rois_path_train, img_transform=train_transform,crop=args.cropped,dataset=args.dataset) val_dataset = Dataset(args.data_val, args.ann_path_val,args.rois_path_val, img_transform=val_transform,crop=args.cropped,dataset=args.dataset) # Data samplers train_sampler = None val_sampler = None if args.distributed: train_sampler = DistributedSampler(train_dataset, num_replicas=args.size, rank=args.rank) val_sampler = DistributedSampler(val_dataset, num_replicas=args.size, rank=args.rank) train_loader = DataLoader(train_dataset, shuffle=(train_sampler is None), sampler=train_sampler, batch_size=args.batch_size, num_workers=args.workers) val_loader = DataLoader(val_dataset, shuffle=(val_sampler is None), sampler=val_sampler, batch_size=1, num_workers=args.workers) def main(): print('Train begins...') best_val_loss = None # Find best model in validation if osp.exists(osp.join(args.save_folder, 'train.csv')): with open(osp.join(args.save_folder, 'train.csv')) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') val_list = [] for row in csv_reader: val_list.append(float(row[2])) best_val_loss = min(val_list) if args.eval_first: val_loss = evaluate() try: out_file = open(os.path.join(args.save_folder, 'train.csv'), 'a+') for epoch in range(args.start_epoch, args.epochs + 1): if args.distributed: train_sampler.set_epoch(epoch) val_sampler.set_epoch(epoch) if args.rank == 0: epoch_start_time = time.time() train_loss = train(epoch) annealing.step(train_loss) val_loss = evaluate() if args.rank == 0: print('-' * 89) print('| end of epoch {:3d} | time: {:5.2f}s ' '| epoch loss {:.6f} |'.format( epoch, time.time() - epoch_start_time, train_loss)) print('-' * 89) out_file.write('{}, {}, {}\n'.format(epoch, train_loss, val_loss)) out_file.flush() if best_val_loss is None or val_loss > best_val_loss and args.rank == 0: best_val_loss = val_loss filename = osp.join(args.save_folder, 'boneage_bonet_weights.pth') torch.save(net.state_dict(), filename) out_file.close() except KeyboardInterrupt: print('-' * 89) print('Exiting from training early') def train(epoch): net.train() total_loss = AverageMeter() epoch_loss_stats = AverageMeter() time_stats = AverageMeter() loss = 0 optimizer.zero_grad() for (batch_idx, (imgs, bone_ages, genders, _)) in enumerate(train_loader): imgs = imgs.to(device) bone_ages = bone_ages.to(device) genders = genders.to(device) start_time = time.time() outputs = net(imgs, genders) loss = criterion(outputs.squeeze(), bone_ages) loss.backward() optimizer.step() loss = metric_average(loss.item(), 'loss') time_stats.update(time.time() - start_time, 1) total_loss.update(loss, 1) epoch_loss_stats.update(loss, 1) optimizer.zero_grad() if (batch_idx % args.log_interval == 0) and args.rank == 0: elapsed_time = time_stats.avg print(' [{:5d}] ({:5d}/{:5d}) | ms/batch {:.4f} |' ' loss {:.6f} | avg loss {:.6f} | lr {:.7f}'.format( epoch, batch_idx, len(train_loader), elapsed_time * 1000, total_loss.avg, epoch_loss_stats.avg, optimizer.param_groups[0]['lr'])) total_loss.reset() epoch_total_loss = epoch_loss_stats.avg args.resume_iter = 0 if args.rank == 0: filename = 'boneage_bonet_snapshot.pth' filename = osp.join(args.save_folder, filename) torch.save(net.state_dict(), filename) optim_filename = 'boneage_bonet_optim.pth' optim_filename = osp.join(args.save_folder, optim_filename) torch.save(optimizer.state_dict(), optim_filename) return epoch_total_loss def evaluate(): net.eval() epoch_total_loss = AverageMeter() for (batch_idx, (imgs, bone_ages, genders, _)) in enumerate(val_loader): imgs = imgs.to(device) bone_ages = bone_ages.to(device) genders = genders.to(device) with torch.no_grad(): outputs = net(imgs, genders) loss = criterion(outputs.squeeze(), bone_ages) loss = metric_average(loss.item(), 'loss') epoch_total_loss.update(loss, 1) epoch_total_loss = epoch_total_loss.avg if args.rank == 0: print('Val loss: {:.5f}'.format(epoch_total_loss)) return epoch_total_loss def metric_average(val, name): tensor = torch.tensor(val) avg_tensor = hvd.allreduce(tensor, name=name) return avg_tensor.item() class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count if __name__ == '__main__': main()
/** * Adds the supplied item to the tag field if it is not already present with * the given color, and if it is a valid choice within the tag set. This method * has a side-effect of rebuilding the popup menu to reflect the unchosen options. * * @param text the text to add to the tag field. * @param textColor the color of the text in the tag field, may be null. */ public void add(String text, Color textColor) { if (!myValues.containsKey(text) && myChoices.contains(text)) { myOrderedSelections.add(text); myValues.put(text, new JTag(text, this::remove, myTagColor, textColor)); add(myValues.get(text)); rebuildPopup(); revalidate(); repaint(); notifyChange(); } }
Faced with an orchestrated influx of millions of migrants from Africa and the Middle East, German officials have started commandeering private property to house the tsunami of new arrivals. Italian property owners have also been forced, literally kicking and screaming, to house migrants against their will. Plans to put resistors in jail are reportedly being considered. And in Sweden, where an extreme housing shortage in Stockholm has been made even more acute by the arrival of hundreds of thousands of migrants in recent years, authorities are using tax money to outbid Swedes in the intensifying competition for living space. Other fundamental freedoms are also being attacked under the guise of dealing with the self-inflicted “refugee crisis.” And it is going to get worse. Perhaps the most extreme attacks on private property have come from Germany. In the city of Hamburg (shown), the ruling coalition of extreme left-wing authorities first began seizing private property to house migrants with a controversial law passed in October of 2015. With some 400 migrants arriving in the city each day and migrant shelters already packed to capacity with new arrivals, officials claimed it was needed. At first, it was just commercial property that was supposed to be confiscated and turned into migrant housing, and only if the property in question was vacant. The confiscation was also only supposed to take place if the owner refused to hand over their properties voluntarily in exchange for compensation funds extracted from taxpayers. But as always occurs with government attacks on fundamental rights, it was a slippery slope — and it did not take long for phase two to begin. Now, authorities in Hamburg, Germany's second-largest city, are even targeting and commandeering residential properties as well. According to local and international news reports this month, authorities have now seized six apartments in the central Hamm district, against the owner’s will. After the properties were confiscated, officials began “renovating” them so they would be suitable for tenants of the government's choosing. The property owner will be billed for all the “renovation” expenses incurred by the government, a spokesman for the governing council behind the seizures was quoted as saying in the press. The costs are estimated to run into five figures. A “city-appointed trustee” will oversee the process and the housing units commandeered by authorities. But this is just the start, according to various news agencies. The local government, dominated by the far-left Socialist and Green parties, even established a “hotline” for residents of Hamburg to report any properties they may know of which may have been vacant for more than four months. After those four months are up, the residential properties will be subject to being commandeered by local government and being put under the supervision of the government's “trustee,” who can then pack the apartments with migrants or other tenants at taxpayer expense. Activists reportedly also set up a website dubbed “Vacancy Reporter” to help authorities locate vacant real estate for authorities to commandeer in Hamburg and beyond. Of course, multiple government policies have fueled the housing crisis. From failing to approve building permits to imposing draconian restrictions on rent, local authorities have helped ensure an acute shortage in supply. Combined with the surge in demand brought about by the national government's deeply unpopular policy of inviting millions of Third World migrants into the country at taxpayer expense, the housing and rental-property markets have been radically distorted. And so, city officials have resorted to further attacks on private property rights to deal with the problems government helped create to begin with. Outside of Hamburg, municipalities have also been evicting tenants from their apartments to house migrants. The first reported case in Germany happened in September of 2015 in the town of Nieheim. It involved Bettina Halbey, a 51-year-old nurse. “I was completely taken aback,” she told Die Welt after receiving the eviction letter. “I find it impossible to describe how the city has treated me.” On social media, she described the move as “a kick in the teeth.” Later that month, Gabrielle Keller, in the German town of Eschbach, was ordered by authorities to vacate her government-owned apartment, again to make room for migrants. “The alternative would have been to set up beds in the gym,” argued the mayor. An even more draconian scheme to trample private property rights to house migrants was also floated in the German capital of Berlin. Under that proposal, police would have been authorized to invade private property without a warrant to determine whether the residence would be suitable for migrant housing, according to media reports. However, even amid the escalating “refugee” crisis brought on by “former” East German Communist Party propagandist Angela Merkel and her “open door” policy, that was considered an unconstitutional bridge too far. More than a few critics suggested Hamburg's attacks on property rights may also be unconstitutional, but no official determination has yet been made. Still, critics expressed outrage. “Hamburg’s situation clearly illustrates the downside to uncontrolled mass migration,” argued Matt O'Brien with the Washington, D.C.-based Federation for American Immigration Reform, which opposes mass migration. “Western civilization operates on the notion that the first duty of a government is to protect the life, liberty and property of its own citizens. All other obligations are subsidiary. Hamburg decided to protect foreigners at the expense of German citizens and, in so doing, failed to fulfill the first duty of government. Let’s hope that if the U.S. government ever begins expropriating private land in response to a migrant crisis, it’s to build a border wall, not to house massive numbers of immigrants that the people of the United States never wanted here.” Local political figures in Hamburg have also spoken out, comparing the attacks on private property to tyranny and shameful communist horrors in Germany's past. “The proposed confiscation of private land and buildings is a massive attack on the property rights of the citizens of Hamburg,” André Trepoll with the Christian Democratic Union (CDU) party was quoted as saying in media reports, saying the “law of intimidation” was a “political dam-break with far-reaching implications.” “It amounts to an expropriation by the state.... The ends do not justify any and all means.” The leader of the Free Democrats Party in Hamburg, meanwhile, called it an “unacceptable crossing of red lines” and noted that, ironically, such “coercive measures” would “only fuel resentment against refugees.” Germany is hardly the only formerly sovereign European nation in which citizens and their fundamental rights — including their private-property rights — are being trampled by authorities to accommodate the avalanche of Third World migrants. In Italy, for example, an elderly hotel operator was terrorized by armed agents of the state for refusing to have his property packed full of migrants. A horrifying video of the episode went viral across the Internet. When Luigi Fogli, 80 at the time, refused to house “refugees” for 7 euros in tax money for each — all of them apparently African men without families present, video shows — authorities simply forced him to do it, literally. Late last year, the Italian Interior Ministry even floated a scheme, dubbed the “Viminale Plan," that would have put resistors behind bars for refusing to allow their properties to be commandeered for housing migrants. Under the plan, widely reported in Italian media, thousands of armed enforcement agents from the police and the military would be deployed to oversee enforcement. The Justice Ministry was reportedly prepared to provide trials and detention to those who resisted the plan. And almost incredibly, the commandeering of private property was set to take place without compensation, as the government does not have the funds to pay. As The New American has documented extensively in a series of articles, private property rights are not the only fundamental human rights being targeted in Europe under the guise of dealing with the so-called refugee crisis. Indeed, across Europe and the rest of the Western world, the globalist-engineered migrant crisis is leading to attacks on a wide array of fundamental liberties including self-government, privacy, free speech, freedom of the press, and more. In Germany, authorities have been raiding apartments and arresting those who criticize foreigners, Islam, or the mass-migration agenda too vociferously. The Islamist terror attacks that have resulted from the crisis and will continue to worsen, meanwhile, are being cited by regional authorities at the European Union and national powers as a pretext to justify the ongoing expansion of the police state at the national, regional, and international level. More than a few political leaders have suggested the establishment's agenda behind the migrant tsunami is the destruction of national cohesion, Christianity, and the nation-state on the road to regional and global governance. And senior establishment bigwigs such as former Goldman Sachs boss and UN migration czar Peter Sutherland have all but confirmed it. Indeed, the United Nations is funding TV ads urging German women to wear Muslim head scarves. The attacks on private property rights must be resisted by all clear-thinking people. America's Founding Fathers warned about just how serious infringements on private property were. John Adams, America's first vice president and second president, was perhaps the most firm and eloquent. “The moment the idea is admitted into society, that property is not as sacred as the laws of God, and that there is not a force of law and public justice to protect it, anarchy and tyranny commence,” Adams warned. “If ‘Thou shalt not covet,’ and ‘Thou shalt not steal,’ were not commandments of Heaven, they must be made inviolable precepts in every society, before it can be civilized or made free.” Across the Western world, including in the United States, that idea was admitted long ago. And under the guise of housing migrants, the idea is rapidly being expanded all over the West. Amid the globalist-orchestrated refugee crisis, in which globalist Western governments destroyed Middle Eastern and African nations before inviting the victims to Europe and the United States at taxpayer expense, the very foundations of Western civilization and Christendom are being eroded. And that was probably the agenda all along. Instead of bombing foreign countries to rubble and then welcoming the Third World into the West, real solutions to the problems must begin by holding accountable the establishment figures behind the tragedies. Trampling the fundamental rights of Germans, Americans, and Italians is probably the worst possible way of dealing with the crisis. Instead of attacking innocent citizens, everyone in Brussels and Washington, D.C., who engineered the illegal wars on Libya and other nations based on illegitimate United Nations resolutions should face legal accountability — up to and including criminal prosecution if crimes were committed, as it seems they were. Property owners in the West and around the world should be left in peace. Photo: Hamburg, Germany Alex Newman, a foreign correspondent for The New American, is normally based in Europe. Follow him on Twitter @ALEXNEWMAN_JOU or on Facebook. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. Related articles: Refugee Crisis: Using Chaos to Build Power Refugee Crisis Has Europe on the Brink Swedes and Germans Told to Integrate Into Their “New Country” Swedish Police: Government Covering Up Huge Migrant Crime Spree Globalists Who Created Refugee Crisis Now Exploiting It UN “Together” Propaganda Bid Seeks to Flood West With Migrants German Newspaper: Officials Are Covering Up Crimes by Migrants Hungarian PM: Mass Migration a Plot to Destroy Christian West Americans, Europeans Agree: Trump Is Right on Immigration Obama-UN Refugee Summit: Huge Push for More Refugees Insider: EU-U.S. Must Take More Refugees, Get Rid of Sovereignty U.S. Intel: Obama Coalition Supported Islamic State in Syria
Martin Dermott Background Martin Dermott was born in Wigan, Lancashire, England. Playing career Martin Dermott played hooker in Wigan's 15-8 victory over Oldham in the 1986 Lancashire County Cup Final during the 1986–87 season at Knowsley Road, St. Helens, on Sunday 19 October 1986, played hooker in the 22-17 victory over Salford in the 1988 Lancashire County Cup Final during the 1988–89 season at Knowsley Road, St. Helens on Sunday 23 October 1988, and played hooker in the 5-4 victory over St. Helens in the 1992 Lancashire County Cup Final during the 1992–93 season at Knowsley Road, St. Helens on Sunday 18 October 1992. Martin Dermott played hooker in Wigan's 18-4 victory over Warrington in the 1986–87 John Player Special Trophy Final during the 1986–87 season at Burnden Park, Bolton on Saturday 10 January 1987, played hooker in the 12-6 victory over Widnes in the 1988–89 John Player Special Trophy Final during the 1988–89 season at Burnden Park, Bolton on Saturday 7 January 1989, played hooker in the 24-12 victory over Halifax in the 1989–90 Regal Trophy Final during the 1989–90 season at Headingley Rugby Stadium, Leeds on Saturday 13 January 1990, played hooker in the 15-8 victory over Bradford Northern in the 1992–93 Regal Trophy Final during the 1992–93 season at Elland Road, Leeds on Saturday 23 January 1993, and played hooker in the 2-33 defeat by Castleford in the 1993–94 Regal Trophy Final during the 1993–94 season at Elland Road, Leeds on Saturday 22 January 1994. During the 1991–92 Rugby Football League season, Dermott played for defending champions Wigan as a hooker in their 1991 World Club Challenge victory against the visiting Penrith Panthers. He was selected to go on the 1992 Great Britain Lions tour of Australia and New Zealand. During the 1992–93 Rugby Football League season Dermott played as a hooker for defending RFL champions Wigan in the 1992 World Club Challenge against the visiting Brisbane Broncos. After the 1993–94 Rugby Football League season Dermott travelled with defending champions Wigan to Brisbane, playing as a hooker in their 1994 World Club Challenge victory over Australian premiers, the Brisbane Broncos.
<gh_stars>0 #include "scene.h" #include "player.h" class Renderable { public: // Virtual destructor is needed for abstract interfaces virtual ~Renderable() = default; /// Render the object /// \param camera - Camera to use for rendering virtual void render(const Camera& camera) = 0; /// Update the object. Useful for specifing animation and behaviour. /// \param dTime - Time delta /// \param scene - Scene reference /// \return - Return true to keep object in scene virtual bool update(float dTime, Scene &scene) = 0; }; void Scene::update(float time) { if(intro){ if(pom <= 1){ pom += 0.01; } else{ pom = 0.f; position += 1; if(position == 6){ intro = false; } } if(position!=5) { camera->position = glm::lerp(CamPositions[position], CamPositions[position + 1], pom); } } camera->update(); // Use iterator to update all objects so we can remove while iterating auto i = std::begin(objects); playR = 2; while (i != std::end(objects)) { // Update and remove from list if needed auto obj = i->get(); auto player = dynamic_cast<Player*>(obj); if ( player ) { playR = 0; } if( player and player->closestRd->position.x == -300 and player->position.y >= 60.f and player->position.y <= 69.f and player->position.x >= -324 and player->position.x <= -276) playR = 1; if (!obj->update(*this, time)) i = objects.erase(i); // NOTE: no need to call destructors as we store shared pointers in the scene else ++i; } } void Scene::render() { // Simply render all objects for ( auto& obj : objects ) obj->render(*this); } std::vector<Object*> Scene::intersect(const glm::vec3 &position, const glm::vec3 &direction) { std::vector<Object*> intersected = {}; for(auto& object : objects) { // Collision with sphere of size object->scale.x auto oc = position - object->position; auto radius = object->scale.x; auto a = glm::dot(direction, direction); auto b = glm::dot(oc, direction); auto c = glm::dot(oc, oc) - radius * radius; auto dis = b * b - a * c; if (dis > 0) { auto e = sqrt(dis); auto t = (-b - e) / a; if ( t > 0 ) { intersected.push_back(object.get()); continue; } t = (-b + e) / a; if ( t > 0 ) { intersected.push_back(object.get()); continue; } } } return intersected; }
#include <bits/stdc++.h> using namespace std; vector <pair<int,int>> by_w[100100]; int dp[300100]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; by_w[w].emplace_back(u, v); } for (int w = 0; w < 100100; w++) { vector <pair<int,int>> upd; for (auto e : by_w[w]) { int u = e.first; int v = e.second; upd.emplace_back(v, dp[u] + 1); } for (auto up : upd) { dp[up.first] = max(dp[up.first], up.second); } } cout << *max_element(dp, dp + 300100); return 0; }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.data.processor.data.entity; import com.google.common.collect.ImmutableList; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.entity.ImmutablePassengerData; import org.spongepowered.api.data.manipulator.mutable.entity.PassengerData; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableListValue; import org.spongepowered.api.data.value.mutable.ListValue; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.world.World; import org.spongepowered.common.data.manipulator.mutable.entity.SpongePassengerData; import org.spongepowered.common.data.processor.common.AbstractEntitySingleDataProcessor; import org.spongepowered.common.data.value.immutable.ImmutableSpongeListValue; import org.spongepowered.common.data.value.mutable.SpongeListValue; import org.spongepowered.common.entity.EntityUtil; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; public class PassengerDataProcessor extends AbstractEntitySingleDataProcessor<net.minecraft.entity.Entity, List<UUID>, ListValue<UUID>, PassengerData, ImmutablePassengerData> { public PassengerDataProcessor() { super(net.minecraft.entity.Entity.class, Keys.PASSENGERS); } @Override protected boolean set(net.minecraft.entity.Entity entity, List<UUID> uuids) { final List<net.minecraft.entity.Entity> passengers = uuids.stream() .map((uuid -> ((World) entity.getEntityWorld()).getEntity(uuid))) .filter(Optional::isPresent) .map(Optional::get) .map(EntityUtil::toNative) .collect(Collectors.toList()); for (net.minecraft.entity.Entity passenger : passengers) { if (!entity.isPassenger(passenger)) { entity.getPassengers().add(passenger); } } return true; } @Override protected Optional<List<UUID>> getVal(net.minecraft.entity.Entity dataHolder) { if (dataHolder.getPassengers().isEmpty()) { return Optional.empty(); } final List<UUID> passengers = dataHolder.getPassengers() .stream() .map(EntityUtil::fromNative) .map(Entity::getUniqueId) .collect(Collectors.toList()); return Optional.of(passengers); } @Override protected ImmutableListValue<UUID> constructImmutableValue(List<UUID> value) { return new ImmutableSpongeListValue<>(Keys.PASSENGERS, ImmutableList.copyOf(value)); } @Override protected ListValue<UUID> constructValue(List<UUID> actualValue) { return new SpongeListValue<>(Keys.PASSENGERS, actualValue); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { if (this.supports(container)) { net.minecraft.entity.Entity entity = ((net.minecraft.entity.Entity) container); if (entity.getPassengers().isEmpty()) { final ImmutableList<UUID> passengers = entity.getPassengers() .stream() .map(EntityUtil::fromNative) .map(Entity::getUniqueId) .collect(ImmutableList.toImmutableList()); entity.removePassengers(); return DataTransactionResult.builder().result(DataTransactionResult.Type.SUCCESS).replace(constructImmutableValue(passengers)).build(); } return DataTransactionResult.successNoData(); } return DataTransactionResult.failNoData(); } @Override public Optional<PassengerData> fill(DataContainer container, PassengerData passengerData) { passengerData.set(Keys.PASSENGERS, container.getObjectList(Keys.PASSENGERS.getQuery(), UUID.class).get()); return Optional.of(passengerData); } @Override protected PassengerData createManipulator() { return new SpongePassengerData(); } }
<reponame>yanhuanwang/dfc<filename>datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/ScheduledTasks.java /* * ============LICENSE_START====================================================================== * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved. * =============================================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. 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. * ============LICENSE_END======================================================================== */ package org.onap.dcaegen2.collectors.datafile.tasks; import org.onap.dcaegen2.collectors.datafile.exceptions.DmaapEmptyResponseException; import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel; import org.onap.dcaegen2.collectors.datafile.model.FileData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; /** * @author <a href="mailto:<EMAIL>"><NAME></a> on 3/23/18 * @author <a href="mailto:<EMAIL>"><NAME></a> */ @Component public class ScheduledTasks { private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class); private final DmaapConsumerTask dmaapConsumerTask; private final XnfCollectorTask xnfCollectorTask; private final DmaapPublisherTask dmaapProducerTask; /** * Constructor for task registration in Datafile Workflow. * * @param dmaapConsumerTask - fist task * @param xnfCollectorTask - second task * @param dmaapPublisherTask - third task */ @Autowired public ScheduledTasks(DmaapConsumerTask dmaapConsumerTask, XnfCollectorTask xnfCollectorTask, DmaapPublisherTask dmaapPublisherTask) { this.dmaapConsumerTask = dmaapConsumerTask; this.xnfCollectorTask = xnfCollectorTask; this.dmaapProducerTask = dmaapPublisherTask; } /** * Main function for scheduling Datafile Workflow. */ public void scheduleMainDatafileEventTask() { logger.trace("Execution of tasks was registered"); //@formatter:off consumeFromDmaapMessage() .publishOn(Schedulers.parallel()) .cache() .doOnError(DmaapEmptyResponseException.class, error -> logger.info("Nothing to consume from DMaaP")) .flatMap(this::collectFilesFromXnf) .retry(3) .cache() .flatMap(this::publishToDmaapConfiguration) .retry(3) .subscribe(this::onSuccess, this::onError, this::onComplete); //@formatter:on } private void onComplete() { logger.info("Datafile tasks have been completed"); } private void onSuccess(String responseCode) { logger.info("Datafile consumed tasks. HTTP Response code {}", responseCode); } private void onError(Throwable throwable) { if (!(throwable instanceof DmaapEmptyResponseException)) { logger.error("Chain of tasks have been aborted due to errors in Datafile workflow", throwable); } } private Flux<FileData> consumeFromDmaapMessage() { dmaapConsumerTask.initConfigs(); return dmaapConsumerTask.execute(""); } private Flux<ConsumerDmaapModel> collectFilesFromXnf(FileData fileData) { return xnfCollectorTask.execute(fileData); } private Flux<String> publishToDmaapConfiguration(ConsumerDmaapModel monoModel) { return dmaapProducerTask.execute(monoModel); } }
<filename>main.py import PySimpleGUI as sg import pygame as pg from pygame import mixer import sys import os # Define the window's contents sg.theme('GreenTan') val=0 start = False pg.mixer.init() #pg.mixer.music.load('burnmarks.wav') global layout layout = [[sg.Text('How long would you like to study?', size=(34, 1), font=("Helvetica", 18), auto_size_text=True, justification='right')], [sg.Slider(resolution=5, range=(0, 120), border_width=2, default_value=val, size=(20,15), orientation='horizontal', font=('Helvetica', 12), tick_interval=30, enable_events=True, key='Slider'), sg.Text('0:00', size=(10,0), font=("Helvetica", 20), auto_size_text=True, justification='right', key='timer')], [sg.Button('Start', key='Start', enable_events=True), sg.Button('Reset',key='Reset', enable_events=True), sg.Button('Pause music', key='Pause')], [sg.Image(r'~/Documents/study_timer/study-timer/assets/study.png', tooltip='test')], ] # Create the window global window window = sg.Window('lofi study timer', layout) running = False time_format = "00:00" # Display and interact with the Window using an Event Loop while True: # This is the code that reads and updates your window event, values = window.read(timeout=1000) slider_val = values['Slider'] # Define the countdown timer components if event == "Start": minutes = slider_val sec = int(minutes * 60) minn, secc = divmod(sec, 60) time_format = "{:02d}:{:02d}".format(minn, secc) if event in (sg.Button, 'Reset'): running = False sec = int(minutes * 60) minn, secc = divmod(sec, 60) time_format = "{:02d}:{:02d}".format(minn, secc) window["timer"].update(time_format) window["Start"].update("Start") window["Reset"].update(disabled=True) window['Slider'].Update(disabled=False) if event == sg.WIN_CLOSED or event == "Cancel": break # ---- Countdown timer ---- if event in 'Slider': print(int(slider_val)) window.refresh() pass if time_format == "00:00": running = False if running is True: minutes = int(slider_val) minn, secc = divmod(sec, 60) time_format = "{:02d}:{:02d}".format(minn, secc) window["timer"].update(time_format) window["Reset"].update(disabled=False) sec -= 1 if event in (sg.Button, 'Start'): minutes = int(slider_val) if running: running = False minutes = int(slider_val) window["Start"].update("Start") else: running = True window['Start'].update("Pause") # Change the 'Start' button to say 'Pause' window['Slider'].Update(disabled=True) # Disable the slider after start has been pressed. window.refresh() window.close() # this is not an exit
<filename>src/main/java/bbejeck/model/StockTickerData.java<gh_stars>100-1000 package bbejeck.model; public class StockTickerData { private double price; private String symbol; public double getPrice() { return price; } public String getSymbol() { return symbol; } public StockTickerData(double price, String symbol) { this.price = price; this.symbol = symbol; } @Override public String toString() { return "StockTickerData{" + "price=" + price + ", symbol='" + symbol + '\'' + '}'; } }
import sys import click import dateparser import requests from bs4 import BeautifulSoup def error(message): click.secho(message, bold=True, fg="red") sys.exit(-1) def parse_comments(file, db): comments = [] next_line = "timestamp" comment = "" with open(file) as fp: for line in fp: if next_line == "timestamp": date = line.strip() next_line = "permalink" continue if next_line == "permalink": permalink = line.strip() next_line = "comment" continue if line.strip() == "-----": id = int(permalink.split('#')[-1]) post_url = permalink.split('#')[0] subsite = permalink.split('/')[2] comments.append( {'id': id, 'date': date, 'url': permalink, 'text': comment, 'subsite': subsite, 'post_url': post_url,}) comment = "" next_line = "timestamp" continue comment += line.strip() db["comments"].insert_all(comments, pk="id", replace=True) def scrape_posts(user_id, db): posts = [] page = 1 while True: print(f"Loading results page {page}") url = f"https://www.metafilter.com/activity/{user_id}/posts/{page}/" res = requests.get(url, allow_redirects=False) if res.status_code == 404: error(f"404 Error encountered trying to load {url}") break if res.status_code == 301: break soup = BeautifulSoup(res.content, 'html.parser') page += 1 for post in soup.find_all("h1", class_="posttitle"): title = post.text url = post.contents[0].attrs['href'] subsite = url.split("/")[2] id = int(url.split("/")[3]) post_body = post.find_next_sibling('div') text = post_body.prettify() text = "".join(text.split("<br/>")[:-1]).strip() spans = list(post_body.find('span')) date_string = spans[3].text + " " + spans[4].replace('on', '').strip() date = dateparser.parse(date_string) favourites = 0 if len(spans) > 5: favourites = int(spans[5].text.replace('(', '').replace(')', '').replace('comments', '').replace('comment', '').strip()) posts.append({'id': id, 'date': date, 'url': url, 'title': title, 'text': text, 'subsite': subsite, 'num_favourites': favourites, 'user_id': int(user_id)}) db["posts"].insert_all(posts, pk="id", replace=True)
How efficiently do corn and soybeanbased cropping systems use water? A systems modeling analysis Agricultural systems are being challenged to decrease water use and increase production while climate becomes more variable and the world's population grows. Low water use efficiency is traditionally characterized by high water use relative to low grain production and usually occurs under dry conditions. However, when a cropping system fails to take advantage of available water during wet conditions, this is also an inefficiency and is often detrimental to the environment. Here, we provide a systemslevel definition of water use efficiency (sWUE) that addresses both production and environmental quality goals through incorporating all major system water losses (evapotranspiration, drainage, and runoff). We extensively calibrated and tested the Agricultural Production Systems sIMulator (APSIM) using 6 years of continuous crop and soil measurements in corn and soybeanbased cropping systems in central Iowa, USA. We then used the model to determine water use, loss, and grain production in each system and calculated sWUE in years that experienced drought, flood, or historically average precipitation. Systems water use efficiency was found to be greatest during years with average precipitation. Simulation analysis using 28 years of historical precipitation data, plus the same dataset with ± 15% variation in daily precipitation, showed that in this region, 430 mm of seasonal (planting to harvesting) rainfall resulted in the optimum sWUE for corn, and 317 mm for soybean. Above these precipitation levels, the corn and soybean yields did not increase further, but the water loss from the system via runoff and drainage increased substantially, leading to a high likelihood of soil, nutrient, and pesticide movement from the field to waterways. As the Midwestern United States is predicted to experience more frequent drought and flood, inefficiency of cropping systems water use will also increase. This work provides a framework to concurrently evaluate production and environmental performance of cropping systems.
[prMac.com] Hagenberg, Austria - Ergonis Software today announced the release of Typinator 3.0, the latest version of its highly acclaimed tool for auto-typing text and auto-correcting typos system-wide across all Mac OS X applications. With the new version, Typinator is no longer a regular application visible in the dock and the application switcher, but rather a dockless background-only application that is acting unobtrusively in the background. A small icon in the menu bar gives quick access to Typinator's main window. A new search feature lets you instantly view only snippets that contain a specified search string. Particularly users with many snippets will love this feature. Typinator 3.0 also adds a number of further improvements. Visit Ergonis Software's website to learn more about all changes in the release and to download and try the new version. "When we initially designed Typinator, we decided to make it a regular application, not a System Preference Pane, since this gives a wider scope for a comfortable user interface, and it seems that our customers like the resulting flexibility. However, it turned out that many users do not want to see Typinator as a regular application visible in the dock and the application switcher," said Christoph Reichenberger, founder and CEO of Ergonis Software. "I am therefore more than happy to announce that Typinator 3.0 offers the best of both worlds. Typinator is now an invisible background application that is visible only in form of a menu status item. However, when you need to access Typinator's functionality, it instantly opens up a full-fledged application window with no limitations in size, functionality, and comfort". Typinator can be purchased securely on the Ergonis Software website. The upgrade to Typinator 3.0 is free for anyone who purchased Typinator in the last 2 years. For information about purchases, including enterprise licenses, volume discounts, and upgrade pricing offers, visit their website. Instead of purchasing Typinator by itself, customers can get the Macility Productivity Bundle that also contains two of the company's other productivity tools, PopChar X and KeyCue. The pricing of the Productivity Bundle represents a saving of more than 35% over the separate purchase of its components. More information about the Productivity Bundle can be found at the Ergonis Software web site. Typinator 3.0 requires Mac OS X version 10.4 or newer. It is fully compatible with Mac OS X 10.5 (Leopard). An Online press kit, including screenshots, is available on the Ergonis Software web site.
Rick Yune Early life Yune was born in Washington D.C. to mother Wonhui Park and father Taeho Yune, who were both Koreans. His younger brother is actor Karl Yune. Yune was educated at Our Lady of Good Counsel High School (Silver Spring, Maryland) and St. John's College High School. In 1994, he received his degree in finance from the University of Pennsylvania's Wharton School. Yune was one of the original hedge fund traders for SAC Capital but left to pursue entrepreneurial ventures. Yune practices many forms of martial arts. He changed the spelling of his last name from "Yun" to "Yune" for Screen Actors Guild (SAG) purposes. Career While studying at Wharton, Rick Yune worked as an intern on Wall Street trading stocks during the mid-1992. During that time, he was "discovered" by a modeling agent and soon became the first Asian-American featured in advertisements for Versace and Ralph Lauren's Polo. Yune made his film debut in 1999, playing Kazuo Miyamoto, a Japanese-American war hero accused of killing a respected fisherman (played by Daniel von Bargen) in the close-knit community, in director Scott Hicks' film adaptation of David Guterson's post-World War II novel, Snow Falling on Cedars. Yune co-starred as Johnny Tran, the ruthless leader of a Vietnamese gang and the rival of Vin Diesel's character, in the 2001 film The Fast and the Furious. In 2002 Yune portrayed James Bond villain Zao, opposite Pierce Brosnan and Halle Berry, in the James Bond Die Another Day. That year Yune was voted one of People magazine's "Sexiest Men Alive". Yune appeared in the 2004 video "Call U Sexy" by the band VS, as well as in Someone (1997) by SWV, featuring Sean "Puffy" Combs. Yune appeared in two 2005 episodes of ABC's spy series Alias, playing a modern-day samurai Kazu Tamazaki who is hunted down by Jennifer Garner as Sydney. He also appeared as a guest in an episode of ABC's legal dramedy series Boston Legal and the CBS crime drama CSI: Crime Scene Investigation. In 2006 he provided his voice for the video game Scarface: The World Is Yours which was based the 1983 motion picture Scarface. He produced, and starred as a Bangkok assassin in, the action/adventure movie The Fifth Commandment, directed by Jesse V. Johnson and also stars Keith David and Bokeem Woodbine. Yune starred with Russell Crowe and Lucy Liu in the 2012 martial arts film, The Man with the Iron Fists. In 2013 Yune played villain Kang Yeonsak, in the action thriller Olympus Has Fallen, opposite Gerard Butler. In 2014, Yune took on the role of Kaidu, a Mongol Khan, in the historical drama series Marco Polo. Yune reprised his role in the second season, which was released in 2016. Other work Yune is a Board member of the Center for Global Dialogue and Cooperation and an Ambassador for the Princess Charlene Foundation of Monaco.
<reponame>e-NABLE-Volunteer-Community/configurator-export import { Field } from '@nestjs/graphql'; import { ArgsType } from '@nestjs/graphql'; import { MeasurementSetDescriptionWhereInput } from './measurement-set-description-where.input'; @ArgsType() export class DeleteManyMeasurementSetDescriptionArgs { @Field(() => MeasurementSetDescriptionWhereInput, {nullable:true}) where?: MeasurementSetDescriptionWhereInput; }
<filename>source/game/blocks.h<gh_stars>0 #ifndef BLOCKS_H #define BLOCKS_H #include "..\engine\atlas.h" typedef enum{ BLOCK } BlockShape; typedef enum{ BLOCK_AIR, BLOCK_GRASS, BLOCK_SPRUCE_GRASS, BLOCK_DESERT_GRASS, BLOCK_CHERRY_GRASS, BLOCK_DIRT, BLOCK_STONE, BLOCK_COBBLE, BLOCK_SAND, BLOCK_COAL_ORE, BLOCK_COPPER_ORE, BLOCK_GOLD_ORE, BLOCK_AMETHYST_ORE, BLOCK_TITANIUM_ORE, BLOCK_OAK_LOG, BLOCK_OAK_LEAVES, BLOCK_OAK_PLANKS, BLOCK_GRAVEL, BLOCK_CLAY, BLOCK_GLASS, BLOCK_WOOL_WHITE, BLOCK_WOOL_BLACK, BLOCK_WOOL_RED, BLOCK_WOOL_GREEN, BLOCK_WOOL_BLUE, BLOCK_WOOL_ORANGE, BLOCK_WOOL_YELLOW, BLOCK_WOOL_PURPLE, BLOCK_WOOL_PINK, BLOCK_GLASS_WHITE, BLOCK_GLASS_BLACK, BLOCK_GLASS_RED, BLOCK_GLASS_GREEN, BLOCK_GLASS_BLUE, BLOCK_GLASS_ORANGE, BLOCK_GLASS_YELLOW, BLOCK_GLASS_PURPLE, BLOCK_GLASS_PINK, BLOCK_BLACKSTONE, BLOCK_BLACKCOBBLE, BLOCK_BLACKSTONE_COAL_ORE, BLOCK_BLACKSTONE_COPPER_ORE, BLOCK_BLACKSTONE_GOLD_ORE, BLOCK_BLACKSTONE_AMETHYST_ORE, BLOCK_BLACKSTONE_TITANIUM_ORE, BLOCK_BEDROCK, } BlockID; typedef struct{ BlockShape shape; bool isTransparent; BlockTex topTex; BlockTex bottomTex; BlockTex sideTex; } Block; //TOP, BOTTOM, SIDE //Only pass one and rest will be copied static const Block blockDict[]= { {BLOCK,false,NULLBLOCK}, {BLOCK,false,TEX_GRASS_TOP,TEX_DIRT,TEX_GRASS_SIDE}, {BLOCK,false,TEX_SPRUCE_GRASS_TOP,TEX_DIRT,TEX_SPRUCE_GRASS_SIDE}, {BLOCK,false,TEX_DESERT_GRASS_TOP,TEX_DIRT,TEX_DESERT_GRASS_SIDE}, {BLOCK,false,TEX_CHERRY_GRASS_TOP,TEX_DIRT,TEX_CHERRY_GRASS_SIDE}, {BLOCK,false,TEX_DIRT}, {BLOCK,false,TEX_STONE}, {BLOCK,false,TEX_COBBLE}, {BLOCK,false,TEX_SAND}, {BLOCK,false,TEX_COAL_ORE}, {BLOCK,false,TEX_COPPER_ORE}, {BLOCK,false,TEX_GOLD_ORE}, {BLOCK,false,TEX_AMETHYST_ORE}, {BLOCK,false,TEX_TITANIUM_ORE}, {BLOCK,false,TEX_OAK_LOG_TOP,TEX_OAK_LOG_TOP,TEX_OAK_LOG_SIDE}, {BLOCK,true,TEX_OAK_LEAVES}, {BLOCK,false,TEX_OAK_PLANKS}, {BLOCK,false,TEX_GRAVEL}, {BLOCK,false,TEX_CLAY}, {BLOCK,true,TEX_GLASS}, {BLOCK,true,TEX_WOOL_WHITE}, {BLOCK,true,TEX_WOOL_BLACK}, {BLOCK,true,TEX_WOOL_RED}, {BLOCK,true,TEX_WOOL_GREEN}, {BLOCK,true,TEX_WOOL_BLUE}, {BLOCK,true,TEX_WOOL_ORANGE}, {BLOCK,true,TEX_WOOL_YELLOW}, {BLOCK,true,TEX_WOOL_PURPLE}, {BLOCK,true,TEX_WOOL_PINK}, {BLOCK,true,TEX_GLASS_WHITE}, {BLOCK,true,TEX_GLASS_BLACK}, {BLOCK,true,TEX_GLASS_RED}, {BLOCK,true,TEX_GLASS_GREEN}, {BLOCK,true,TEX_GLASS_BLUE}, {BLOCK,true,TEX_GLASS_ORANGE}, {BLOCK,true,TEX_GLASS_YELLOW}, {BLOCK,true,TEX_GLASS_PURPLE}, {BLOCK,true,TEX_GLASS_PINK}, {BLOCK,false,TEX_BLACKSTONE}, {BLOCK,false,TEX_BLACKCOBBLE}, {BLOCK,false,TEX_BLACK_COAL_ORE}, {BLOCK,false,TEX_BLACK_COPPER_ORE}, {BLOCK,false,TEX_BLACK_GOLD_ORE}, {BLOCK,false,TEX_BLACK_AMETHYST_ORE}, {BLOCK,false,TEX_BLACK_TITANIUM_ORE}, {BLOCK,false,TEX_BEDROCK} }; #define BLOCK_COUNT (sizeof(blockDict)/sizeof(blockDict[0])) #endif
Erythroleukemia of childhood and infancy: a report of two cases. Two rare de novo cases are presented of pediatric erythroleukemia (EL), AML-M6 in a four-month-old (patient A) and four-year-old (patient B) African-Americans who presented to the Medical College of Georgia from 1989 to 1995. The clinical, morphologic, immunophenotypic and cytogenetic features of both patients are reviewed. The purpose of this study is to correlate the bone marrow morphology with the immunophenotypes and the karyotypes of the neoplastic cells. The patients were both female, presented with flu-like symptoms, and were noted to have hepatosplenomegaly on physical examination. The peripheral blood examination was significant for anemia (Hb 54 (A), 84(B)g/L), and thrombocytopenia (86 (A), 70(B) x 10/L). The bone marrow contained 75 percent (A) and 76.8 percent (B) erythroblasts and showed myelodysplastic changes in the erythroid cell line. Cytochemical analysis was performed, and greater than 10 erythroblasts per 100 cells were periodic acid-Schiff positive. Immunophenotypes of the pretreatment bone marrow showed glycophorin-A, CD71, and CD11b positivity. The karyotypes of both patients contained complex (> 3 per clone) cytogenetic abnormalities. Our data suggest that the initial presentation and course of disease are different in adults and children. However, once the adult form reaches the acute leukemia stage, the laboratory findings are similar to those at initial presentation in pediatric EL.
Measurement to Error Stability: a Notion of Partial Detectability for Nonlinear Systems In previous work the notion of input to state stability (ISS) has been generalized to systems with outputs, yielding a number of useful concepts. When considering a system whose output is to be kept small (i.e. an error output), the notion of input to output stability (IOS) arises. Alternatively, when considering a system whose output is meant to provide information about the state (i.e. a measurement output), one arrives at the detectability notion of output to state stability (OSS). Combining these concepts, one may consider a system with two outputs, an error and a measurement. This leads naturally to a notion of partial detectability we call measurement to error stability (MES). This property characterizes systems in which the error signal is detectable through the measurement signal. This paper provides a partial Lyapunov characterization of the MES property. A closely related property of stability in three measures (SIT) is introduced, which characterizes systems for which the error decays whenever it dominates the measurement. The SIT property is shown to imply MES, and the two are shown to be equivalent under an additional boundedness assumption. A nonsmooth Lyapunov characterization of the SIT property is provided, which yields the partial characterization of MES. The analysis is carried out on systems described by differential inclusions -- implicitly incorporating a disturbance input with compact value-set. Introduction The notion of input to state stability (ISS), introduced in, provides a theoretical framework in which to formulate questions of robustness with respect to inputs (seen as disturbances) acting on a system. An ISS system is, roughly, one which has a "finite nonlinear gain" with respect to inputs and whose transient behavior can be bounded in terms of the size of the initial state and inputs; the precise definition is in terms of K-function gains. The theory of ISS systems now forms an integral part of several texts ( ) as well as expository and research articles (see e.g. ). In light of the duality between input/state and state/output behaviour which is common in control theory, it is natural to ask whether an ISS-like notion of output to state stability can be formulated. This concept, called OSS, is the subject of. The definition given is precisely the same as that of ISS with outputs in the place of inputs. In the case of linear systems this property is equivalent to detectability. (When applied to nonlinear systems, OSS is more properly described as zero-detectability). The paper contains a discussion of various definitions of detectability for nonlinear systems which have appeared in the literature. Several of these definitions are given in terms of the existence of a Lyapunov or "storage" function for the system. The main result of is the fact that the OSS property is equivalent to the existence of an appropriate Lyapunov function. These papers also contain a discussion of a generalized notion in which both inputs and outputs are considered (input-output to state stability, or IOSS). This property is addressed more completely in where a Lyapunov characterization is provided and the construction of nonlinear observers is discussed. This work addresses a generalization of the OSS property to a notion of "partial detectability". When discussing systems with outputs, the output signal typically plays one of two roles. A common situation is when the outputs are considered as measurements. Here, one supposes that knowledge of the whole state is not available, but rather that only partial knowledge of the state can be used. (Most commonly the output map is a projection, which corresponds simply to the ability to measure some, but not all, of the components of the state. More generally, one may only have access to some function of the state variables -e.g. the sum of two components -and so we allow for more general output mappings in the theory). This is the role of the output in OSS, and in the theory of detectability and observers in general. A second role for outputs occurs when the goal of the control design is not to regulate the behaviour of the entire state, but rather only to regulate the output signal. The theory of output regulation addresses precisely this situation (see e.g. ). In the case of systems with no inputs, the problem of stability of a subset of the state variables (i.e. stability of an output signal which is a projection) has been addressed in the ordinary differential equations literature under the name "partial stability". Within the ISS framework, the notion of stability of the output signal has been described by input to output stability (IOS). Consider now the case in which both the above situations occur. That is, there are two output signals, one which is measured, and the other which must be regulated. A special case of this situation has been addressed in the output regulation theory, under the name "error feedback". This theory formulates the question of regulating an output of the system (the error) with knowledge of that output only. The more general case is when there are two distinct channels playing these two roles. In this paper we generalize the notion of OSS to this situation by introducing the concept of measurement to error stability (MES), which can be viewed as a notion of partial detectability through the measurement channel. In this paper we will present a partial Lyapunov characterization of the MES property. This will be accomplished by first comparing the MES property to a notion of output stability relative to a set. This notion, which will be called stability in three measures (SIT) (cf. ) will be characterized by the existence of a lower semicontinuous Lyapunov function. It will be shown that the SIT property implies MES, and that the converse holds under an additional boundedness assumption. All stability notions discussed in this paper are defined "robustly" with respect to disturbances. Disturbances are incorporated implicitly into the model by describing the dynamics of the system by a differential inclusion. Basic Definitions and Notations We consider the differential inclusion with two output maps and a map : R n → R ≥0. We take the state x ∈ R n. We assume that the set-valued map F from R n to subsets of R n is locally Lipschitz (precise definitions to follow) with nonempty compact values. In addition, we assume that the differential inclusion is forward complete. We assume that the output maps h : R n → R py and g : R n → R pw are locally Lipschitz. The map is assumed to be continuous and proper; it will be used as a measurement of the magnitude of the state vector. We will denote || := (). The use of || allows a framework which includes the Euclidean norm, distance to a compact set, and more general measures of the magnitude of the state. Remark 2.1 We use the setting of a differential inclusion as a generalization of the perturbed differential equation where f is locally Lipschitz and the inputs d(), thought of as disturbances, take values in some compact set D. The setup provided by includes this case by choosing The Euclidean norm in a space R k is denoted simply by ||. If z is a function defined on a real interval containing , z is the sup norm of the restriction of z to , that is z = ess sup {|z(t)| : t ∈ }. For each p ∈ R n and r ≥ 0 let B(p, r) := {x ∈ R n : |x − p| ≤ r}, the ball of radius r centered at p. Let B denote the unit ball B. To formulate the statement that a nonsmooth function decreases in an appropriate manner, we will make use of the notion of the viscosity subgradient (cf. ). Definition 2.2 A vector ∈ R n is a viscosity subgradient of the function V : R n → R at ∈ R n if there exists a function g : R n → R satisfying lim h→0 g(h) |h| = 0 and a neighbourhood O ⊂ R n of the origin so that The (possibly empty) set of viscosity subgradients of V at is called the viscosity subdifferential and is denoted ∂DV (). We remark that if V is differentiable at, then ∂DV () = {∇V ()}. A function : R ≥0 → R ≥0 is of class K (denoted ∈ K) if it is continuous, positive definite, and strictly increasing; and is of class K∞ if in addition it is unbounded. A function : R ≥0 R ≥0 → R ≥0 is of class KL if for each fixed t ≥ 0, (, t) is of class K and for each fixed s ≥ 0, (s, t) decreases to zero as t → ∞. We next cite two results on nonlinear gain functions. The first is a small-gain lemma which is a special case of the main result in. Lemma 2.3 Suppose given a KL function, a function R : R ≥0 R ≥0 → R ≥0, a K function for which (r) < r if r > 0. Then if a system as in and a time t1 ≥ 0 satisfy the following: ii: for each 0 ≤ t0 ≤ t < t1, the state satisfies the reachability condition then there exists a KL function which satisfies for each trajectory of the system and for all 0 ≤ t0 ≤ t < t1. ✷ The next proposition follows directly from the proof of Lemma 3.1 in. for each fixed r > 0, Tr : R>0 onto → R>0 is continuous and is strictly decreasing; for each fixed > 0, Tr() is strictly increasing as r increases and limr→∞ Tr() = ∞; such that (s, t) ≤ for all s ≤ r, all t ≥ Tr(). ✷ Differential Inclusions We review some standard concepts from set-valued analysis (See e.g. ). The following statements apply to a map F from R n to subsets of R n. Definition 2.5 Let 0 < T ≤ ∞. A function x : [0, T ) → R n is said to be a solution of the differential inclusion if it is absolutely continuous and satisfie for almost every t ∈ [0, T ). A function x : [0, T ) → R n is called a maximal solution of the differential inclusion if it does not have an extension which is a solution. That is, either T = ∞ or there does not exist a solution x : [0, T+) → R n with T+ > T so that Definition 2.6 The differential inclusion is said to be forward complete on R n if every maximal solution is defined for all t ≥ 0. For each C ⊆ R n we let S(C) denote the set of maximal solutions of satisfying x ∈ C equipped with the topology of uniform convergence on compact intervals. If C is a singleton {} we will use the shorthand S(). We set S := S(R n ), the set of all maximal solutions. Given a trajectory x() ∈ S() for some ∈ R n, we denote for all t ≥ 0. An immediate consequence of the definition of a locally Lipschitz set-valued map is the following. ✷ We will use the notation R ≤T (C) for the reachable set in time T starting in the set C for the differential inclusion. That is, for each T > 0 and C ⊆ R n, The next result follows immediately from Corollary 3.4 of and Theorem 3, §7, of. Lemma 2.9 Suppose the set-valued map F from R n to subsets of R n is locally Lipschitz with nonempty compact values, and the differential inclusion as in is forward complete. Then, for each T ≥ 0 and each compact set C ⊂ R n the set R ≤T (C) is bounded. ✷ The following generalization of Gronwall's Lemma will be needed. This is a special case of Lemma 8.3 in. Lemma 2.10 Suppose the set-valued map G defined on R n has closed nonempty values and is globally Lipschitz with constant L. Let T > 0 be given. Then for any solution x() o defined for t ∈ and any p ∈ R n, there is a solution zp() of defined on which has zp = p and satisfies ✷ We next make the straightforward observation that the result of the previous Lemma is valid for locally Lipschitz set-valued maps provided we restrict to compact sets. Lemma 2.11 Suppose given a system as in. Let a compact C ⊂ R n and T > 0 be given. Then there exists L > 0 such that for any solution x() of defined on which satisfies x ∈ C and any p ∈ C, there is a solution zp() of defined on which has zp = p and satisfies is globally Lipschitz, say with constant L. The result follows from Lemma 2.10 and the fact that F and F agree on the set R ≤T (C), which contains the trajectories of interest. Stability and Detectability Properties The following definitions are given for a forward complete system with two output channels as in. The outputs y and w are considered as error and measurement signals, respectively. Our primary motivation is the following notion. Definition 3.1 We say that the system is measurement to error stable (MES) if there exist ∈ KL and ∈ K so that for each x() ∈ S, and all t ≥ 0. In the investigation of the MES property, the following notion of relative stability of the error will be useful. This is a notion of output stability which is applicable to systems with a single output y. Definition 3.2 Given a closed subset D of the state space R n, we say that the system is relatively error stable (RES) with respect to D if there exists ∈ KL so that for any solution x() ∈ S, if there exists t1 > 0 so that x(t) / ∈ D for all t ∈ , then A special case of this property occurs for a system with two outputs when the set D is defined by an inequality involving the two output maps, as follows. We say that the system satisfies the stability in three measures (SIT) property (with gain ) if there exists ∈ KL so that for any solution x() ∈ S, if there exists t1 > 0 so that |y(t)| > (|w(t)|) for all t ∈ , then It is immediate that SIT is equivalent to relative error stability with respect to the set D : The following relative stability properties will also be considered. Definition 3.4 We say the system satisfies the relative measurement to error bounded property (RMEB) if there exist K functions 1, 1, and 2 so that for any solution Definition 3.5 We say the system satisfies the relative error bounded property (REB) if there exist K functions 2 and so that for any solution x() ∈ S, if there exists t1 > 0 so that |y(t)| > 2(|w(t)|) for all t ∈ , then We begin with the straightforward observation that the REB and RMEB properties are equivalent. Lemma 3. 6 The system satisfies the RMEB property if and only if it satisfies the REB property. Proof. One implication is immediate. In the next section we provide a Lyapunov characterization for the relative error stability property. Since error stability relative to a set D involves a condition only on R n \D, one would expect a necessary and sufficient Lyapunov condition to be the existence of a function which decays appropriately along trajectories in R n \D. This is the case. Unfortunately, the "natural" method of construction leads to a function which is only lower semicontinuous. Lyapunov Functions We give definitions of the appropriate Lyapunov functions. Definition 4.1 Given an open set E ⊆ R n, we say that a lower semicontinuous function V : R n → R ≥0 is a lower semicontinuous RES-Lyapunov function for system there exists 3 : R ≥0 → R ≥0 continuous positive definite so that for each ∈ E, We say that V is a lower semicontinuous exponential decay RES-Lyapunov function for system on E if in addition holds with 3(r) = r. We specialize the above definitions for the notion of stability in three measures as follows. We next remark that the decrease statements and can be written equivalently in an integral formulation, using the following standard result (a minor extension of Theorem 4.6.3 in, see e.g. for details). Proposition 4.3 Suppose given a forward complete syste where F is locally Lipschitz and takes nonempty compact values. Let a lower semicontinuous function V : R n → R ≥0 and a locally Lipschitz function w : R n → R be given. The following are equivalent: for any t ≥ 0. ✷ Making use of this result, the decrease statements and above can be written equivalently as (after possibly replacing 3 by a locally Lipschitz function dominated by the original 3) for all x() ∈ S which remain in the appropriate set on the interval . This alternative formulation will be used below. The Lyapunov characterizations are as follows. Theorem 1 Let a system of the form and a closed set D ⊂ R n be given. Let E = R n \D. The following are equivalent. 1. The system is relatively error stable with respect to D. The system admits a lower semicontinuous RES-Lyapunov function on E. 3. The system admits a lower semicontinuous exponential decay RES-Lyapunov function on E. The implication ⇒ is immediate. The others will be shown in Section 6. Corollary 4.4 Let a system of the form and a function ∈ K be given. The following are equivalent. 1. The system satisfies the SIT property with gain. The system admits a lower semicontinuous SIT-Lyapunov function with gain. 3. The system admits a lower semicontinuous exponential decay SIT-Lyapunov function with gain. Having given a characterization of the SIT property, we now indicate how this notion is related to measurement to error stability. The following will be shown. Lemma 5.1 If the system satisfies the MES property, then it satisfies the SIT property. Lemma 5.2 If the system satisfies the RMEB property and the SIT property, then it satisfies the MES property. In addition, we provide an example to show that the converse of Lemma 5.1 does not hold in general. The following partial characterization of MES is an immediate consequence of Corollary 4.4 and the two preceding lemmas. Proofs We first show that the MES property implies the SIT property. Proof. (Lemma 5.1) Assume that the system satisfies the MES property with gains and. Let be any K∞ function so that ( −1 (s)) < s for all s > 0. For each x() ∈ S, it follows that if t1 > 0 is such that then from the definition of MES, for any t ∈ . Lemma 5.1 follows from an application of Lemma 2.3 with this and t1, and with ( −1 (r)) in the place of. The existence of the map R(, ) follows from Lemma 2.9. We next show that under the RMEB condition, SIT implies MES. We will show the following, which gives Lemma 5.2 immediately. As this holds for all > 0 sufficiently small, it follows by continuity that in the limit as → 0, To complement these results, we next exhibit an example showing the SIT property alone does not imply MES. However it is clear that the MES property does not hold, since the oscillations of the error y() grow without bound, and so cannot verify the MES bound for any gains and. Sufficiency We will show that the existence of a lower semicontinuous RES-Lyapunov function implies relative error stability. We will make use of the following comparison result. Define w() to be the maximal solution of the initial value proble Then w(t) is defined for all t ≥ 0 and v(t) ≤ w(t) ∀t ∈ [0, t). Proof. (We follow the proof of Theorem III.4.1 in ). Let v(), w() be as above for given () and t. It is immediate that w(t) ∈ for all t for which w(t) is defined, hence w() is defined for all t ≥ 0. For each integer n ≥ 1, let wn() be the maximal solution o Then for each n, wn(t) ∈ for all t for which wn(t) is defined, hence each wn() is defined for all t ≥ 0. We will show that for all n ≥ 1. Indeed, suppose not. Then there exists n ≥ 1 and ∈ [0, t) so that v( ) > wn( ). As T was arbitrary, we conclude that v(t) ≤ w(t) for all t ∈ [0, t). The following is an immediate consequence of Lemma 6.1 and (, Lemma 4.4). Lemma 6.2 Suppose given a locally Lipschitz positive definite function : R ≥0 → R ≥0. Then there exists ∈ KL with the following property: For any 0 < t ≤ ∞ and for any lower semicontinuous Proof. Lemma 6.1 tells us that v(t) ≤ w(t) for all t ∈ [0, t), where w is the maximal solution of the initial value problem (t) = −(w(t)), Lemma 4.4 of provides the existence of a ∈ KL so that Finally, we give the proof of ⇒ for Theorem 1 (sufficiency). Proof. Let a system of the form and a closed set D ⊂ R n be given. Let E = R n \D. Suppose there exists a lower semicontinuous RES-Lyapunov function V for the system which satisfies and (and hence ) on E with gains 1, 2 ∈ K∞ and 3 continuous positive definite. We will verify that the system satisfies the relative error stability property with respect to D. Necessity For a system which satisfies the relative error stability property with respect to a set D, we define, for each ∈ E := R n \D and each trajectory x() ∈ S(), the first hitting time of x() into D as follows. Passing to a subsequence if necessary, we assume k → 0. Thus, there exists K > 0 such that k ≤ 0 + 1 for all k ≥ K. Since x k () converges uniformly to x() on the finite interval , it follows from continuity of x() and each x k () that Since D is closed and x k ( k ) ∈ D for each k, we have x(0) ∈ D. Hence (x()) ≤ 0. Note that in general the function is not upper semicontinuous, as indicated in Figure 2. We now present the proof of ⇒ for Theorem 1 (necessity). Proof. Suppose the system satisfies the relative error stability property with respect to a set D. Let E := R n \D. We will construct an exponential decay lower semicontinuous RES-Lyapunov function for on E. Lemma 6.5 The function V is lower semicontinuous on R n. As previously mentioned, the MES property (or more precisely IMES -partial detectability under explicit inputs) is a natural combination of the notions of IOS and IOSS. As such, one would hope that a Lyapunov characterization of the IMES property would include as special cases the existing characterizations for IOS and IOSS (derived in and, respectively). The work presented here is a first step toward such a single unifying result. Several extensions to this result will be needed to complete this program. Firstly, an explicit input can be included by modelling the system as a forced differential inclusion. Secondly, a complete Lyapunov characterization is needed, with no recourse to an additional boundedness assumption. Finally, one would hope to prove that the stability property implies the existence of a smooth Lyapunov function, rather than the discontinuous case described here. When and if these problems are addressed, there will be a single characterization which would encompass the Lyapunov results on ISS, IOS and IOSS.
// Check to see if all of the packets have been received in each file public static boolean filesDone(ArrayList<Byte> fileIDs, HashMap<Byte, UDPfile> fileMap) { for (int i = 0; i < fileIDs.size(); i++) { if(!(fileMap.get(fileIDs.get(i)).isComplete())) { return false; } } return (fileIDs.size() == 3); }
56 Clean Technology in the Food Manufacturing Industry The food industry appears to have minimal concerns with clean technology. After all, the raw materials are natural, the processing is mild, and the by-products are biodegradable and nontoxic. However, the delivery of beneficial and attractive products to consumers frequently requires separation, purification, and restructuring of agricultural materials, and each step yields unwanted by-products, which at present are disposed of as cheaply as possible. In future, the industry will need to consider all of its operations more critically. For example, Large-scale processing can produce by-products that threaten the local environment by overloading in the oxygen demand. P h ysical processes are a compromise between energy efficiency and unacceptable damage to product quality. P ackaging is an integral part of the product because of the need for safety and quality maintenance during distribution. These materials are less
package com.jayfella.properties.component; import com.jayfella.properties.SimpleStringCellRenderer; import com.simsilica.lemur.ListBox; import com.simsilica.lemur.Panel; import com.simsilica.lemur.RollupPanel; import com.simsilica.lemur.core.VersionedReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; public class EnumComponent extends JmeComponent { private RollupPanel content; private ListBox<Enum<?>> enumListBox; private VersionedReference<Set<Integer>> ref; public EnumComponent() { this(null, null, null); } public EnumComponent(Object parent, Field field) { super(parent, field); create(); } public EnumComponent(Object parent, Method getter, Method setter) { super(parent, getter, setter); create(); } private void create() { this.enumListBox = new ListBox<>(); this.enumListBox.setCellRenderer(new SimpleStringCellRenderer<>()); this.ref = this.enumListBox.getSelectionModel().createReference(); this.content = new RollupPanel("", this.enumListBox, null); this.content.setOpen(false); } public void setEnumValues(Class<? extends Enum<?>> enumData) { Enum<?>[] var2 = enumData.getEnumConstants(); int index = var2.length; int i; for(i = 0; i < index; ++i) { Enum<?> val = var2[i]; this.enumListBox.getModel().add(val); } if (this.getReflectedItem() != null) { Enum<?> enumVal = (Enum<?>)this.getReflectedItem().getValue(); index = -1; for(i = 0; i < this.enumListBox.getModel().size(); ++i) { if (this.enumListBox.getModel().get(i) == enumVal) { index = i; break; } } if (index > -1) { this.enumListBox.getSelectionModel().setSelection(index); } else { // this should never happen, I guess.. Presumptions and all that. } } } public void setPropertyName(String name) { super.setPropertyName(name); this.content.setTitle("Enum: " + name); } public void setValue(Object value) { super.setValue(value); Enum<?> enumValue = (Enum<?>)value; int index = -1; for(int i = 0; i < this.enumListBox.getModel().size(); ++i) { Enum<?> val = this.enumListBox.getModel().get(i); if (enumValue == val) { index = i; break; } } if (index > -1) { this.enumListBox.getSelectionModel().setSelection(index); } } public Panel getPanel() { return this.content; } public void update(float tpf) { if (this.ref.update()) { Set<Integer> indices = this.ref.get(); if (!indices.isEmpty()) { Integer index = indices.iterator().next(); if (index != null && this.getReflectedItem() != null) { Enum<?> newValue = this.enumListBox.getModel().get(index); this.setValue(newValue); } } } if (this.getReflectedItem() != null) { if (this.isFocused(this.enumListBox)) { return; } Enum<?> newValue = (Enum<?>)this.getReflectedItem().getValue(); this.setValue(newValue); } } }
def fibonacci_optimal_memoization(n: int) -> int: if n < 0: raise ValueError("n must be >= 0") if n in fibo_dict: return fibo_dict[n] else: fibo_dict[n] = fibonacci_optimal_memoization(n - 1) + fibonacci_optimal_memoization(n - 2) return fibo_dict[n]
<filename>videos/90c31368-aa93-4dd2-a55d-2969e605b589/1080p_084.ts version https://git-lfs.github.com/spec/v1 oid sha256:efb4c3b28f4774a9a2c9630a44ba20df20389f02440cacf04ee52f2a347aa637 size 2254684
import { setMapColors } from "./mapColors.actions" import { MapColors } from "../../../../codeCharta.model" export function splitMapColorsAction(payload: MapColors) { return setMapColors(payload) }
The present invention relates to an electron beam exposure technique. More specifically, the present invention relates to high-precision electron beam exposure equipment and exposure method. In electron beam writing equipment, optical adjustment of an electron beam is one of the most important techniques. In a prior art, axis adjustment of an electron beam lens is performed by measuring the change of position of an electron beam with changing the focus length of the lens (for example, see Micro Electronic Engineering, vol. 21, 1993, pp. 145-148). The method, however, is used only in a point beam and a micro area beam substantially handled as a point beam in which a crossover is larger than an image. In addition, a focal point is changed by varying excitation of one lens. There are electron beam exposure equipment having a method for projecting a large field electron beam onto a sample and a method for exposing a large field by plural electron beams at the same time. In these methods, there is no guide for the above axis adjustment. In a method for using plural electron beams which can control on/off independently in the large field projection methods, correction using only a specific electron beam is proposed (for example, see Japanese Patent Application Laid-Open No. 10-106931). In such proposition, a method about optical adjustment of a lens is not described. Further, in a prior art, a method for adjusting an optics system of large field projection is proposed. To permit wide deflection, plural detectors and lens interference are finely adjusted to ultimately change the lens characteristic, thereby realizing low aberration. It is very complex (for example, see Japanese Patent Application Laid-Open No. 10-303095). As a simplified method, a method for adjusting the position of a crossover (pupil image) is proposed. This method is limited (for example, see Japanese Patent Application Laid-Open No. 10-302696). In large field projection aiming at higher throughput, an electron optics system using a doublet lens is required. The doublet lens substantially equalizes the sum of the focus lengths of two electromagnetic lenses and the distance between the two electromagnetic lenses to form one image plane by the two electromagnetic lenses. In the above prior art, a simplified optical adjustment method for using the lenses of this method with high precision is not considered.
/// Create a new Join element. pub fn from_nick_and_nodes<N: Into<String>>(nick: N, nodes: &[&str]) -> Join { let subscribes = nodes .into_iter() .cloned() .map(|n| Subscribe::new(n)) .collect(); Join { id: None, nick: nick.into(), subscribes, } }
Tiny birds, even tinier backpacks, and a heck of a lot of air miles. Those are the essential ingredients behind a Canada-U.S. study that appears to have convincingly solved a 50-year-old mystery while at the same time discovering one of the most impressive animal migrations on Earth. The bird is the blackpoll warbler, a small but tuneful denizen of the boreal forest that can be found in summer months from Alaska to Newfoundland. The mystery has to do with how they get to South America every fall, where they overwinter. Story continues below advertisement Now, with the help of some clever technology, scientists have the answer: The intrepid warblers take the direct route, flying across the Atlantic for up to 2,800 kilometres at a stretch. "The idea that a 15-gram bird can fly non-stop over water for days is astounding," said Bridget Stutchbury, a professor of biology at York University in Toronto, who was not involved in the study. "It's the first time anyone's directly proven that that's what these birds are doing." Researchers say the discovery is important not just because it is an ornithological record setter, but because it may indicate that habitat loss along their unconventional route or in their wintering grounds is the reason blackpolls are losing six per cent of their population each year. It has long been suspected that the blackpoll – which get its name from the prominent black cap on adult males of the species – is doing something unusual compared to songbirds of similar size. Like other warblers, blackpolls can be seen and heard moving northward every May, passing through the Eastern United States and Canada on their way to their northern breeding grounds. But come fall, it is a different story. Rather than retracing their spring route, the birds head east to New England and the Maritimes, where they devour enough insects to double their body weight in some cases. At that point, "they disappear," said Ryan Norris, an ecologist at the University of Guelph and the Canadian leader of the study, published on Tuesday in the journal Biology Letters. "There's all sorts of sightings of them, and then there are no sightings, or very few." Eventually, the blackpolls reappear in Colombia, Venezuela and Brazil. Since the 1960s, researchers have speculated that blackpolls bulk up and make a straight shot across the Atlantic rather than take the longer, overland route. The idea was bolstered by stories of the birds showing up in Bermuda after storms or dropping in on ships at sea. But skepticism remained. No such migration over the open ocean had ever been demonstrated in birds so small. The first chance to do so came in 2013, with the arrival of geolocator devices that are small and light enough for warblers to carry in specially designed backpacks. Bulkier versions have been used in earlier studies to trace the migration routes of larger species. Story continues below advertisement Story continues below advertisement The devices can record only the passage of time and varying light levels from day to night. Yet, just like an 18th-century navigator equipped only with a ship's clock and a sextant, the geolocaters use this information to compute latitude and longitude as an individual bird migrates. "As soon as these little backpacks became light enough, we were out putting them on blackpolls," Dr. Norris said. The catch is that the geolocaters are too small to transmit their data. Researchers have to recapture the blackpolls after they return the next season to find out where they have been, a task Dr. Norris compares to searching for a handful of flying needles in a forest-sized haystack. "The odds are somewhat daunting," said Chris Rimmer, a conservation biologist and director of the Vermont Center for Ecostudies, which, unbeknownst to the Canadian team, was undertaking a similar experiment. The two groups learned of each other and pooled their results. Of the nearly 40 birds they had collectively outfitted with geolocators in 2013, five were retrieved the next year. It was only a handful, but enough to show clearly that blackpolls use an ocean route in the fall. One bird that Dr. Norris' group released in Nova Scotia flew directly to Haiti, nearly 3,000 kilometres to the south. Other species are known to fly even farther, but as a ratio of body weight to distance, the blackpoll beats them all. Despite the risk of being so far from land, Dr. Norris said, the strategy has benefits, because it allows the warblers to avoid predators and it gets them to their wintering grounds faster. Story continues below advertisement At some point, Dr. Norris speculates, there were probably two populations of blackpolls, but, over time, the ones that chose the Atlantic flight had a higher rate of survival than their land-leaning cousins. Dr. Stutchbury said she hoped the study would raise the profile of blackpoll warblers and lead to more concerted conservation efforts. "These kind of discoveries give us extra respect for some of these little-known birds, and with that respect comes a responsibility."
<gh_stars>0 /** * This file is part of oSCJ. * * oSCJ is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * oSCJ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with oSCJ. If not, see <http://www.gnu.org/licenses/>. * * * Copyright 2009, 2010 * @authors <NAME>, <NAME> */ package javax.realtime; /** * This error is thrown on an attempt to refer to an object in * an inaccessible {@link MemoryArea}. For example this * will be thrown if logic in a {@link NoHeapRealtimeThread} * attempts to refer to an object in the traditional Java heap. * * @spec RTSJ 1.0.1 - from OVM/RTSJ */ public class MemoryAccessError extends Error { /** * A constructor for <tt>MemoryAccessError</tt>. */ public MemoryAccessError() {} /** * A descriptive constructor for <tt>MemoryAccessError</tt>. * * @param description Description of the error. */ public MemoryAccessError(String description) { super(description); } }
Crews will also replace wood planks and make any other necessary repairs to the bridge. The Milroy Bridge is closed every other year for a safety inspection. The intersection is known for its backups during peak traffic times. The bridge was built in 1931 and connects North Levee Road East in the city of Fife with state Route 167 (River Road) in unincorporated Pierce County near Puyallup.
The Health and Care (Staffing) (Scotland) Bill is expected to pass the stage one debate in the Scottish Parliament. Proposed new legislation to enshrine safe levels of health and care staff in law is expected to pass its first hurdle at Holyrood later. The Health and Care (Staffing) (Scotland) Bill was put forward following concerns about staffing levels and workforce planning in the NHS and by care providers. If passed, the bill would put enhanced existing workforce planning tools on a statutory footing, aiming to ensure safe and appropriate staffing levels. In a recent report, Holyrood’s Health and Sport Committee, which has been scrutinising the proposed legislation, backed the general principles of the Bill. However, MSPs on the committee have asked for more detail on how staff numbers and care quality will be assessed, monitored and reported. They also raised concerns about a danger of resources being skewed towards the hospital sector in order to meet the initial requirements set out in the legislation. They committee called on the government to “reflect on” staff such as paramedics, radiographers, physiotherapists and others, collectively known as Allied Health Professionals, being excluded from the legislation. Speaking ahead of the debate, Health Secretary Jeane Freeman said: “I am pleased that the Health and Sport Committee support the general principles of this important legislation, which will create a system to help ensure there is appropriate staffing in place to meet patient need. “Our NHS has now seen seven consecutive years of annual growth in overall workforce numbers, but in order to meet increasing demand on our services, it’s crucial that we understand the workload required to meet service users’ needs. The debate comes two days after annual NHS workforce figures were published, showing a marginal 0.2% increase between the September 30 census point this year on overall staff. Numbers of medical and dental consultants rose and vacancies for these posts fell, but doctors’ organisation BMA Scotland beliee certain types of empty roles being omitted from the calculations mean the real vacancy rate is almost double at around 13.9% – equivalent to a hospital worth of consultants. Nursing and midwifery staff numbers increased but vacancies for these positions also rose.
def ps_params_generator(centers, deltaPix = 1): fixed_ps = [] kwargs_ps_init = [] kwargs_ps_sigma = [] kwargs_lower_ps = [] kwargs_upper_ps = [] for i in range(len(centers)): center_x = centers[i][0] * deltaPix center_y = centers[i][1] * deltaPix fixed_ps.append({}) kwargs_ps_init.append({'ra_image': [center_x], 'dec_image': [center_y]}) kwargs_ps_sigma.append({'ra_image': [0.5*deltaPix], 'dec_image': [0.5*deltaPix]}) kwargs_lower_ps.append({'ra_image': [center_x-2*deltaPix], 'dec_image': [center_y-2*deltaPix] } ) kwargs_upper_ps.append({'ra_image': [center_x+2*deltaPix], 'dec_image': [center_y+2*deltaPix] } ) ps_params = [kwargs_ps_init, kwargs_ps_sigma, fixed_ps, kwargs_lower_ps, kwargs_upper_ps] return ps_params
Study of the impact of climate change on precipitation in Paris area using method based on iterative multiscale dynamic time warping (IMS-DTW) Studying the impact of climate change on precipitation is constrained by finding a way to evaluate the evolution of precipitation variability over time. Classical approaches (feature-based) have shown their limitations for this issue due to the intermittent and irregular nature of precipitation. In this study, we present a novel variant of the Dynamic time warping method quantifying the dissimilarity between two rainfall time series based on shapes comparisons, for clustering annual time series recorded at daily scale. This shape based approach considers the whole information (variability, trends and intermittency). We further labeled each cluster using a feature-based approach. While testing the proposed approach on the time series of Paris Montsouris, we found that the precipitation variability increased over the years in Paris area.
/** * Method adding services metadata * @param monitorMetaDataBuffer - the metadata buffer */ private void fillServiceMetadata(final String serviceName, final int index) { final int servAreaOffset = noOfServicesOffset + BitUtil.SIZE_OF_INT; metaDataBuffer.putInt(noOfServicesOffset, metaDataBuffer.getInt(noOfServicesOffset) + 1); int serviceNameOffset = getServiceNameOffset(servAreaOffset); int serviceLocationOffset = serviceNameOffset + serviceName.length() + BitUtil.SIZE_OF_INT; metaDataBuffer.putStringUtf8(serviceNameOffset, serviceName, ByteOrder.nativeOrder()); initializeServiceRefMetadata(serviceLocationOffset, index * OFFSETS_PER_SERVICE); prevServiceOffset = serviceNameOffset; prevServiceName = serviceName; }
The natural history of incidentally detected small renal masses I read with interest the recent article by Volpe et al. on the natural history of 32 incidentally detected small renal masses. The authors stated that small renal masses grow at slow or undetectable rates and that a period of observation may be appropriate for some patients. I would like to point out, however, that the study was somewhat limited in that none of the tumors were analyzed on biopsy and only nine were resected. Tumors were presumed to be renal cell carcinomas (RCCs) on the basis of imaging studies, which are not infallible in distinguishing RCCs from benign tumors such as oncocytomas and angiomyolipomas. In fact, one of the nine resected tumors in the study was confirmed to be an oncocytoma. Volpe and colleagues concluded that tumor growth rate on its own probably was not sufficient for the accurate prediction of the behavior of every small renal mass. Furthermore, they speculated that studies (cytogenetic, immunohistochemical, and other) performed on needle biopsy samples, as well as the investigation of novel radiographic parameters, could help in the identification of patients who had renal lesions exhibiting favorable prognostic characteristics and a long natural history and who therefore could be followed conservatively in most cases. It is worth noting that pathologists, and especially cytopathologists, already use fine-needle aspiration and coreneedle biopsy to distinguish patients who can be followed conservatively from those who should undergo resection. As Volpe et al. point out, recent studies have found that as many as 38.5% of all masses measuring 2 cm are benign. Benign lesions such as angiomyolipomas can be identified on fine-needle aspiration or core-needle biopsy, as can RCC subtypes such as chromophobe RCC and low-grade papillary RCC, which are associated with a significantly lower risk of disease progression compared with conventional RCC. Conventional/clear cell tumors with high Fuhrman grade, in contrast, are associated with a relatively poor prognosis and probably should be resected if at all possible, regardless of their size. Some other minor issues also warrant mentioning. Volpe and colleagues state that the biologic behavior of predominantly cystic RCC is not well known, when it is in fact well documented that these tumors are relatively indolent. It is true that in the past, the term adenoma was used by pathologists to describe renal masses that measured 3 cm, were detected incidentally at autopsy, and were histologically similar to RCC but had lower associated metastasis rates. The current definition of adenoma according to the 1996 American Joint Committee on Cancer Consensus Conference, however, is very different, and based on this definition, adenomas specifically do not include radiographically identified masses. There remain specific settings in which growth rate may be useful in predicting outcome for patients with small, radiographically identified lesions. These settings include Fuhrman Grade 1 or 2 conven650
<reponame>ejfitzgerald/agents-aea # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """This module contains a class to manage transactions.""" import copy import datetime from collections import defaultdict, deque from typing import Deque, Dict, List, Tuple, cast from aea.decision_maker.default import OwnershipState from aea.helpers.dialogue.base import DialogueLabel from aea.helpers.search.models import Description from aea.helpers.transaction.base import RawMessage, Terms from aea.mail.base import Address from aea.protocols.signing.message import SigningMessage from aea.skills.base import Model from packages.fetchai.skills.tac_negotiation.dialogues import ( FipaDialogue, SigningDialogues, ) MessageId = int class Transactions(Model): """Class to handle pending transaction proposals/acceptances and locked transactions.""" def __init__(self, **kwargs) -> None: """Initialize the transactions.""" self._pending_transaction_timeout = kwargs.pop( "pending_transaction_timeout", 30 ) super().__init__(**kwargs) self._pending_proposals = defaultdict( lambda: {} ) # type: Dict[DialogueLabel, Dict[MessageId, SigningMessage]] self._pending_initial_acceptances = defaultdict( lambda: {} ) # type: Dict[DialogueLabel, Dict[MessageId, SigningMessage]] self._locked_txs = {} # type: Dict[str, SigningMessage] self._locked_txs_as_buyer = {} # type: Dict[str, SigningMessage] self._locked_txs_as_seller = {} # type: Dict[str, SigningMessage] self._last_update_for_transactions = ( deque() ) # type: Deque[Tuple[datetime.datetime, str]] self._nonce = 0 @property def pending_proposals( self, ) -> Dict[DialogueLabel, Dict[MessageId, SigningMessage]]: """Get the pending proposals.""" return self._pending_proposals @property def pending_initial_acceptances( self, ) -> Dict[DialogueLabel, Dict[MessageId, SigningMessage]]: """Get the pending initial acceptances.""" return self._pending_initial_acceptances def get_next_nonce(self) -> str: """Get the next nonce.""" self._nonce += 1 return str(self._nonce) def generate_signing_message( self, performative: SigningMessage.Performative, proposal_description: Description, dialogue_label: DialogueLabel, role: FipaDialogue.Role, agent_addr: Address, ) -> SigningMessage: """ Generate the transaction message from the description and the dialogue. :param proposal_description: the description of the proposal :param dialogue_label: the dialogue label :param role: the role of the agent (seller or buyer) :param agent_addr: the address of the agent :return: a transaction message """ is_seller = role == FipaDialogue.Role.SELLER goods_component = copy.copy(proposal_description.values) [ # pylint: disable=expression-not-assigned goods_component.pop(key) for key in ["fee", "price", "currency_id", "nonce", "ledger_id"] ] # switch signs based on whether seller or buyer role amount = ( proposal_description.values["price"] if is_seller else -proposal_description.values["price"] ) fee = proposal_description.values["fee"] if is_seller: for good_id in goods_component.keys(): goods_component[good_id] = goods_component[good_id] * (-1) amount_by_currency_id = {proposal_description.values["currency_id"]: amount} fee_by_currency_id = {proposal_description.values["currency_id"]: fee} nonce = proposal_description.values["nonce"] ledger_id = proposal_description.values["ledger_id"] terms = Terms( ledger_id=ledger_id, sender_address=agent_addr, counterparty_address=dialogue_label.dialogue_opponent_addr, amount_by_currency_id=amount_by_currency_id, is_sender_payable_tx_fee=not is_seller, quantities_by_good_id=goods_component, nonce=nonce, fee_by_currency_id=fee_by_currency_id, ) skill_callback_ids = (str(self.context.skill_id),) signing_dialogues = cast(SigningDialogues, self.context.signing_dialogues) skill_callback_info = {"dialogue_label": str(dialogue_label)} raw_message = RawMessage( ledger_id=ledger_id, body=terms.sender_hash.encode("utf-8") ) signing_msg = SigningMessage( performative=performative, dialogue_reference=signing_dialogues.new_self_initiated_dialogue_reference(), skill_callback_ids=skill_callback_ids, terms=terms, skill_callback_info=skill_callback_info, raw_message=raw_message, ) signing_msg.counterparty = "decision_maker" return signing_msg def update_confirmed_transactions(self) -> None: """ Update model wrt to confirmed transactions. :return: None """ confirmed_tx_ids = self.context.shared_state.pop( "confirmed_tx_ids", [] ) # type: List[str] for transaction_id in confirmed_tx_ids: # remove (safely) the associated pending proposal (if present) self._locked_txs.pop(transaction_id, None) self._locked_txs_as_buyer.pop(transaction_id, None) self._locked_txs_as_seller.pop(transaction_id, None) def cleanup_pending_transactions(self) -> None: """ Remove all the pending messages (i.e. either proposals or acceptances) that have been stored for an amount of time longer than the timeout. :return: None """ queue = self._last_update_for_transactions timeout = datetime.timedelta(0, self._pending_transaction_timeout) if len(queue) == 0: return next_date, next_item = queue[0] while datetime.datetime.now() - next_date > timeout: # remove the element from the queue queue.popleft() # extract dialogue label and message id transaction_id = next_item self.context.logger.debug( "removing transaction from pending list: {}".format(transaction_id) ) # remove (safely) the associated pending proposal (if present) self._locked_txs.pop(transaction_id, None) self._locked_txs_as_buyer.pop(transaction_id, None) self._locked_txs_as_seller.pop(transaction_id, None) # check the next transaction, if present if len(queue) == 0: break next_date, next_item = queue[0] def add_pending_proposal( self, dialogue_label: DialogueLabel, proposal_id: int, signing_msg: SigningMessage, ) -> None: """ Add a proposal (in the form of a transaction) to the pending list. :param dialogue_label: the dialogue label associated with the proposal :param proposal_id: the message id of the proposal :param signing_msg: the transaction message :raise AssertionError: if the pending proposal is already present. :return: None """ assert ( dialogue_label not in self._pending_proposals and proposal_id not in self._pending_proposals[dialogue_label] ) self._pending_proposals[dialogue_label][proposal_id] = signing_msg def pop_pending_proposal( self, dialogue_label: DialogueLabel, proposal_id: int ) -> SigningMessage: """ Remove a proposal (in the form of a transaction) from the pending list. :param dialogue_label: the dialogue label associated with the proposal :param proposal_id: the message id of the proposal :raise AssertionError: if the pending proposal is not present. :return: the transaction message """ assert ( dialogue_label in self._pending_proposals and proposal_id in self._pending_proposals[dialogue_label] ) signing_msg = self._pending_proposals[dialogue_label].pop(proposal_id) return signing_msg def add_pending_initial_acceptance( self, dialogue_label: DialogueLabel, proposal_id: int, signing_msg: SigningMessage, ) -> None: """ Add an acceptance (in the form of a transaction) to the pending list. :param dialogue_label: the dialogue label associated with the proposal :param proposal_id: the message id of the proposal :param signing_msg: the transaction message :raise AssertionError: if the pending acceptance is already present. :return: None """ assert ( dialogue_label not in self._pending_initial_acceptances and proposal_id not in self._pending_initial_acceptances[dialogue_label] ) self._pending_initial_acceptances[dialogue_label][proposal_id] = signing_msg def pop_pending_initial_acceptance( self, dialogue_label: DialogueLabel, proposal_id: int ) -> SigningMessage: """ Remove an acceptance (in the form of a transaction) from the pending list. :param dialogue_label: the dialogue label associated with the proposal :param proposal_id: the message id of the proposal :raise AssertionError: if the pending acceptance is not present. :return: the transaction message """ assert ( dialogue_label in self._pending_initial_acceptances and proposal_id in self._pending_initial_acceptances[dialogue_label] ) signing_msg = self._pending_initial_acceptances[dialogue_label].pop(proposal_id) return signing_msg def _register_transaction_with_time(self, transaction_id: str) -> None: """ Register a transaction with a creation datetime. :param transaction_id: the transaction id :return: None """ now = datetime.datetime.now() self._last_update_for_transactions.append((now, transaction_id)) def add_locked_tx( self, signing_msg: SigningMessage, role: FipaDialogue.Role ) -> None: """ Add a lock (in the form of a transaction). :param signing_msg: the transaction message :param role: the role of the agent (seller or buyer) :raise AssertionError: if the transaction is already present. :return: None """ as_seller = role == FipaDialogue.Role.SELLER transaction_id = signing_msg.terms.id assert transaction_id not in self._locked_txs self._register_transaction_with_time(transaction_id) self._locked_txs[transaction_id] = signing_msg if as_seller: self._locked_txs_as_seller[transaction_id] = signing_msg else: self._locked_txs_as_buyer[transaction_id] = signing_msg def pop_locked_tx(self, signing_msg: SigningMessage) -> SigningMessage: """ Remove a lock (in the form of a transaction). :param signing_msg: the transaction message :raise AssertionError: if the transaction with the given transaction id has not been found. :return: the transaction """ transaction_id = signing_msg.terms.id assert transaction_id in self._locked_txs signing_msg = self._locked_txs.pop(transaction_id) self._locked_txs_as_buyer.pop(transaction_id, None) self._locked_txs_as_seller.pop(transaction_id, None) return signing_msg def ownership_state_after_locks(self, is_seller: bool) -> OwnershipState: """ Apply all the locks to the current ownership state of the agent. This assumes, that all the locked transactions will be successful. :param is_seller: Boolean indicating the role of the agent. :return: the agent state with the locks applied to current state """ signing_msgs = ( list(self._locked_txs_as_seller.values()) if is_seller else list(self._locked_txs_as_buyer.values()) ) terms = [signing_msg.terms for signing_msg in signing_msgs] ownership_state = cast( OwnershipState, self.context.decision_maker_handler_context.ownership_state ) ownership_state_after_locks = ownership_state.apply_transactions(terms) return ownership_state_after_locks
As controversial San Francisco 49ers Quarterback Colin Kaepernick prepares to make his first start since his much-discussed kneeling during the National Anthem, reports are coming out the National Football League is experiencing a slide in television ratings. Some blame Kaepernick for tarnishing the NFL brand. On Facebook, perennial presidential candidate Mike Huckabee chastised the “the NFL Commissioner’s mealy-mouthed quasi-endorsement of players imposing their grievance politics onto the game” for ratings that are “dropping like Target’s stock price.” John Calvin concurred in the American Spectator: “May I be bold enough to suggest that the decline in ratings is primarily due to the NFL’s embrace of several of its players’ repeated blasphemy of our National Anthem prior to each football game? A situation…that the NFL could control if it really wanted to.” But are the critics of the NFL—and Kaepernick—right? The polling firm Rasmussen Reports recently found that “32 percent of Americans say they are less likely to watch an NFL game because of the growing number of Black Lives Matter protests by players on the field.” The same survey reported that 13 percent of respondents are more likely to watch an NFL game because of the protests, while the majority say it will have no effect. Fans are more willing to shell out the big bucks for the big games, whether Kaepernick is kneeling or not. But the NFL claims that other polling data shows the image of professional football players and the sport is up, despite the viewer decline. Critics scoff that those numbers lie, but seem surprisingly trusting of diminishing ratings polling. If anything, both sides seem to only trust the numbers that confirm their viewpoint. In fact, the NFL ratings slump predate Kaepernick’s high-profile protest. The decline has been occurring over the last several years, so the argument that the NFL was just doing fine until the quarterback kneeled during the National Anthem isn’t supported by the evidence. Has NFL Attendance Dropped? Polls and ratings aren’t the only methods to measure whether Colin Kaepernick is hurting the NFL’s image. ESPN’s data on NFL attendance show that from 2015 to 2016, attendance rose slightly from 68,273.84 fans per NFL game to 68,630.03. Last year, the percentage of tickets sold was 96.7 percent; this year, it is 96.8 percent. That’s right; fans are more willing to shell out the big bucks for the big games, whether Kaepernick is kneeling or not. And the 49ers now place 12th in attendance, the same as last year. Another way to gauge whether this alleged anger against Kaepernick is costing football is to look at college football, given that athletes at Michigan, Nebraska, and other schools have held protests during the National Anthem. Sure enough, college football is dominating the TV landscape, beating the competition in head-to-head match-ups. What Else Could Account For The Ratings Decline? Many excuses have been given for the slight drop in NFL viewership. Some suggest that it’s the heated Trump-Clinton race, which has everyone fixated on politics instead of sports. That might explain how the first presidential debate cut into Monday Night Football’s numbers, but not other games. Others argue it has to do with the baseball playoffs, but those occur every year. Furthermore, baseball was tied with football for fan support in 1985, but twice as many people like football than baseball today, according to Harris polling results. The Samford University Sports Business Report may have revealed the real reason why the NFL is losing TV viewers. People are watching the game in different ways, even live-streaming it. “The NFL has done this to itself because they created these multimedia packages and allowed its constituents to be able to access their content online with the NFL Mobile Network,” writes Ryan Hughes. The declines are actually in traditional television viewing, not in viewers, therefore. A recent visit to a Verizon shop resulted in a packed store, with vendors wearing football jerseys showing me how to watch NFL games on my cell phone. Currently, ratings agencies are trying to figure out how to incorporate such online viewers into determining who is watching what, according to Rebecca Fairley Raney of the website How Stuff Works. Until we know that, we won’t know if #boycottNFL is scoring or not. John A. Tures is a professor of political science at LaGrange College in LaGrange, Ga. He can be reached at jtures@lagrange.edu.
/* * @XMHF_LICENSE_HEADER_START@ * * eXtensible, Modular Hypervisor Framework (XMHF) * Copyright (c) 2009-2012 Carnegie Mellon University * Copyright (c) 2010-2012 VDG Inc. * All Rights Reserved. * * Developed by: XMHF Team * Carnegie Mellon University / CyLab * VDG Inc. * http://xmhf.org * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the names of Carnegie Mellon or VDG Inc, nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @XMHF_LICENSE_HEADER_END@ */ #include <stdint.h> #include <string.h> void *memmove(void *dst_void, const void *src_void, u32 length){ char *dst = dst_void; const char *src = src_void; if (src < dst && dst < src + length){ // Have to copy backwards src += length; dst += length; while (length--){ *--dst = *--src; } }else{ while (length--){ *dst++ = *src++; } } return dst_void; } u32 strnlen(const char * s, u32 count){ const char *sc; for (sc = s; count-- && *sc != '\0'; ++sc); return (u32)(sc - s); } void *memcpy(void * to, const void * from, u32 n) { size_t i; for(i=0; i<n; i++) { ((uint8_t*)to)[i] = ((const uint8_t*)from)[i]; } return to; } void *memset (void *str, int c, size_t len) { register u8 *st = str; while (len-- > 0) *st++ = (u8)c; return str; } #ifndef HAVE_MEMCMP int memcmp(const void *s1, const void *s2, size_t n) { if (n != 0) { const unsigned char *p1 = s1, *p2 = s2; do { if (*p1++ != *p2++) return (*--p1 - *--p2); } while (--n != 0); } return (0); } #endif /* HAVE_MEMCMP */
NANDROLONE DECANOATE VERSES ERYTHROPOIETIN FOR TREA TMENT OF ANEMIA CAUSED BY CHRONIC KIDNEY DISEASE INTRODUCTION Erythropoietin and other erythropoietin stimulating agents (ESAs) like Nandrolone Decanoate are the main stay for the treatment of anemia caused due to chronic kidney disease (CKD). The main limitation of EPO use in developing countries is cost, making it unavailable to most patients. Androgens which ar e relatively cheap were used in the treatment of anaemia in dialysis patients before the invention o f recombinant EPO. However, there are concerns about their efficacy and side effects. The aim of t his ABSTRACT Androgens which are comparatively cheap were used i n the treatment of anaemia (due to chronic kidney diseases) in dialysis patients before the developme nt of Erythropoietin (EPO). However, there aresome concerns related to their efficacy and side effects. S udy aims are to examine the efficacy and harms of Nandrolone Decanoate for the treatment of anaemia c aused by chronic kidney disease (CKD) compared to recombinant erythropoietin. A systematic analysis a nd review revealed no difference between Nandrolone Decanoate and recombinant erythropoietin for the tr eatment of anaemia caused by CKD in men over 50 years. Therefore, nandrolone Decanoate can be used for the treatment of anaemia caused by CKD in this category of patients, in developing countries. Howe ver, further studies are required to determine the longterm efficacy and safety of nandrolone Decanoate in men over 50 years of age, also its safety and effectiveness in females, and in males less than 50 years of age.
Liraglutide improves carotid intima-media thickness in patients with type 2 diabetes and non-alcoholic fatty liver disease: an 8-month prospective pilot study Objective: To explore the effects of the glucagon-like peptide-1 receptor analogue liraglutide on subclinical atherosclerosis in diabetic subjects with non-alcoholic fatty liver disease (NAFLD). Research design and methods: In this 8-month prospective study, 29 subjects with type 2 diabetes (T2DM) and NAFLD (16 men and 13 women, mean age: 61 ± 10 years) were matched for age and gender with 29 subjects with T2DM without NAFLD (16 men and 13 women, mean age: 61 ± 8 years). Liraglutide 0.6 mg/day for 2 weeks, followed by 1.2 mg/day, was given in addition to metformin. Main outcome measures: Anthropometric variables, glucometabolic parameters and carotid intima-media thickness (IMT) using B-mode real-time ultrasound were assessed at baseline and 4 and 8 months. Results: Glycated hemoglobin reduced significantly in both groups. No significant changes were found in body weight, waist circumference and lipids. Carotid IMT decreased significantly in the T2DM patients with NAFLD (from 0.96 ± 0.27 to 0.82 ± 0.17 to 0.85 ± 0.12 mm, p = 0.0325), but not in the T2DM patients without NAFLD (from 0.91 ± 0.23 to 0.88 ± 0.17 to 0.85 ± 0.15 mm, p = 0.4473). Conclusion: Eight months of liraglutide use in patients with T2DM and NAFLD significantly reduced carotid IMT, a surrogate marker of atherosclerosis, independently of glucometabolic changes.
Retrograde Coronary Chronic Total Occlusion Intervention Coronary chronic total occlusion (CTO) is a frequent finding in patients with coronary artery disease. It remains one of the most challenging subsets, accounting for 10-20% of all percutaneous coronary interventions (PCI). Although remarkable progress in PCI has been made, it is reasonable to state that successful recanalization of CTO represents the last frontier of PCI. PCI of CTOs has been limited historically by technical success rates of 50-70%. The introduction of enhanced guidewires, microcatheter, channel dilatator with increasing operator experience, and innovative techniques such as the retrograde approach have raised hopes for better outcomes. This article goes into depth into various strategies of retrograde approach in CTO. INTRODUCTION It has been demonstrated that successful recanalization of CTO improves angina status, increases exercise capacity, and reduces mortality and the need for subsequent coronary artery bypass surgery. Despite remarkable progress over the last decades, successful recanalization of CTOs represents the "final frontier" of PCI. PCI of this subset of lesions is still technically challenging although new devices and a wide range of guidewires have been developed. The technical success rate for CTO via the antegrade approach remains suboptimal, in the range of 65%-70% worldwide. However, retrograde approach via collateral channel (CC) overcomes the limitations of the conventional antegrade approach. When it becomes more widely adopted it is expected to be a breakthrough to potentially improve the success rate of complex CTO. Despite this, adoption of this technique is limited. Retrograde procedure is used in only 15% of CTO PCI as suggested by the EuroCTO registry. INDICATIONS FOR RETROGRADE APPROACH Retrograde access via donor collateral (bypass graft) was first performed in 1990. A higher success rate upto 95% could be achieved from the combination of antegrade and retrograde approach. Angiographic features of blunt occlusion with a large side branch, bridging collaterals, calcification, and long CTO are no longer considered negative predictors of success while using a retrograde approach. Possible indications of this new approach could be subsets of previous antegrade failures. It could be the primary procedure in many situations like ostial occlusions, long occlusions, heavy calcification, occlusions with ambiguous proximal cap, and occlusions with a diffusely diseased distal vessel. Retrograde penetration of the distal CTO cap may be easier because it is tapered and softer as compared to the proximal cap; also, it is not reliant upon precise visualization of CTO origin, and is exposed to higher pressure, where the proximal cap is blunt or less benign. ANGIOGRAPHIC/ASSESSMENT AND SELECTION COLLATERAL CHANNEL ANALYSIS The first key to success of the retrograde approach is to study the diagnostic images carefully and select a best CC. Optimal angiographic planning requires dual injections from both left and right coronary ostia with complete filling of the distal collateral bed from all feeding sources. Lower magnification and avoiding panning considerably helps in evaluating CCs. The distal vessel size, nature of the proximal and distal cap, side branches, tortuosity, and calcification are other critical items of information that are gained from the angiogram. The three types of CCs are bypass graft, epicardial channels, and septal channels. In severely degenerated saphenous vein graft cases, it is necessary to recanalize CTO of the native coronary artery to improve long-term outcome. Despite the poor suitability of graft for PCI, it can be used as a channel for wire passage. An arterial graft could also be used for the retrograde conduit. Septal CCs are the safest and are preferable whenever possible. Compared with the epicardial, the septal CC is a shorter route to the recipient vessel and is less tortuous. It can also be dilated using a small balloon (1.25-1.5 mm) with very low pressure (up to 2 atm) to navigate the catheter through it without major adverse clinical events. At present, the Corsair catheter (Asahi Intec, Japan) circumvents septal CCs dilatation with a small balloon. Excessive septal tortuosity is a severe limitation to wire advancement whereas size is less so. Straight faintly visible or even invisible septal Debabrata Dash CCs could be crossed by "surfing" with the wire. The angle of entry, angle of donor vessel and at the base of the heart, if acute, could be a significant limitation to both wire and microcatheter passage. These CCs are best evaluated in a combination of right anterior oblique (RAO) or anteroposterior cranial (AP) and RAO projections. As opposed to septal CCs, the main assessment criteria for epicardial CCs is a size and not the extent of tortuosity. Challenging anatomy, such as a corkscrew or highly tortuous configuration demonstrated by epicardial CCs, is not a contraindication, especially in the Corsair era. In general, larger epicardial CCs are safer and more likely to permit a balloon or microcatheter. There is some risk of perforation during wire manipulation which could be controlled by simple ballooning at the proximal site. Dilatation of this CC should not be done as it leads to vessel rupture and cardiac tamponade. However, the chance for tamponade is lower during wiring of the epicardial CC in a patient with bypass graft as there is no pericardial space. When this channel is the only donor artery to a viable CTO region, wire manipulation leads to distant ischemia. SYSTEM SETUP Two 6-8 F guiding catheters are usually engaged in the right and left coronary arteries via radial or femoral arteries. Use of bi-femoral or radial route is a matter of operator preference and experience with knowledge of risks/benefit of both. For retrograde limb, use of short (90cm) guiding catheters (especially when using epicardial CCs) allowing the externalization of the wire, is recommended. A regular 100 cm guide catheter can be manually shortened and connected to a 1F smaller introducer sheath. Removing 10 cm is usually sufficient. Because of reversibility, heparin is the anticoagulation of choice. An activated clotting time (ACT) of 300 to 350 seconds should be targeted. Bivaluridin or glycoprotein IIb/IIIa antagonists are not recommended because of concerns in case of perforation. COLLATERAL CROSSING AND GUIDEWIRE HAN-DLING Successful collateral crossing depends on CC selection, wire tip curve, and wire handling. The best CC would be clearly visible, less tortuous collaterals by super-selective injection, exemplified by Dr. Werner's CC grade 1 or 2 ( Fig. 1A and B) (CCs are graded as follows: CC0, no continuous connection, CC1, continuous thread-like connection; and CC2, continuous, small sidebranch-like connection). Acute angulation, branching, cork-screw morphology, and calcification are major hurdles for wire crossing. It would be wise to avoid severe corkscrew-like collaterals, which are characterized by an amplitude to diameter ratio of less than 2. Suitable for CC crossing, the best spring coil wires are Sion and Sion blue (Asahi Intec, Japan); polymer jacket wires are Fielder FC, XT, XTR (Asahi Intec, Japan), Pilot 50, and Whisper (Abbott vascular, USA). Fielder FC would be of choice in CC 1 or 2. Fielder XT, XTR or Sion (Asahi Intec, Japan) wire would be recommended in less visible, minor tortuosity on CC 0 or 1. Sion blue (Asahi Intec, Japan) can help to track very tiny or invisible CCs, or CCs with threedimensional tortuosity. An extremely small tip (< 1mm) curve (45 0 ) is recommended for CC navigation. After a wire access to the selected CC, the microcatheter is placed at the start of the CC. Although choice of microcatheter depends on operator preference, currently Corsair is the microcatheter of choice. After the position has been secured, the workhorse wire is exchanged with an appropriate polymer jacket (tapered or nontapered) or spring coil wire to cross the CC. The Corsair is an over the wire (OTW) hybrid catheter composed of 8 thin wires wound with 2 large ones. It has a soft tapered tip with tungsten braiding and a hydrophilic shaft which serves as a CC dilator while providing exceptional CC tracking and crossing as well as retrograde wire control. Gentle rotation of this catheter is required to advance or pull it by either clockwise or counterclockwise rotation. It is performed by 5-10 alternating clockwise and counterclockwise rotations while providing forward tension. Rotation should be limited to 10 times in one direction. In case of failure to cross or blockage of the Corsair, it should be exchanged for a low-profile microcatheter (Finecross, Terumo, Japan) or an OTW balloon (Ryujin 1.25 mm x 10 mm Terumo, Japan; Lacross 1.30 mm x 10 mm, Goodman, Japan or Maverick 1.50 mm x 15 mm, Boston Scientific, USA) with a longer shaft (>145 cm) by using extension guidewire or the counter flush method. From the very beginning, the Finecross should be the microcatheter of choice for a very tortuous epicardial channel. The author prefers the newly developed Finecross GT (Asahi Intec, Japan) for locating channels with small bends. Once the wire is positioned at the tip of the corsair catheter, it is gently advanced with rotation along the path of least resistance (surfing) in case of septal CCs and should halt once a series of ventricular beats has developed or migration to the side branch is noted. The wire is quickly redirected to find an alternative CCs in case of resistance. Forceful advancement of the wire could lead to CC rupture, vessel perforation, and septal hematoma which might be fatal. In doubtful wire position there is selective injection (advancement of microcatheter with pulling the back of the wire) of the contrast (as little as 2 ml); if a wash out of the contrast is revealed, the CC is connected to the other ventricle. Wire advancement in to the left or right ventricle is benign as long as the microcatheter is not advanced. When the contrast stays in the channel, it infers focal perforation. Selective injection is the last resort after several surfing attempts have failed, as it increases the risk of septal rupture and hematoma. During septal surfing, the wrong path is also assessed by wire buckling. On occasion, there are sudden rapid and large deviations in wire-tip movement indicating entry into a cardiac chamber. Septal hematoma, manifesting as severe chest pain, may lead to a fatal event if not treated adequately, such as by coil embolization of septal CC or creation of a fistula connecting to the ventricle. In case of epicardial CC, surfing is not advisable. Divergence from the observed path may lead to perforation which is more problematic than septal rupture. CONNECTING THE ANTEGRADE AND RETRO-GRADE CHANNEL Retrograde penetration is attempted with a guidewire such as a Fielder XT (Asahi Intec, Japan) from the distal cap of a CTO lesion with the support of a microcatheter. If it fails, it should be exchanged for an Ultimate Bro 3, Miracle 3, 6 and 12 (Asahi Intec, Japan) and is advanced in a retrograde manner to the most proximal part possible. The recently introduced Gaia 2(Asahi Intec, Japan) is effective for retrograde tracking of true lumen. If the distal cap is very hard and calcified, Conquest Pro or Conquest Pro 12 (Asahi Intec, Japan) should be used. While keeping the retrograde approach in place, an antegrade approach is also commenced. After successful penetration of the tip of the retrograde guidewire into the CTO lesion, one or a combination of the following different strategies is used. RETROGRADE WIRE CROSSING TECHNIQUE When a wire crosses the entire occlusion in a retrograde manner, it is called "retrograde wire crossing". After deeply negotiating the retrograde wire into the aorta or the antegrade guide, it can be anchored by inflating a small balloon (2-2.5 mm) within the antegrade guide catheter to facilitate crossing of the occlusion with the Corsair (Figs. 2, 3). If this fails, the Corsair is exchanged for a 1.25 or 1.5 mm OTW balloon, which usually has a smaller crossing profile than the Corsair to perform the retrograde balloon dilatation in the occlusion so that any subsequent procedure can be accomplished in the antegrade manner. This is the simplest way of all the retrograde techniques and can be achieved in 30% of cases, but it is the view of the author that the success rate could be 50% with appropriate wire escalation. When direct retrograde wire crossing fails, other techniques to connect the antegrade and retrograde channels are the kissing wire, controlled antegrade and retrograde subintimal tracking (CART) technique, Reverse CART, and knuckle wire technique (KWT). KISSING WIRE TECHNIQUE The retrograde wire is advanced to the proximal part within the CTO lesion. If the tip of this guidewire approaches the proximal cap of the CTO with its tip in alignment with the antegrade guidewire, both the antegrade and retrograde guidewires (Figs. 4, 5) meet (kiss) (Fig. 1). However, it is difficult to align both wires inside the occluded true channel as there are many diseased layers inside the occlusion. THE CART TECHNIQUE The CART technique consists of antegrade wiring through the CTO where retrograde balloon creates a local subintimal dissection for facilitating wire crossing to the distal true lumen. At first, a wire is advanced antegradely, trying to cross the CTO. If the wire has entered the subintimal space, it is left in this position. A second wire is advanced in a retrograde manner through the CC under the support of a microcatheter. This wire is positioned at the distal end of the CTO, then penetrated retrogradely from the distal true lumen into the CTO, and finally into the subintimal space at the CTO site. A small balloon (1.5-2 mm) is advanced over the retrograde wire into the subintimal space; it is then dilated in the same space and also on the course from this subintimal space to the proximal cap of the CTO. The deflated balloon should be left in place to keep this subintimal space open. This enables two dissections (created by antegrade wire and the retrograde balloon) to lie in the subintimal space at the CTO site. Thereafter, the antegrade wire is advanced further along the deflated retrograde balloon that lies from the subintimal space to the distal true lumen (Fig. 6). Then ballooning and stent implantation can be performed over the antegrade wire. The advantage of this technique is the minimization of just subintimal tracking through the length of the CTO lesion. The limitation is that, it is not always possible to negotiate a retrograde balloon inside the occlusion, particularly in complex CTO lesions. Subintimal space extending to the proximal true lumen of the CTO may cause a fatal event when the CTO is located in the proximal part of the left coronary system (e.g. dissection of the left main). Other limitations are empiric estimation of retrograde balloon size and unpredictable procedure time. It is advisable to use the closest sized balloon inside the CTO to create sufficient wire re-entry space. With introduction of the Corsair microcatheter the CART technique is rarely employed except in some cases of ostial occlusions, heavily calcified occlusions, and when the microcatheter is unable to enter the occlusion. REVERSE CART TECHNIQUE The reverse CART technique consists of dilatating the CTO lesion with the balloon through the antegrade wire followed by retrograde wire being advanced into the space dilated with the antegrade balloon. A wire is negotiated in a retrograde manner into the distal cap of the CTO and another is advanced antegradely in the proximal cap of the CTO. The retrograde wire is advanced into the subintimal space into the CTO lesion. The subintimal space created by antegrade wire is enlarged by inflating a balloon to create a plaque dissection and modification of the lesion which is target space for retrograde wire penetration into the proximal true lumen. Next, the retrograde wire is externalized through the guide and is used for subsequent antegrade angioplasty (Figs. 7, 8). The tip of retrograde microcatheter should be in the mid portion of the antegrade balloon. Before balloon inflation, the balloon and retrograde microcatheter may lie 4 to 5 mm apart on fluoroscopy, yet they are both in subintimal space. With balloon inflation, the two subintimal spaces become one space. There should be no space between the balloon and the retrograde microcatheter. If a gap exists, there remains tissue between the two and the common space does not exist. In this scenario, either a higher inflation pressure is required or a larger diameter balloon needs to be used. On deflation of the balloon, the retrograde support catheter can be seen "drooping" into the common space created indicating a continuous pathway from distal true lumen, through the subintimal space, and into the proximal true lumen. This technique is predictable and reproducible as compared to classical CART. Undersizing of the antegrade balloon makes the creation of a common subintimal space much more difficult. The subintimal space may either compress or collapse after antegrade balloon inflation or deflation, making the true lumen wiring more difficult even with continuous subintimal connection. The "Stent Reverse CART" technique entails deployment of a stent within the antegrade dissected plane to create an open target for retrograde crossing. An alternative method is to use a Guideliner mother-in-child catheter (Vascular solutions, Minneapolis, MN, USA) into the space to help connect the retrograde wire to the antegrade guide (Mother-in-child Reverse CART). Unlike a stent, a catheter may be removed or repositioned if the connection between the antegrade and the retrograde true lumen fails. Recoil of subintimal channel may occur even after successfully connecting the channel between the antegrade and retrograde space. Moreover, blind medial disruption with the antegrade balloon potentially causes bidirectional expansion of the subintimal dissection making retrograde wire crossing difficult. The intravascular ultrasound (IVUS) estimates optimal antegrade balloon size that avoids risk of perforation. A smaller size balloon should be used in presence of calcified plaque. If IVUS indicates the recoil of a connecting channel, redilatation with a bigger balloon should be performed. IVUS also directly visualizes the position of retrograde wire in the subintima. The retrograde wire could be navigated into proximal true lumen under IVUS (IVUSguided reverse CART). An important precaution is to avoid contrast injections after creating antegrade subintimal dissection until the last stent is deployed to prevent pressurized contrast injection into the dilated segment causing a spiral dissection or hematoma. THE KWT TECHNIQUE The KWT technique is employed in case of failure of retrograde wire escalation or when the CTO is quite long with vessel ambiguity. This entails creating a small loop with retrograde polymer jacketed wire Fielder FC, XT (Asahi Intec, Japan) or Pilot 200 (Abbott Vascular, USA), which is advanced inside the occlusion and creates subintimal space so that antegrade wire in the subintima can be led inside this space. The antegrade KWT can be combined with retrograde KWT in complex CTO lesions. The limitations of this technique are such that a longitudinal dissected plane cannot be controlled and the cross-sectional dissected wire is not wide enough to lead the antegrade wire. Knuckle wire should be pushed, but never rotated for fear of wire knotting. WIRE TRAPPING TECHNIQUE After retrograde wire crossing, the antegrade wire can be trapped in the distal lumen by an inflated balloon to create an extra back up force for balloon crossing or stent delivery. In retrograde wire crossing or reverse CART technique, retrograde wire can be trapped in the proximal lumen or in the guide catheter for easy passage of retrograde balloon inside the occlusion. After the retrograde wire enters the ascending aorta, a gooseneck microsnare (Amplatz, USA) is inserted and snares the retrograde wire tip from the aorta into the antegrade guiding catheter. The microsnare is pulled back slowly and carefully until retrograde wire is pulled out of the antegrade guiding catheter. The balloon and stent can be delivered over retrograde wire to recanalize the occlusion. REVERSE WIRE TRAPPING TECHNIQUE After crossing the CTO lesion, entering the ascending aorta, and being snared by the antegrade microsnare, the retrograde wire is drawn back, dragging the microsnare tip to advance through the occlusion simultaneously. After the microsnare and microcatheter have crossed the lesion antegradely, the retrograde wire is released. Afterwards the microsnare is drawn back and exchanged for an antegrade wire followed by balloon dilatation and stent implantation. THE RENDEZVOUS (BRIDGE) TECHNIQUE In this technique, antegrade and retrograde microcatheters are aligned in a guide catheter at the level of the ascending aorta, after which an antegrade wire is pulled into a ret-rograde microcatheter. The antegrade wire is advanced further down beyond the CTO site through the retrograde microcatheter. This bridge technique could be used in case of failure of advancement of antegrade wire, whereas retrograde wire can be negotiated using a microcatheter. This can also be applied in cases of large dissection and uncertainty in the movement of wire, or in cases where CCs are small and not ideal for large retrograde balloon dilatation. This can replace wire externalization by 300-cm wire. DOUBLE BALLOON INFLATION Two overlapping balloons inserted in the retrograde and antegrade subintimal spaces are inflated simultaneously to join the subintimal spaces together with confluence in Reverse CART technique. This allows the retrograde wire to pass easily through this newly created confluent subintimal space and then finally into true lumen. EXTERNALIZATION The crossing wire is exchanged for an externalization wire after a microcatheter is delivered into the antegrade guide. The externalization of the retrograde wire must be carried out with utmost care. The retrograde guide catheter may be deep throated; this needs to be avoided to prevent ostial damage. While advancing the stiffer shaft of the retrograde wire into the CC, the collateral needs to be protected by the presence of the microcatheter. Several workhorse wires come in ≥ 300 cm (300-cm Pilot 200 wire, Abbott Vascular, USA; 325 cm Rota floppy, Boston Scientific, USA; 335 cm Viper, CSI, St Paul, Minnesota; 300 cm RG3, Fielder FC, Asahi Intec, Japan) for externalization. The Viper wire is extraordinarily stiff, and is often difficult to pass through very tortuous CCs. This has been overcome by flushing the channel dilator with Rotaglide solution (Boston Scientific, USA) before the externalization wire is inserted. The shaft of the Rota floppy wire is only 0.009" in diameter, and is easily kinkable. It should be used as a last resort if no other long wires are available. RG3 wire has emerged as an ideal guidewire. However, the shaft is not as stiff as a standard coronary wire and therefore it gives less support to balloons and stents after externalization. Despite coaxial antegrade guide, retrograde passage of wire into guide fails in conditions such as in aorto-ostial lesions or extremely tortuous vessels, or whenever there is poor retrograde wire control. Difficulty in wiring the antegrade guide can be overcome by snaring. The 3-snare system, referred to as tulip snare (EN Snare; Merit Medical Systems, South Jordan, USA), is the most useful snaring system for externalization of wire during retrograde procedure. The larger the snare the better it is. An 18x30 mm EN Snare, which is 6 French compatible, is preferred. FINAL TREATMENT Once the externalized wire approaches the antegrade guiding hub, the operator needs to detach the copilot, place a finger over the hub of antegrade guide, and wait for retrograde wire to tap it. Retrograde wire is pushed 5 to 7 cm out of the guide, once the tap is felt. Then a wire introducer is placed into antegrade copilot and the externalized soft tip of the wire is threaded. Introducer and copilot over the wire are slided and reconnected without flushing. Flushing after reverse CART can result in hydraulic dissection. Ballooning and stenting is performed after 20 to 30 cm wire is externalized. Retrograde injection is used for a distal landing zone for stents. Externalized wire in a tortuous artery should always be protected with a catheter. The stiff part of the wire should be under cover of a channel dilator or channelcrossing catheter. The end of the externalized wire should never be pulled unless the CC is protected. However, pushing is always permitted but still it needs to be done with protection of the CCs. REMOVAL OF THE EXTERNALIZED WIRE AND CORSAIR CHANNEL DILATOR To remove the wire, the channel dilator should be readvanced into the antegrade guide. It must protect the CC until the soft wire tip is back in the CC. Both antegrade and retro-grade guiding catheters are disengaged from the coronary ostium and pulled back 3 to 4 cm into the aorta to avoid ostial dissection because of externalized wire retraction. After establishing guiding catheter control, the externalized wire is removed and gradually synchronized with the heart beat taking care not to kink it. Then the channel dilator is removed with clockwise rotation. However, some operators advocate leaving some part of the wire within the channel dilator to retract it so that CC can be assessed in the event of its rupture that could otherwise manage this complication rapidly. Once the retrograde system has been removed successfully, a careful angiographic demonstration of the integrity of the CCs, as well as checking for extravasations, needs to be performed via the retrograde catheter. COMPLICATIONS ASSOCIATED WITH THE PRO-CEDURE Specific complications pertaining to retrograde approach are CC rupture, thrombus formation, and global ischemia. Most CC ruptures are benign and do not require further treatment apart from abandoning that CC and trying for another. The channel dilator is safer than a balloon and rarely causes CC dissection or perforation even in CC with excessive tortuosity. While advancing the microcatheter, if septal wire shows excessive kinking, the wire has to be withdrawn to prevent septal perforation. If there is small septal perforation to the right or left ventricle, observation can be made. Septal hematoma or cardiac tamponade needs embolic occlusion via microcatheter. Before pulling out the retrograde wire, the donor artery should be visualized with the externalized wire in place. Then a microcatheter from both ends of the wire would allow access to a bleeding point. Thrombus formation is prevented by saline flush of the guide catheter and by maintenance of ACT >300 seconds and checked every 20-30 min. Global ischemia can be minimized by careful manipulation of retrograde wire. Stenting should be done if there is significant stenosis to the CC of the donor artery. Catheter induced dissection occurs when the retrograde devices are withdrawn. This could be prevented by constant pulling of the guide catheter to disengage from the ostium, while gentle rotation (in either direction) of the channel dilator is performed to withdraw it. CONCLUSION A growing body of evidence demonstrates that successful PCI of CTO translates into clinical benefit. However, because of the perceived procedural complexity, CTO still is the most common reason for discarding PCI. The proven clinical benefit, as well as the improved long-term patency with drug-eluting stents, has resulted in a growing interest among interventionists for treating CTOs. Tremendous improvements in the PCI equipment, and the development of innovative strategies including the retrograde techniques, have allowed for a success rate of up to 95%, even in complex CTO cases. With the application of the soft polymercoated wires, IVUS, and channel dilators like Corsair, more and more would be managed by reverse CART, while conventional CART is still likely to be needed in ostial occlusions, heavily calcified occlusions, and if the microcatheter is unable to enter the occlusions. Collaborative efforts to share experience of this retrograde technique and overcome challenges through refinement in technique and technology would be pivotal to further success in CTO PCI. CONFLICT OF INTEREST The author confirms that this article content has no conflict of interest.
def main_layout(): return OrderedDict( ( ("editable", True), ("hideControls", False), ("id", None), ("originalTitle", ""), ("refresh", "1m"), ("schemaVersion", 6), ("sharedCrosshair", False), ("style", "dark"), ("tags", []), ("timezone", "utc"), ("title", ""), ("version", 0), ("annotations", OrderedDict((("list", []), )) ), ("nav", [ OrderedDict((("type", "timepicker"), ("collapse", False), ("notice", False), ("enable", True), ("status", "Stable"), ("now", True), ("refresh_intervals", [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ])) ) ] ), ("rows", []), ("time", OrderedDict((("from", "now-6h"), ("to", "now"))) ) ) )
__author__ = 'regu0004'
<reponame>a-padhy/hacktoberfest2021-1 class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { //Key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i; } return result; } };
A case of sporotrichosis treated successfully with oral fluconazole 200 mg once weekly Summary. A case of fixed cutaneous sporotrichosis that developed on the extensor aspect of the left wrist of an 83yearold woman was treated once a week with 200 mg of oral fluconazole. This dermatological lesion healed within 4 months, leaving a scar. No sideeffects were seen. At the time of writing, 7 months after the end of treatment, there has been no recurrence. Reports on the efficacy of onceweekly fluconazole administration in cases of sporotrichosis have appeared, but it would be valuable to study more such cases.
<reponame>huawenbo/ERSW-project def SVM_model(x_train, y_train, x_test, y_test): model = SVC(kernel='rbf', probability=True) model.fit(x_train,y_train) pred_train = model.predict_proba(x_train)[:,-1] pred_test = model.predict_proba(x_test)[:,-1] result = [roc_auc_score(y_train,pred_train), roc_auc_score(y_test,pred_test)] return model, result, (y_test.values, pred_test)
/** * Returns the lattice of neurons. * @return the lattice of neurons. */ public double[][][] neurons() { double[][][] lattice = new double[nrow][ncol][]; for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { lattice[i][j] = map[i][j].w; } } return lattice; }
package buildinfo import ( "fmt" "strconv" "time" ) var ( Version = "head" // set by command-line on CI release builds BuiltAt = "" // set by command-line on CI release builds Commit = "" // set by command-line on CI release builds VersionString = "" // formatted on boot from 'version' and 'builtAt' ) func init() { buildVersionString() } func BuildTime() *time.Time { if BuiltAt == "" { return nil } epoch, err := strconv.ParseInt(BuiltAt, 10, 64) if err != nil { return nil } t := time.Unix(epoch, 0) return &t } func buildVersionString() { timeString := "no build date" buildTime := BuildTime() if buildTime != nil { timeString = fmt.Sprintf("built on %s", buildTime.Format("Jan _2 2006 @ 15:04:05")) } VersionString = fmt.Sprintf("%s, %s", Version, timeString) if Commit != "" { VersionString = fmt.Sprintf("%s, ref %s", VersionString, Commit) } }
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flaskweb import routes app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config.update(dict( SECRET_KEY="powerful secretkey", WTF_CSRF_SECRET_KEY="a csrf secret key" )) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app) bcrypt = Bcrypt(app) login_manager = LoginManager(app) from flaskweb import routes
# -*- coding: utf-8 -*- """Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from resilient_circuits.util import get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResult PACKAGE_NAME = "fn_utilities" FUNCTION_NAME = "utilities_shell_command" # The default configuration-data section from the package config_data = """[fn_utilities] remote_powershell_extensions=ps1 # remote auth transport one of [ntlm, basic] remote_auth_transport=ntlm # remote computers missing_parens=foo incorrect_pswd_creds=(<PASSWORD>@192.168.1.186) correct_host=(ms:foo@192.168.1.186) # remote shell commands remote_command=[remote path to script] # local shell_command default commands (unix) nslookup=nslookup "{{shell_param1}}" dig=dig "{{shell_param1}}" traceroute=(tracepath '{{shell_param1}}') traceroute_windows=[traceroute.ps1] whois=whois "{{shell_param1}}" # remote shell cmd bad_suffix=[bad_suffix.ps2] missing_brackets=missing_brackets good_remote=[good_remote.ps1] """ # Provide a simulation of the Resilient REST API (uncomment to connect to a real appliance) resilient_mock = "pytest_resilient_circuits.BasicResilientMock" def call_shell_command_function(circuits, function_params, timeout=10): # Fire a message to the function evt = SubmitTestFunction(FUNCTION_NAME, function_params) circuits.manager.fire(evt) event = circuits.watcher.wait("{}_result".format(FUNCTION_NAME), parent=evt, timeout=timeout) assert event assert isinstance(event.kwargs["result"], FunctionResult) pytest.wait_for(event, "complete", True) return event.kwargs["result"].value class TestShellCommand: """ Tests for the shell_command function""" def test_function_definition(self): """ Test that the package provides customization_data that defines the function """ func = get_function_definition(PACKAGE_NAME, FUNCTION_NAME) assert func is not None @pytest.mark.parametrize("shell_command, shell_param1, expected_results", [ ('nslookup', "text", {"value": "xyz"}), ('dig', "text", {"value": "xyz"}) ]) def test_local_success(self, circuits_app, shell_command, shell_param1, expected_results): """ Test calling with sample values for the parameters """ function_params = { "shell_command": shell_command, "shell_param1": shell_param1 } #results = call_shell_command_function(circuits_app, function_params) #assert(expected_results == results) @pytest.mark.parametrize("shell_remote, shell_command, shell_param1", [ (True, 'nslookup:', None), (True, 'nf_cmd:na_host', None), (True, 'missing_parens:na_host', None), (True, 'incorrect_pswd_creds:na_host', None), (True, 'nf_cmd:correct_host', None), (True, 'nslookup:correct_host', None), (True, 'bad_suffix:correct_host', None), (True, 'missing_brackets:correct_host', None) ]) def test_remote_failures(self, circuits_app, shell_remote, shell_command, shell_param1): with pytest.raises(Exception): function_params = { "shell_remote": shell_remote, "shell_command": shell_command, "shell_param1": shell_param1 } results = call_shell_command_function(circuits_app, function_params) @pytest.mark.parametrize("shell_remote, shell_command, shell_param1", [ (False, 'good_remote', None), (False, 'remote_command', None), (False, 'correct_host', None) ]) def test_local_failures(self, circuits_app, shell_remote, shell_command, shell_param1): with pytest.raises(Exception): function_params = { "shell_remote": shell_remote, "shell_command": shell_command, "shell_param1": shell_param1 } results = call_shell_command_function(circuits_app, function_params)