text:
Scott BH
Factors influenc...
Blood Transfusio...
Transfusion duri...
Complications of...
Blood transfusion in cardiac surgery: Is it appropriate?
Bharathi H Scott
Department of Anesthesiology, SUNY at Stony Brook Helath Sciences Center, Stony Brook, New York, USA
Scott BH. Blood transfusion in cardiac surgery: Is it appropriate?. Ann Card Anaesth 2007;10:108-12
Scott BH. Blood transfusion in cardiac surgery: Is it appropriate?. Ann Card Anaesth [serial online] 2007 [cited 2021 Jan 20];10:108-12. Available from: https://www.annals.in/text.asp?2007/10/2/108/37935
Blood transfusion is commonly used in cardiac surgical patients and accounts for about 10-20% of blood transfused. Inspite of published guidelines there are tremendous variations in transfusion practices among physicians and institutions. The incidence of blood transfusion among patients undergoing cardiac surgery has been reported to vary between 27% and 92%. [1] More recently it has been reported to be 29.4%. [2] It is noted that approximately 10-20% of patients consume 80% of total blood transfused among cardiac surgery patients. [3] The observed variability in transfusion practices may be reduced by altering blood use in this high usage group. Although there are concerns about blood shortage and risks of allogenic blood transfusion, present rate of blood utilization is expected to continue because the transfusion guidelines are not applied appropriately and consistently. It is important to note that blood transfusion is safer than ever today in the United States. This is attributed to the new testing guidelines and donor policies. On the other hand these new guidelines are also responsible for donor shortage. Needless to say transfusion trigger in patients undergoing cardiac surgery and cardiopulmonary bypass (CPB) remains contentious. The aim of this review is to provide clinically useful guidelines, based on available evidence.
Factors influencing blood transfusion
The factors influencing blood utilization are well documented. They include, older age, female gender, comorbidities, small body size, low preoperative haematocrit, preoperative antiplatelet or anti-thrombotic medication, redo and complex procedures, emergency operations, and on-pump surgery. [4]
Blood Transfusion. Why we do it?
Clinicians transfuse blood to increase haemoglobin (Hb) levels with the intention of increasing oxygen carrying capacity, blood volume, especially in acute blood loss and in the process improve outcomes. [5] Studies examining impact of blood transfusion on clinical outcomes often have shown conflicting and confusing results. It is hard to define the benefits of blood transfusion, since randomized trials to support the use of blood products do not exist. However, clinical reports of survival benefit support transfusion in certain clinical situations. [6],[7],[8] So what are the risks of anaemia? Most of the information on the risks of anaemia is from our experience with patients who refuse blood transfusion on religious grounds. One of the earlier studies showed that patients with lower haematocrits had higher mortality especially in patients with cardiovascular disease. [9] The next question to ask is how low can the Hb go without adverse consequences?
Weiskopf et al showed that Hb lowered to 5-6 g/dL produced subtle decreases in cognitive function in humans, which was reversed with transfusion of blood to a Hb >7g/dL. [5] Jehovah witness patients with ischaemic heart disease had increased mortality, if preoperative Hb was <10 g/ dL. [9] Increased incidence of myocardial ischaemia was noted in patients with haematocrit <28% undergoing radical prostatectomies and vascular surgery. [10],[11]
So from these studies it is reasonable to conclude that in patients with coronary artery disease, anaemia increases mortality and morbidity. What should the transfusion trigger be? Lowest haematocrit that can be tolerated in patients with coronary artery disease is not known. At the present time there is a lot of uncertainty as to the level of haematocrit at which blood transfusion should be triggered in the perioperative setting and during CPB.
The American Society of Anesthesiologists published transfusion guidelines in 1996 and an amended report was published in 2005. This task force developed a consensus statement based mostly on best available evidence that concluded that "red blood cell transfusions should not be dictated by a single Hb transfusion trigger but instead should be based on the patient's risk of developing complications of inadequate oxygenation". These guidelines do not specifically address the transfusion needs of the cardiac surgery patient. Based on the American Society of Anesthesiologists and Society of Thoracic Surgeons guidelines, it is reasonable to advocate blood transfusion when Hb is <6g/dL. Blood transfusion is probably not indicated in patients with Hb >10g/ dL. [12],[ 13] There is also a general consensus that patients with cardiovascular disease should be transfused at higher haematocrit levels when compared to their healthy counterparts. Because of lack of randomized trials to define the optimum transfusion trigger in cardiac surgery, this issue will continue to remain controversial. [12]
The author believes that it is important to examine at what level of haematocrit the benefits of transfusion outweigh the risks. Wu et al demonstrated that in patients with acute myocardial infarction, haematocrit <33% was associated with increased 30 day and one year mortality. Those who received transfusion for haematocrits less than 33% had lower mortality rates than patients who did not receive a transfusion for similar haematocrit levels. [14] Cardiac anaesthesiologists deal with similar patients in their practice and the author believes this supports the belief that patients with cardiovascular disease have better outcomes with higher haematocrit levels. Routine use of blood transfusion to maintain an arbitrary haematocrit is questioned as there is conflicting data as to whether blood transfusion really improves patient outcome. Bracy et al in a randomized control trial examined the impact of transfusion at two different triggers. One group received transfusion with a Hb level <9.0g/dL as threshold for transfusion and the second group received transfusion for Hb level <8.0 g/dL.This study demonstrated that there were no differences in the outcome between the two groups. [15] In this study functional recovery issue was not addressed. There is limited data in this area, but it is suggested that patients with Hb levels <10g/dl improve their exercise tolerance and functional recovery with transfusion. The author believes this is an important consideration, as cardiac surgery patients are routinely fast tracked and discharged early from hospitals.
Transfusion during cardiopulmonary bypass
This is another controversial area. The Society of Thoracic Surgeons guidelines suggests that in patients with severe anaemia on CPB (Hb£ 6.0 g/ dL or £8 g/dL in elderly patients) or acute blood loss (³30% of blood volume), receive red blood cell transfusion to support cardiac output and sustain oxygen carrying capacity with the expectation that operative mortality will be improved. Certain patients with critical non-cardiac end-organ ischaemia (e.g. central nervous system, gastrointestinal system) may also benefit from Hb levels as high as 10 g/dL, but more evidence to support this recommendation is required. [13] In the setting of Hb values exceeding 6 g/dL while on CPB, the patient's clinical situation should be considered as the most important component of the decision making process. Indications for transfusion of red blood cells in this setting are multifactorial and should be guided by patientrelated factors such as age, acuity of illness, endorgan ischaemia, cardiac function, the clinical setting of active blood loss and laboratory or clinical data. Fang et al demonstrated that haematocrit less than 17% during CPB in high risk patients was an independent predictor of increased mortality. [16] Again, the decision to transfuse should be based on the risk for organ ischaemia and potential for or presence of active bleeding.
In a comprehensive database study from the Northern New England Cardiovascular Disease Study Group, DeFoe et al reported that of 6,980 consecutive patients who underwent coronary artery bypass at six medical centres between 1996 and 1998, the lowest haematocrit during CPB was associated with increased mortality, return to bypass after separation and increased incidence of intra-aortic balloon placement. They also noted that patients with low preoperative haematocrit and smaller body size, as expected had low haematocrits during CPB leading to higher mortality risk. This was attributed to greater haemodilution and anaemia during CPB. [17]
Habib et al reported a retrospective analysis of operative results and resource utilization in consecutive cardiac operations with CPB. [18] Myocardial infarction, renal failure, stroke, prolonged ventilation, sepsis and multiorgan failure were significantly increased as lowest haematocrit value decreased below 22%. They noted that hospital length of stay, and mortality were significantly greater as a function of haemodilution severity. Long-term survival is improved in patients with higher haematocrits during CPB, suggesting that increased haemodilution severity is associated with worse perioperative outcomes. [18] Karkouti et al prospectively evaluated 10,949 consecutive patients who underwent coronary bypass with extracorporeal circulation from 1999 to 2004, and reported that nadir haematocrit of 21% during cardiopulmonary bypass was an independent predictor of perioperative stroke. After controlling for confounding variables, each percent decrease in haematocrit was associated with a ten percent increase in the odds of suffering perioperative stroke. [19] Hardy et al demonstrated that Hb <6 gm/dL in the first 24 hours after CPB was associated with increased incidence of renal and gastrointestinal complications. The low Hb group also had longer length of stay and haemodynamic instability. [20] Karkouti et al in yet another observational study showed that the nadir haematocrit <21% during CPB was associated with acute renal failure. [21]
Blood transfusion in the postoperative cardiac surgery patient
Blood transfusion in this group of patients after surgery requires careful consideration of patient factors such as cardiac, pulmonary and neurological status, surgical factors such as potential for ongoing bleeding and haemodynamic and physiological parameters. Again, there is a paucity of data in support of transfusion. Society of Thoracic surgeons guidelines strongly recommends blood transfusion, when Hb level is < 6g/dL, especially when anaemia is acute and it is reasonable to transfuse, if Hb is <7g/dL. Transfusion is not recommended, if Hb is >10g/ dL. [13] Hebert et al found that patients with cardiac disease admitted to the critical care unit had a significantly higher risk of death with lower Hb value. [22] But in a subsequent prospective, randomized, controlled trial the same authors reported that there was no difference in mortality between restrictive and liberal transfusion groups. They claimed that the restrictive protocol was at least as effective and possibly superior to the liberal transfusion protocol. [23] Spiess et al examined the impact of transfusion in patients undergoing coronary artery bypass grafts. They divided their patients into three groups based on the admission haematocrit in the intensive care unit. They found that patients classified into the high haematocrit group (34%) had higher incidence of myocardial infarction than the patients in the low group (<24%). [24]
Complications of Blood transfusion
Complications associated with blood transfusion include, ABO incompatibility, alloimmunization, immunosuppression, febrile reactions, infections, pneumonia, sepsis, and viral transmission. Bradykinin, cytokines and complement in stored blood are thought to cause acute lung injury and add to inflammatory response after cardiopulmonary bypass. [25] Blood transfusion in coronary operations has been associated with increased risk of mortality during a one year followup period with the majority of deaths occurring within the first thirty days. [26] Because of the possible association of blood transfusion on CPB with worse outcomes, several investigators evaluated this possibility with observational studies. Engoren and co-workers studied 1,915 patients who underwent first-time isolated coronary artery bypass operations between 1994 and 1997 and found that 649 of the study patients (34%) received a transfusion during their hospitalization. Transfused patients were older, smaller, more likely to be female, and had more co-morbidity. The transfused patients also had twice the five-year mortality (15% vs. 7%) of non-transfused patients. After correction for co-morbidities and other factors, transfusion was still associated with an increase in mortality. The authors concluded that blood transfusions during or after coronary bypass operations are associated with increased long term morbidity and mortality. [27] In a review of over 15,000 patients undergoing CPB procedures at the Cleveland Clinic a strong association was demonstrated between the use of transfusions and postoperative infections. [28] Examining the data over a period of three years at the author's institution, it was found that transfused patients had significantly higher mortality, morbidity and length of stay. It should be pointed out that transfused patients had significantly more preoperative comorbidities. [29] All of the data reviewed above are derived from observational studies and therefore only document associations but not cause and effect. Anaemia may well drive a number of physiological responses as well as physician behaviours such as inclination towards transfusion. It is therefore unclear at this time how important any level of anaemia is, in creating organ failure or long term adverse outcomes. Then to add to all this conflicting information, it has been shown that 28 days or longer stored red blood cells are depleted of 2,3 diphosphoglycerate leading to leftward shift of the oxyhaemoglobin dissociation curve. This leads to question the basic premise of blood transfusion as a vehicle to increase oxygen carrying capacity. [30] The storage duration of red blood cells is shown to be associated with increased intensive care and hospital length of stay and mortality. [31]
The author believes that it is important to recognize that despite a large body of literature, the precise haematocrit, at which benefits of blood transfusion outweigh the risks is not known. Most cardiac anaesthesiologists would agree that it is reasonable to administer blood when Hb is <7 g/dL especially to treat symptoms and signs of inadequate tissue oxygen delivery, and transfusion is not needed when Hb is >10g/dL. The practice of blood transfusion in the setting of Hb between 7.1 and 9.92g/dL is variable and perhaps, determined by the patient's condition. In the clinical setting, the anaesthesiologist will continue to make transfusion decisions based on clinical assessment of the situation weighing risks versus benefits of blood transfusion. Guidelines presently available may not apply to every patient, especially in high risk cardiac surgical patients. Practitioners and institutions should develop their own multidisciplinary blood transfusion and conservation guidelines to maintain appropriate blood transfusion practices.
1. Stover EP, Siegel LC, Parks R, et al. Variability in transfusion practice for coronary artery bypass surgery persists despite national consensus guidelines: a 24institution study. Institutions of the Multicenter Study of Perioperative Ischemia Research Group. Anesthesiology 1998; 88: 327-333.
2. Karkouti K, Cohen MM, McCluskey SA, Sher GD. A multivariate model for predicting the need for blood transfusion in patients undergoing first time elective coronary artery bypass graft surgery. Transfusion 2001; 41: 1193-203.
3. Ferraris V, Ferraris S. Limiting excessive postoperative blood transfusion after cardiac procedures: A review. Tex Heart Inst J. 1995; 22: 216-230.
4. Scott BH, Seifert FC, Glass PSA, et al. Blood use in patients undergoing coronary artery bypass surgery: Impact of cardiopulmonary bypass pump, hematocrit, gender, age and body weight. Anesth Analg 2003; 97: 958-63.
5. Weiskopf RB, Viele MK, Feiner J, Kelley S, et al. Human cardiovascular and metabolic response to acute, severe isovolemic anemia. JAMA 1998; 279: 217-221.
6. Goodnough LT, Despotis GJ. Transfusion medicine: support of patients undergoing cardiac surgery. Am J Cardiovasc Drugs 2001; 1: 337-351.
7. Carson JL, Noveck H, Berlin JA, Gould SA. Mortality and morbidity in patients with very low postoperative Hb levels who decline blood transfusion. Transfusion 2002; 42: 812-818.
8. Carson JL, Duff A, Poses RM, Berlin JA, et al. Effect of anaemia and cardiovascular disease on surgical mortality and morbidity. Lancet 1996; 348: 1055-1060.
9. Viele MK, Weiskopf RB. What can we learn about the need for transfusion from patients who refuse blood? The experience with Jehovah's Witnesses. Transfusion 1994; 34: 396-401.
10. Nelson AH, Fleisher LA, Rosenbaum SH. Relationship between postoperative anemia and cardiac morbidity in high risk vascular patients in the intensive care unit. Crit Care Med 1993; 21: 860-866.
11. Hogue CW, Goodnough LT, Monk TG. Perioperative myocardial ischemic episodes are related to hematocrit level in patients undergoing radical prostatectomy. Transfusion 1998; 38: 924-931.
12. Guidelines. Practice Guidelines for blood component therapy: A report by the American Society of Anesthesiologists Task Force on Blood Component Therapy. Anesthesiology 1996; 84: 732-747 (amended in 2005 available at publicationsAndServices/BCTGuidesFinal.pdf.)
13. Ferraris VA, Ferraris SP, Saha SP, et al. Perioperative blood transfusion and blood conservation in cardiac surgery. The Society of Thoracic Surgeons and the Society of Cardiovascular Anesthesiologists practice guidelines. Ann Thorac Surgery 2007; 83: S 27-S 86.
14. Wu Wc, Rathore SS, Wang Y, et al. Blood transfusion in elderly patients with acute myocardial infarction. N Eng J Med 2001; 345: 1230-1236.
15. Bracey AW, Radovancevic R, Riggs SA, et al. Lowering the hemoglobin threshold for transfusion in coronary artery bypass procedures: Effect on patient outcome. Transfusion 1999; 39: 1070-1077.
16. 16 Fang WC, Helm RE, Krieger KH, et al. Impact of minimum hematocrit during cardiopulmonary bypass on mortality in patients undergoing coronary artery surgery. Circulation 1997; 96(Suppl II): 194-199.
17. DeFoe GR, Ross CS, Olmstead EM, et al. Lowest hematocrit on bypass and adverse outcomes associated with coronary artery bypass grafting. Northern New England Cardiovascular Disease Study Group. Ann Thorac Surg 2001; 71: 769-776.
18. Habib RH, Zacharias A, Schwann TA, et al. Adverse effects of low hematocrit during cardiopulmonary bypass in the adult: should current practice be changed? J Thorac Cardiovasc Surg 2003; 125: 1438-1450.
19. Karkouti K, Djaiani G, Borger MA, et al. Low hematocrit during cardiopulmonary bypass is associated with increased risk of perioperative stroke in cardiac surgery. Ann Thorac Surg 2005; 80: 1381-1387.
20. Hardy JF, Martineau R, Couturier A, et al. Influence of hemoglobin concentration after extracorporeal circulation on mortality and morbidity in patients undergoing cardiac surgery. Br J Anaesth 1998; 81: 38-45.
21. Karkouti K, Beattie WS, Wijeysundera DN, et al. Hemodilution during cardiopulmonary bypass is an independent risk factor for acute renal failure in adult cardiac surgery. J Tharac Cardiovasc Surg 2005; 129: 391-400.
22. Hebert PC, Wells G, Tweeddale M, et al. Does transfusion practice affect mortality in critically ill patients? Transfusion Requirements in Critical Care (TRICC) Investigators and the Canadian Critical Care Trials Group. Am J Respir Crit Care Med 1997; 155: 1618-1623.
23. Herbert PC, Wells G, Blajchman MA, et al. A multicenter, randomized, controlled clinical trial of transfusion requirements in critical care. Transfusion requirements in Critical Care Investigators. Canadian Critical care Trials Group. N Eng J Med 1999; 340: 409-417.
24. Spiess BD, Ley C, Body SC, et al. Hematocrit value on intensive care unit entry influences the frequency of Q wave myocardial infarction after coronary artery bypass grafting.The multicenter study of perioperative ischemia (Mc SPI) research group. J Thorac Cardiovasc Surg 1998; 116: 460-467.
25. Murkin JM, Wall MH. Transfusion trigger Hct 25%: Above or below, which is better? Pro: Hct <25% is better and Con : > 25% is better. J Cardiothorac Vasc Anesth 2004; 18: 234-241.
26. Kudavalli M, Oo AY, Newall N, et al. Effect of perioperative red blood cell transfusion on 30 - day and 1year mortality following coronary artery bypass surgery. Eur J of Cardiothorac Surg 2005; 27: 592-598.
27. Engoren MC, Habib RH, Zacharias A, et al. Effect of blood transfusion on long-term survival after cardiac operation. Ann Thorac Surg 2002; 74: 1180-1186.
28. Banbury MK, Brizzio ME, Rajeswaran J, et al. Transfusion increases the risk of postoperative infection after cardiovascular surgery. J Am Coll Surg 2006; 202: 131-138.
29. Scott B, Seifert F, Grimson R. Transfusion in cardiac surgery: Impact on hospital length of stay and mortality. Annual meeting of the American Society of Anesthesiologists. Chicago 2006. http:// www.asaabstracts.com A1014.
30. van Bommel J, decorate D, Lind A, et al. The effect of the transfusion of stored RBC's on intestinal microvascular oxygenation in the rat. Transfusion 2001; 41: 1515-1523.
31. Basaran S, Frumento RJ, Cohen A, et al. The association between duration of storage of transfused red blood cells and morbidity and mortality after reoperative cardiac surgery. Anesth Analg 2006; 103: 15-20.
Department of Anesthesiology SUNY at Stony Brook, Health Sciences Center, L4-060 Stony Brook, NY 11794-8480.
DOI: 10.4103/0971-9784.37935
1 Blood Transfusion Practice in a Referral Cardiovascular Center in Tehran, Iran: A Critical Point of View
Alireza Alizadeh Ghavidel,Ziae Totonchi,Abedin Hoseini,Mohsen Ziyaeifard,Rasoul Azarfarin
Research in Cardiovascular Medicine. 2014; 3(4)
2 Blutungsmenge und Gerinnung, Gabe von Blut, Transfusionstrigger
G. Trummer
Zeitschrift für Herz-,Thorax- und Gefäßchirurgie. 2013; 27(5): 347
3 The use of cell saver system in cardiac surgery with cardiopulmonary bypass [O uso de recuperador de sangue em cirurgia cardíaca com circulação extracorpórea]
Almeida, R.M.S. and Leitão, L.
Brazilian Journal of Cardiovascular Surgery. 2013; 28(1): 76-82
4 TRALI: A volley of caution
Gude, D.
Annals of Cardiac Anaesthesia. 2012; 15(1): 86-87
5 Transfusion triggers in cardiac surgery [Kardiyak cerrahide transfüzyon karari]
Gul̈er, T.
Gogus-Kalp-Damar Anestezi ve Yogun Bakim Dernegi Dergisi. 2012; 18(2): 27-45
6 Transfusion of red blood cells: The impact on short-term and long-term survival after coronary artery bypass grafting, a ten-year follow-up
Van Straten, A.H.M., Bekker, M.W.A., Soliman Hamad, M.A., Van Zundert, A.A.J., Martens, E.J., Schönberger, J.P.A.M., De Wolf, A.M.
Interactive Cardiovascular and Thoracic Surgery. 2010; 10(1): 37-42
7 Risk Factors for Red Blood Cell Transfusion After Coronary Artery Bypass Graft Surgery
van Straten, A.H.M. and Kats, S. and Bekker, M.W.A. and Verstappen, F. and ter Woorst, J.F.J. and van Zundert, A.J. and Soliman Hamad, M.A.
Journal of Cardiothoracic and Vascular Anesthesia. 2010; 24(3): 413-417
Albert H.M. van Straten,Suzanne Kats,Margreet W.A. Bekker,Frank Verstappen,Joost F.J. ter Woorst,André J. van Zundert,Mohamed A. Soliman Hamad
Journal of Cardiothoracic and Vascular Anesthesia. 2010; 24(3): 413
9 Gestion de la volémie durant la circulation extracorporelle en chirurgie cardiaque
F. Blaffart,J.-O. Defraigne
IRBM. 2010; 31: S22
10 Management of blood volume during extracorporeal circulation in cardiac surgery [Gestion de la volémie durant la circulation extracorporelle en chirurgie cardiaque]
Blaffart, F. and Defraigne, J.-O.
IRBM. 2010; 31(SUPPL. 1): S22-S26
11 Case study: Providence regional medical center improves surgical safety
Joint Commission Perspectives on Patient Safety. 2010; 10(8): 1-4+11
12 Intravenous treatment with iron in bloodless medicine [Podávání intravenózního železa v bezkrevní medicíně]
Slikpac, J.
Casopis Lekaru Ceskych. 2009; 148(10): 497-501
13 Intraoperative Transfusion of 1 U to 2 U Packed Red Blood Cells Is Associated with Increased 30-Day Mortality, Surgical-Site Infection, Pneumonia, and Sepsis in General Surgery Patients
Bernard, A.C. and Davenport, D.L. and Chang, P.K. and Vaughan, T.B. and Zwischenberger, J.B.
Journal of the American College of Surgeons. 2009; 208(5): 931-937e2
14 Blood Transfusion Reduction in Cardiac Surgery: Multidisciplinary Approach at a Community Hospital
James Brevig,Julie McDonald,Edy S. Zelinka,Trudi Gallagher,Ruyun Jin,Gary L. Grunkemeier
The Annals of Thoracic Surgery. 2009; 87(2): 532
Andrew C. Bernard,Daniel L. Davenport,Phillip K. Chang,Taylor B. Vaughan,Joseph B. Zwischenberger
Journal of the American College of Surgeons. 2009; 208(5): 931
Brevig, J. and McDonald, J. and Zelinka, E.S. and Gallagher, T. and Jin, R. and Grunkemeier, G.L.
The Annals of Thoracic Surgery. 2009; 87(2): 532-539
© Annals of Cardiac Anaesthesia | Published by Wolters Kluwer - Medknow


text:
#include <modules/opengl/openglcapabilities.h>
#include <modules/opengl/inviwoopengl.h>
#include <modules/opengl/texture/textureunit.h>
#include <inviwo/core/util/formatconversion.h>
#include <inviwo/core/util/logcentral.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/properties/optionproperty.h>
#include <modules/opengl/openglsettings.h>
#include <inviwo/core/util/settings/systemsettings.h>

namespace inviwo {

bool OpenGLCapabilities::glewInitialized_ = false;
std::string OpenGLCapabilities::preferredProfile_ = "core";
int OpenGLCapabilities::glVersion_ = 0;
std::string OpenGLCapabilities::glVersionStr_ = "0";

#define OpenGLInfoNotFound(message) { LogInfoCustom("OpenGLInfo",message << " Info could not be retrieved"); }

OpenGLCapabilities::GLSLShaderVersion::GLSLShaderVersion() : number_(0), profile_("") {}

OpenGLCapabilities::GLSLShaderVersion::GLSLShaderVersion(int num) : number_(num), profile_("") {}

OpenGLCapabilities::GLSLShaderVersion::GLSLShaderVersion(int num, std::string pro) : number_(num), profile_(pro) {}

std::string OpenGLCapabilities::GLSLShaderVersion::getProfile() {
    return profile_;
}

int OpenGLCapabilities::GLSLShaderVersion::getVersion() {
    return number_;
}

std::string OpenGLCapabilities::GLSLShaderVersion::getVersionAsString() {
    return toString<int>(number_);
}

std::string OpenGLCapabilities::GLSLShaderVersion::getVersionAndProfileAsString() {
    return (hasProfile() ? getVersionAsString() + " " + profile_ : getVersionAsString());
}

bool OpenGLCapabilities::GLSLShaderVersion::hasProfile() {
    return (profile_ != "");
}

bool OpenGLCapabilities::GLSLShaderVersion::sortHighestFirst(GLSLShaderVersion i, GLSLShaderVersion j) {
	return (i.getVersion()>j.getVersion());
}

OpenGLCapabilities::OpenGLCapabilities()
    : shadersAreSupported_(false)
    , shadersAreSupportedARB_(false)
    , geometryShsadersAreSupported_(false)
    , maxProgramLoopCount_(-1)
    , geometryShadersMaxVertices_(-1)
    , geometryShadersMaxOutputComponents_(-1)
    , geometryShadersMaxTotalOutputComponents_(-1)
    , texSupported_(false)
    , tex3DSupported_(false)
    , texArraySupported_(false)
    , fboSupported_(false)
    , maxTexSize_(-1)
    , max3DTexSize_(-1)
    , maxArrayTexSize_(-1)
    , maxArrayVertexAttribs_(-1)
    , maxColorAttachments_(-1)
    , numTexUnits_(-1)
{
    supportedShaderVersions_.clear();
    currentGlobalGLSLHeader_ = "";
    currentGlobalGLSLVertexDefines_ = "";
    currentGlobalGLSLFragmentDefines_ = "";
    OpenGLSettings* systemSets = InviwoApplication::getPtr()->getSettingsByType<OpenGLSettings>();
    if(systemSets){
        Property* selpro = systemSets->getPropertyByIdentifier("selectedOpenGLProfile");
        if(selpro){
            OptionPropertyString* selProProperty_ = dynamic_cast<OptionPropertyString*>(selpro);
            if(selProProperty_){
                preferredProfile_ = selProProperty_->getSelectedIdentifier();
            }
        }
    }
}

OpenGLCapabilities::~OpenGLCapabilities() {
    TextureUnit::deinitialize();
}

void OpenGLCapabilities::printInfo() {
    //OpenGL General Info
    LogInfoCustom("OpenGLInfo","GPU Vendor: " << glVendorStr_);
    LogInfoCustom("OpenGLInfo","GPU Renderer: " << glRenderStr_);
    if (isTexturesSupported()) {
        glm::u64 totalMem = getTotalAvailableTextureMem();
        LogInfoCustom("OpenGLInfo","Dedicated video memory: " << (totalMem>0 ? formatBytesToString(totalMem) : "UNKNOWN"));
    }
    LogInfoCustom("OpenGLInfo","OpenGL Version: " << glVersionStr_);
    std::string profile = preferredProfile_;
    profile[0] = toupper(profile[0]);
    LogInfoCustom("OpenGLInfo","OpenGL Profile: " << profile);

    if (isShadersSupported()) {
        LogInfoCustom("OpenGLInfo","GLSL version: " << glslVersionStr_);
    }
}

void OpenGLCapabilities::printDetailedInfo() {
    //OpenGL General Info
    LogInfoCustom("OpenGLInfo","GPU Vendor: " << glVendorStr_);
    LogInfoCustom("OpenGLInfo","GPU Renderer: " << glRenderStr_);
    LogInfoCustom("OpenGLInfo","OpenGL Version: " << glVersionStr_);
    std::string profile = preferredProfile_;
    profile[0] = toupper(profile[0]);
    LogInfoCustom("OpenGLInfo","OpenGL Profile: " << profile);

    //GLSL
    if (isShadersSupported()) {
        LogInfoCustom("OpenGLInfo","GLSL version: " << glslVersionStr_);
        LogInfoCustom("OpenGLInfo","Current set global GLSL version: " << getCurrentShaderVersion().getVersionAndProfileAsString());
        LogInfoCustom("OpenGLInfo", "Shaders supported: YES");
    }
    else if (isShadersSupportedARB()) {
        LogInfoCustom("OpenGLInfo","GLSL version: " << glslVersionStr_);
        LogInfoCustom("OpenGLInfo","Current set global GLSL version: " << getCurrentShaderVersion().getVersionAndProfileAsString());
        LogInfoCustom("OpenGLInfo","Shaders supported: YES(ARB)");
    }
    else
        LogInfoCustom("OpenGLInfo","Shaders supported: NO");

    if (isGeometryShadersSupported()){
        LogInfoCustom("OpenGLInfo", "Geometry shaders supported: YES");

        LogInfoCustom("OpenGLInfo", "Geometry shaders: Max output vertices : " << geometryShadersMaxVertices_);
        LogInfoCustom("OpenGLInfo", "Geometry shaders: Max output components: " << geometryShadersMaxOutputComponents_);
        LogInfoCustom("OpenGLInfo", "Geometry shaders: Max total output components: " << geometryShadersMaxTotalOutputComponents_);
    }
    else{
        LogInfoCustom("OpenGLInfo", "Geometry shaders supported: NO");
    }

    LogInfoCustom("OpenGLInfo","Framebuffer objects supported: " << (isFboSupported() ? "YES" : "NO "));
    // Texturing
    LogInfoCustom("OpenGLInfo","1D/2D textures supported: " << (isTexturesSupported() ? "YES" : "NO "));
    LogInfoCustom("OpenGLInfo","3D textures supported: " << (is3DTexturesSupported() ? "YES" : "NO "));
    LogInfoCustom("OpenGLInfo","Array textures supported: " << (isTextureArraysSupported() ? "YES" : "NO "));

    if (isTexturesSupported()) {
        LogInfoCustom("OpenGLInfo","Max 1D/2D texture size: " << getMaxTexSize());
    }

    if (is3DTexturesSupported()) {
        LogInfoCustom("OpenGLInfo","Max 3D texture size: " << getMax3DTexSize());
    }

    if (isTextureArraysSupported()) {
        LogInfoCustom("OpenGLInfo","Max array texture size: " << getMaxArrayTexSize());
    }

    if (isFboSupported()) {
        LogInfoCustom("OpenGLInfo","Max color attachments: " << getMaxColorAttachments());
    }

    if (isTexturesSupported()) {
        LogInfoCustom("OpenGLInfo","Max number of texture units: " << getNumTexUnits());
        glm::u64 totalMem = getTotalAvailableTextureMem();
        LogInfoCustom("OpenGLInfo","Total available texture memory: " << (totalMem>0 ? formatBytesToString(totalMem) : "UNKNOWN"));
        glm::u64 curMem = getCurrentAvailableTextureMem();
        LogInfoCustom("OpenGLInfo","Current available texture memory: " << (curMem>0 ? formatBytesToString(curMem) : "UNKNOWN"));
    }

}

bool OpenGLCapabilities::canAllocate(glm::u64 dataSize, glm::u8 percentageOfAvailableMemory) {
    return getCurrentAvailableTextureMem()*percentageOfAvailableMemory/100 >= dataSize;
}

uvec3 OpenGLCapabilities::calculateOptimalBrickSize(uvec3 dimensions, size_t formatSizeInBytes, glm::u8 percentageOfAvailableMemory) {
    uvec3 currentBrickDimensions = dimensions;

    while (!canAllocate(getMemorySizeInBytes(currentBrickDimensions, formatSizeInBytes), percentageOfAvailableMemory)) {
        int theMaxDim = (currentBrickDimensions.x > currentBrickDimensions.y ? (currentBrickDimensions.x > currentBrickDimensions.z ? 0 : 2) :
                         (currentBrickDimensions.y > currentBrickDimensions.z ? 1 : 2));

        if (currentBrickDimensions[theMaxDim] % 2 != 0)
            currentBrickDimensions[theMaxDim]++; //Make the dim we are dividing even

        currentBrickDimensions[theMaxDim] /= 2;
    }

    // adapt brick size according to maximum texture dimension
    unsigned int maxGPUTextureDim = static_cast<unsigned int>(getMaxTexSize());

    while (currentBrickDimensions.x>maxGPUTextureDim || currentBrickDimensions.y>maxGPUTextureDim
           || currentBrickDimensions.z>maxGPUTextureDim) {
        int theMaxDim = (currentBrickDimensions.x > currentBrickDimensions.y ? (currentBrickDimensions.x > currentBrickDimensions.z ? 0 : 2) :
                         (currentBrickDimensions.y > currentBrickDimensions.z ? 1 : 2));

        if (currentBrickDimensions[theMaxDim] % 2 != 0)
            currentBrickDimensions[theMaxDim]++; //Make the dim we are dividing even

        currentBrickDimensions[theMaxDim] /= 2;
    }

    return currentBrickDimensions;
}

int OpenGLCapabilities::getOpenGLVersion(){
    return glVersion_;
}

bool OpenGLCapabilities::hasSupportedOpenGLVersion(){
    return (glVersion_ >= 320);
}

bool OpenGLCapabilities::hasOpenGLVersion(){
    return (glVersion_ > 0);
}

void OpenGLCapabilities::initializeGLEW() {
    if (!hasSupportedOpenGLVersion()) {
        std::string preferProfile = getPreferredProfile();
        if (preferProfile == "core") glewExperimental = GL_TRUE;
        GLenum glewError = glewInit();
        if (GLEW_OK != glewError) {
            LogErrorCustom("OpenGLInfo", glewGetErrorString(glewError));
        }
        else{
            const GLubyte* glversion = glGetString(GL_VERSION);
            glVersionStr_ = std::string(
                (glversion != nullptr ? reinterpret_cast<const char*>(glversion) : "INVALID"));
            glVersion_ = parseAndRetrieveVersion(glVersionStr_);
        }
        LGL_ERROR_SUPPRESS;
        glewInitialized_ = true;

        if(!hasSupportedOpenGLVersion())
            InviwoApplication::getPtr()->addNonSupportedTags(Tags::GL);
    }
}

bool OpenGLCapabilities::isExtensionSupported(const char* name) {
    return (glewIsExtensionSupported(name) != '0');
}

bool OpenGLCapabilities::isSupported(const char* name) {
    return (glewIsSupported(name) != '0');
}

bool OpenGLCapabilities::isTexturesSupported() {
    return texSupported_;
}

bool OpenGLCapabilities::isTextureArraysSupported() {
    return texArraySupported_;
}

bool OpenGLCapabilities::is3DTexturesSupported() {
    return tex3DSupported_;
}

bool OpenGLCapabilities::isFboSupported() {
    return fboSupported_;
}

bool OpenGLCapabilities::isShadersSupported() {
    return shadersAreSupported_;
}

bool OpenGLCapabilities::isShadersSupportedARB() {
    return shadersAreSupportedARB_;
}

bool OpenGLCapabilities::isGeometryShadersSupported() {
    return geometryShsadersAreSupported_;
}

OpenGLCapabilities::GLSLShaderVersion OpenGLCapabilities::getCurrentShaderVersion() {
    if(supportedShaderVersions_.size() > currentGlobalGLSLVersionIdx_)
        return supportedShaderVersions_[currentGlobalGLSLVersionIdx_];
    else
        return 0;
}

std::string OpenGLCapabilities::getCurrentGlobalGLSLHeader() {
    if (currentGlobalGLSLHeader_ == "")
        rebuildGLSLHeader();

    return currentGlobalGLSLHeader_;
}

std::string OpenGLCapabilities::getCurrentGlobalGLSLVertexDefines() {
    if (currentGlobalGLSLVertexDefines_ == "")
        rebuildGLSLVertexDefines();

    return currentGlobalGLSLVertexDefines_;
}

std::string OpenGLCapabilities::getCurrentGlobalGLSLFragmentDefines() {
    if (currentGlobalGLSLFragmentDefines_ == "")
        rebuildGLSLFragmentDefines();

    return currentGlobalGLSLFragmentDefines_;
}

glm::u64 OpenGLCapabilities::getCurrentAvailableTextureMem() {
    glm::u64 currentAvailableTexMeminBytes = 0;

    if(!OpenGLCapabilities::hasOpenGLVersion())
        return currentAvailableTexMeminBytes;

    try {
        GLint nCurAvailMemoryInKB[4] = {0};

        if (glVendor_ == VENDOR_NVIDIA) {
#ifdef GL_NVX_gpu_memory_info
            glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, nCurAvailMemoryInKB);
#endif
        }
        else if (glVendor_ == VENDOR_AMD) {
#ifdef GL_ATI_meminfo
            glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, nCurAvailMemoryInKB);
#endif
        }

        currentAvailableTexMeminBytes = KILOBYTES_TO_BYTES(static_cast<glm::u64>(nCurAvailMemoryInKB[0]));
    }
    catch (const Exception& e) {
        LogWarn("Failed to fetch current available texture memory: " << e.what());
    }

    return currentAvailableTexMeminBytes;
}

glm::u64 OpenGLCapabilities::getTotalAvailableTextureMem() {
    glm::u64 totalAvailableTexMemInBytes = 0;

    try {
        if (glVendor_ == VENDOR_NVIDIA) {
#ifdef GL_NVX_gpu_memory_info
            GLint nTotalAvailMemoryInKB[4] = {0};
            glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, nTotalAvailMemoryInKB);
            totalAvailableTexMemInBytes = KILOBYTES_TO_BYTES(static_cast<glm::u64>(nTotalAvailMemoryInKB[0]));
#endif
        }
        else if (glVendor_ == VENDOR_AMD) {
#if defined(WGL_AMD_gpu_association)
            UINT n = wglGetGPUIDsAMD(0, 0);
            UINT *ids = new UINT[n];
            size_t total_mem_mb = 0;
            wglGetGPUIDsAMD(n, ids);
            wglGetGPUInfoAMD(ids[0],
                WGL_GPU_RAM_AMD,
                GL_UNSIGNED_INT,
                sizeof(size_t),
                &total_mem_mb);
            totalAvailableTexMemInBytes = MEGABYTES_TO_BYTES(static_cast<glm::u64>(total_mem_mb));
#elif defined(GLX_AMD_gpu_association)
            UINT n = glXGetGPUIDsAMD(0, 0);
            UINT *ids = new UINT[n];
            size_t total_mem_mb = 0;
            glXGetGPUIDsAMD(n, ids);
            glXGetGPUInfoAMD(ids[0],
                GLX_GPU_RAM_AMD,
                GL_UNSIGNED_INT,
                sizeof(size_t),
                &total_mem_mb);
            totalAvailableTexMemInBytes = MEGABYTES_TO_BYTES(static_cast<glm::u64>(total_mem_mb));
#endif
        }
    }
    catch (const Exception& e) {
        LogWarn("Failed to fetch total available texture memory: " << e.what());
    }

    return totalAvailableTexMemInBytes;
}

int OpenGLCapabilities::getMaxProgramLoopCount() {
    return maxProgramLoopCount_;
}

int OpenGLCapabilities::getNumTexUnits() {
    return numTexUnits_;
}

int OpenGLCapabilities::getMaxTexSize() {
    return maxTexSize_;
}

int OpenGLCapabilities::getMax3DTexSize() {
    return max3DTexSize_;
}

int OpenGLCapabilities::getMaxArrayTexSize() {
    return maxArrayTexSize_;
}

int OpenGLCapabilities::getMaxArrayVertexAttribs() {
    return maxArrayVertexAttribs_;
}

int OpenGLCapabilities::getMaxColorAttachments() {
    return maxColorAttachments_;
}

std::string OpenGLCapabilities::getPreferredProfile(){
    return preferredProfile_;
}

bool OpenGLCapabilities::setPreferredProfile(std::string profile, bool showMessage){
    preferredProfile_ = profile;

    size_t i = 0;
    while (i<supportedShaderVersions_.size() && (supportedShaderVersions_[i].hasProfile()
        && supportedShaderVersions_[i].getProfile() != preferredProfile_))
        i++;

    bool changed = false;
    if(i != currentGlobalGLSLVersionIdx_){
        currentGlobalGLSLVersionIdx_ = i;
        changed = true;
    }

    if(changed || showMessage)
        LogInfoCustom("OpenGLInfo","Current set global GLSL version: " << getCurrentShaderVersion().getVersionAndProfileAsString());

    return changed;
}

void OpenGLCapabilities::retrieveStaticInfo() {
    NO_GL_THEN_RETURN

    const GLubyte* vendor = glGetString(GL_VENDOR);
    glVendorStr_ =
        std::string((vendor != nullptr ? reinterpret_cast<const char*>(vendor) : "INVALID"));

    if (glVendorStr_.find("NVIDIA") != std::string::npos)
        glVendor_ = VENDOR_NVIDIA;
    else if (glVendorStr_.find("AMD") != std::string::npos || glVendorStr_.find("ATI") != std::string::npos)
        glVendor_ = VENDOR_AMD;
    else if (glVendorStr_.find("INTEL") != std::string::npos || glVendorStr_.find("Intel") != std::string::npos)
        glVendor_ = VENDOR_INTEL;
    else
        glVendor_ = VENDOR_UNKNOWN;

    const GLubyte* glrender = glGetString(GL_RENDERER);
    glRenderStr_ =
        std::string((glrender != nullptr ? reinterpret_cast<const char*>(glrender) : "INVALID"));
    //GLSL
    shadersAreSupported_ = (glVersion_ >= 200);
    shadersAreSupportedARB_ = isExtensionSupported("GL_EXT_ARB_fragment_program");
    geometryShsadersAreSupported_ = isExtensionSupported("GL_EXT_ARB_geometry_shader4");

    GLint numberOfSupportedVersions = 0;
    const GLubyte* glslStrByte = nullptr;
#ifdef GL_VERSION_4_3
    if(glVersion_ >= 430){
        glslStrByte = glGetString(GL_SHADING_LANGUAGE_VERSION);
        glslVersionStr_ = std::string(
            (glslStrByte != nullptr ? reinterpret_cast<const char*>(glslStrByte) : "000"));
        glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &numberOfSupportedVersions);
        int glslVersion = parseAndRetrieveVersion(glslVersionStr_);

        for (int i=0; i<numberOfSupportedVersions; i++) {
            parseAndAddShaderVersion(toString<const GLubyte*>(glGetStringi(GL_SHADING_LANGUAGE_VERSION, i)), glslVersion);
        }

		std::sort(supportedShaderVersions_.begin(), supportedShaderVersions_.end(), &GLSLShaderVersion::sortHighestFirst);
    }
#endif

    if (numberOfSupportedVersions == 0) {
        if (isShadersSupported())
            glslStrByte = glGetString(GL_SHADING_LANGUAGE_VERSION);
        else if (isShadersSupportedARB())
            glslStrByte = glGetString(GL_SHADING_LANGUAGE_VERSION_ARB);

        glslVersionStr_ = std::string(
            (glslStrByte != nullptr ? reinterpret_cast<const char*>(glslStrByte) : "000"));
        int glslVersion = parseAndRetrieveVersion(glslVersionStr_);

        if (glslVersion != 0) {
#ifdef GL_VERSION_4_4
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(440, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(440, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_4_3
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(430, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(430, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_4_2
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(420, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(420, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_4_1
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(410, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(410, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_4_0
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(400, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(400, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_3_3
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(330, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(330, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_3_2
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(150, "core"), glslVersion);
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(150, "compatibility"), glslVersion);
#endif
#ifdef GL_VERSION_3_1
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(140), glslVersion);
#endif
#ifdef GL_VERSION_3_0
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(130), glslVersion);
#endif
#ifdef GL_VERSION_2_1
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(120), glslVersion);
#endif
#ifdef GL_VERSION_2_0
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(110), glslVersion);
#endif
        }
    }

    //Set current used GLSL version to highest(i.e. 1st in vector) with preferred profile (or no profile)
    if (isShadersSupported() || isShadersSupportedARB()) {
        size_t i = 0;

        while (i<supportedShaderVersions_.size() && (supportedShaderVersions_[i].hasProfile()
                && supportedShaderVersions_[i].getProfile() != preferredProfile_))
            i++;

        currentGlobalGLSLVersionIdx_ = i;
    }

    maxProgramLoopCount_ = -1;

    if (GLEW_NV_fragment_program2) {
        GLint i = -1;
        glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOOP_COUNT_NV, &i);

        if (i > 0) {
            //Restrict cycles to realistic samplingRate*maximumDimension, 20*(10 000) slices = 200 000
            maxProgramLoopCount_ = std::min<int>(static_cast<int>(i), 200000);
        }
    }

    if (isGeometryShadersSupported()){
        glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES, static_cast<GLint*>(&geometryShadersMaxVertices_));
        glGetIntegerv(GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS, static_cast<GLint*>(&geometryShadersMaxOutputComponents_));
        glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_COMPONENTS, static_cast<GLint*>(&geometryShadersMaxTotalOutputComponents_));
    }

    //Texturing
#ifdef GL_VERSION_1_1
    texSupported_ = true;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&maxTexSize_);
#else
    texSupported_ = isExtensionSupported("GL_EXT_texture");
    maxTexSize_ = 0;
#endif
#ifdef GL_VERSION_1_2
    tex3DSupported_ = true;
    glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, (GLint*)&max3DTexSize_);
#else
    tex3DSupported_ = isExtensionSupported("GL_EXT_texture3D");

    if (is3DTexturesSupported())
        glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, (GLint*)&max3DTexSize_);
    else
        max3DTexSize_ = 0;

#endif
#ifdef GL_VERSION_2_0
     glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, (GLint*)&maxArrayVertexAttribs_);
#endif
#ifdef GL_VERSION_3_0
    if(glVersion_ >= 300){
        texArraySupported_ = true;
        glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, (GLint*)&maxArrayTexSize_);
    }
    else{
#endif
        texArraySupported_ = isExtensionSupported("GL_EXT_texture_array");

        if (isTextureArraysSupported())
            glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, (GLint*)&maxArrayTexSize_);
        else
            maxArrayTexSize_ = 0;
#ifdef GL_VERSION_3_0
    }
#endif
    numTexUnits_ = -1;

    if (isShadersSupported())
        glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&numTexUnits_);

    if (getNumTexUnits() < 0)
        glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&numTexUnits_);

    if(numTexUnits_<0)
        numTexUnits_ = 0;

    TextureUnit::initialize(numTexUnits_);
    //FBO
    fboSupported_ = isExtensionSupported("GL_EXT_framebuffer_object");
    maxColorAttachments_ = 0;

    if (isFboSupported())
        glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments_);
}

void OpenGLCapabilities::retrieveDynamicInfo() {
}

void OpenGLCapabilities::rebuildGLSLHeader() {
    currentGlobalGLSLHeader_ = "#version " + supportedShaderVersions_[currentGlobalGLSLVersionIdx_].getVersionAndProfileAsString() + "\n";

    if (supportedShaderVersions_[currentGlobalGLSLVersionIdx_].getVersion() == 140 && preferredProfile_ == "compatibility")
        currentGlobalGLSLHeader_ += "#extension GL_ARB_compatibility : enable\n";

    if (supportedShaderVersions_[currentGlobalGLSLVersionIdx_].hasProfile()) {
        currentGlobalGLSLHeader_ += "#define GLSL_PROFILE_" + toUpper(supportedShaderVersions_[currentGlobalGLSLVersionIdx_].getProfile()) + "\n";
    }

    if (supportedShaderVersions_[currentGlobalGLSLVersionIdx_].getVersion() < 150){
        currentGlobalGLSLHeader_ += "#define texture(t, s) texture2D(t, s)\n";
        currentGlobalGLSLHeader_ += "#define texture(t, s) texture3D(t, s)\n";
    }

    int lastVersion = -1;

    for (size_t i=currentGlobalGLSLVersionIdx_; i<supportedShaderVersions_.size(); i++) {
        if (lastVersion != supportedShaderVersions_[i].getVersion()) {
            currentGlobalGLSLHeader_ += "#define GLSL_VERSION_" + supportedShaderVersions_[i].getVersionAsString() + "\n";
            lastVersion = supportedShaderVersions_[i].getVersion();
        }
    }

    if (getMaxProgramLoopCount() > 0) {
        currentGlobalGLSLHeader_ += "#define MAX_PROGRAM_LOOP_COUNT " + toString(getMaxProgramLoopCount()) + "\n";
    }
}

void OpenGLCapabilities::rebuildGLSLVertexDefines() {
    currentGlobalGLSLVertexDefines_ = "";

    // layout locations for GLSL >= 3.30 are handled now via glBindAttributeLocation
    currentGlobalGLSLVertexDefines_ += "in vec4 in_Vertex;\n";
    currentGlobalGLSLVertexDefines_ += "in vec3 in_Normal;\n";
    currentGlobalGLSLVertexDefines_ += "in vec4 in_Color;\n";
    currentGlobalGLSLVertexDefines_ += "in vec3 in_TexCoord;\n";
}

void OpenGLCapabilities::rebuildGLSLFragmentDefines() {
    currentGlobalGLSLFragmentDefines_ = "";
    // layout locations for GLSL >= 3.30 are now handled via glFragDataLocation
    if (supportedShaderVersions_[currentGlobalGLSLVersionIdx_].getVersion() >= 130) {
        currentGlobalGLSLFragmentDefines_ += "layout(location = 0) out vec4 FragData0;\n";
        currentGlobalGLSLFragmentDefines_ += "layout(location = 1) out vec4 PickingData;\n";
    }
    else {
        currentGlobalGLSLFragmentDefines_ += "#define FragData0 gl_FragColor\n";
        currentGlobalGLSLFragmentDefines_ += "#define PickingData gl_FragData[" + toString(getMaxColorAttachments()-1) + "]\n";
    }
}

void OpenGLCapabilities::addShaderVersion(GLSLShaderVersion version) {
    supportedShaderVersions_.push_back(version);
}

void OpenGLCapabilities::addShaderVersionIfEqualOrLower(GLSLShaderVersion version, int compVersion) {
    if (version.getVersion() <= compVersion)
        addShaderVersion(version);
}

void OpenGLCapabilities::parseAndAddShaderVersion(std::string versionStr, int compVersion) {
    //Assumes <version><space><profile> or <version>, example 420 core or 140
    if (!versionStr.empty()) {
		//Remove all non-alphanumeric characters, but keep spaces
		versionStr.erase(std::remove_if(versionStr.begin(), versionStr.end(),
			[](char c) { return !(std::isspace(c) || std::isalnum(c)); }),
			versionStr.end());
        std::vector<std::string> versionSplit = splitString(versionStr);

		if (versionSplit.size() > 1 && (versionSplit[1].compare("core") == 0 || versionSplit[1].compare("compatibility") == 0))
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(stringTo<int>(versionSplit[0]), versionSplit[1]), compVersion);
        else
            addShaderVersionIfEqualOrLower(GLSLShaderVersion(stringTo<int>(versionSplit[0])), compVersion);
    }
}

int OpenGLCapabilities::parseAndRetrieveVersion(std::string versionStr) {
    // Assumes format <version><space><desc> example "4.1 ATI-1.20.11"
    // Version to int mapping, 4.1 => 410, 4.40 => 440
    if (!versionStr.empty()) {
        std::vector<std::string> versionSplit = splitString(versionStr, ' ');
        std::vector<std::string> numberSplit = splitString(versionSplit[0], '.');
        int factor = 1;
        if (numberSplit.size() > 1) {
            if(numberSplit[1].size() == 1) {
                factor = 10;
            }
            return stringTo<int>(numberSplit[0])*100 + stringTo<int>(numberSplit[1]) * factor;
        }
    }

    return 0;
}

} // namespace

redpajama_set_name: RedPajamaGithub


I wouldn't have called this a latke ((in Jewish cooking) a pancake, especially one made with grated potato) if yiddish hadn't become so hip all of a sudden. But it seems like this year everybody knew so much about jewish cooking that we jews should start calling it by what it is. Yiddish food usually consists of cheap and filling ingredients, like potatoes, and is usually nobody's favourite. I come from two totally different traditions: lebanese and yiddish. And not to be disrespectful to either of them, but lebanese cooking is always better. No matter what you do with it or how basic- it's always better. Don't get me wrong, yiddish food can be filling and more… colourful? But not even my Zeide (yiddish word for grandpa) would disagree with me. But they do fry stuff! So they have something going for them. Anyways, this amazing brunch/breakfast is a fusion of both worlds, and yet not as caloric as either of them. It is a simple sweet potato latke covered with labneh (Strained yogurt) and avocado slices, sprinkled with za'atar, and topped with a perfectly fried egg.
Peel and grate sweet potato. Place on a bowl with ice water for 5 minutes. Drain and pat dry with paper towels. Return them to the bowl and mix with one egg, salt and pepper. If they are too thick, grind them in a food processor (but you can skip this if they're finely grated). Add mozzarella cheese and miz well. Heat a frying pan with olive oil, and when almost smoking, drop four squeezed balls of sweet potato. Let them brown on one side without moving for about 4-5 minutes, then turn them carefully and wait until golden brown. Take them out, divide them in two plates, add a dollop of labneh in each, sprinkle with za'atar, two slices of avocado, and a fried egg on top. You can eat them by destroying everything and making a very delicious homogeneous mixture, like Aslan does, or eat it like more civilised common people. But either way, enjoy!
Para todos ustedes que conocen la cocina yiddish, las latkes (tortitas fritas de papa) son uno de los poco platillos realmente deliciosos. Aparte de la sopa de matze-ball y un par de platillos más, la comida yiddish tiene poco a su favor. En especial si la comparas con su mayor contrincante (en mi familia la menos), la comida árabe. Creciendo bajo el techo de una madre yiddish (de ascendencia judeo-polaca) y un padre de familia siria, queda más que claro que ni siquiera mi mamá se dignó a tratarnos de acercar al difícil placer de la comida de sus ancestros. Combinando mis tres culturas, me inspiré en lo pesado de los desayunos mexicanos para crear un platillo con latkes de camote cubiertas en jocoque y aguacate, espolvoreadas con za'atar, y terminadas un huevo estrellado encima para no quitarle proteina necesaria para el día.
Se pela y ralla el camote. Se pone a remojar por 5 minutos en un bowl con agua helada. Se cuela y seca con toallas de papel, y se regresa al bowl en dónde se sazona con sal y pimienta y se le agrega un huevo. Se mezcla (si está rallada demasiado gruesa, se muele unos segundos en un procesador). Se combina con queso mozzarella y se pone a calentar un sartén con aceite de oliva. Cuando esté casi humeando, se van haciendo bolitas con el camote, exprimiendo el exceso de líquido. Se ponen a dorar 4-5 minutos sin mover, luego se voltean y se dejan dorar del segundo lado. Se dividen en dos platos, se cubren con una cucharada de jocoque, dos rebanadas de aguacate, un poco de za'atar, y un huevo estrellado encima.


Although autonomous driving is a incredible concept the safety aspects are concerning, before they can be bight by the mass market.
In the interest of facilitating a robust conversation, I want to offer seven of the most pressing concerns. Effective decision making, as Peter Drucker observed, depends on the dialogue between different points of view and a choice between different judgments.
The following differing points of view and judgments cover a wide range of potential issues, including technical viability, operational resiliency, and even fears that driverless cars might work too well and thus unleash a host of unwanted secondary effects.
Please feel free to reiterate, refute or add to the items on this list.
The technology is not robust enough. Even if theoretical solutions are found, it might be hard to reliably translate them to the real world. Robustness would depend on a myriad of electronic, mechanical and software components operating with little tolerance for error under adverse (freezing, wet, boiling) conditions, long duty cycles, less than perfect maintenance (car owners being human), fender benders, network and electrical outages, and so on. Dr. Louise Cummings, for example, made a well-reasoned argument along these lines during a recent U.S. Senate committee hearing.
They will cost too much. The cost of sophisticated electronics, including lidar, radar, sensors, cameras, computing and networking devices, on top of the cost of additional development, maintenance, and liability, will price driverless cars out of reach of most consumers.


text:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string input = Console.ReadLine();

        Dictionary<string,Trainer> trainerss = new Dictionary<string, Trainer>();
        while (input != "Tournament")
        {
            string[] splited = input.Split(new[] {'\n', '\t', ' '}, StringSplitOptions.RemoveEmptyEntries).ToArray();
            if (!trainerss.ContainsKey(splited[0]))
            {
                Trainer trainer = new Trainer();
                trainer.name = splited[0];
                trainerss.Add(splited[0], trainer);
            }

            Pokemon pokemon = new Pokemon();
            pokemon.name = splited[1];
            pokemon.element = splited[2];
            pokemon.health = double.Parse(splited[3]);
            trainerss[splited[0]].pokemons.Add(pokemon);

            input = Console.ReadLine();
        }

        input = Console.ReadLine();

        while (input != "End")
        {
            foreach (var trainer in trainerss)
            {
                bool hasElement = false;
                foreach (var pokemon in trainer.Value.pokemons)
                {
                    if (pokemon.element.Equals(input))
                    {
                        trainer.Value.badges += 1;
                        hasElement = true;
                        break;
                    }
                }
                if (!hasElement)
                {
                    foreach (var pokemon in trainer.Value.pokemons)
                    {
                        pokemon.health -= 10;
                        if (pokemon.health <= 0)
                        {
                            pokemon.element = "ForRemove";
                        }
                    }
                }
            }
            input = Console.ReadLine();
        }
        foreach (var trainer in trainerss.OrderByDescending(x => x.Value.badges))
        {
            Console.WriteLine($"{trainer.Value.name} {trainer.Value.badges} {trainer.Value.pokemons.Count(x => x.element != "ForRemove")}");
        }
    }
}


Employment and immigration opportunities await qualified candidates.
Remember that you have to have proof of your qualifications when you participate in these sessions. If you need help in putting your profile together or have questions on how you can take advantage of this opportunity, feel free to contact us.
Not sure if you have experience in the qualified occupations? Check out the description of these occupations below. If it matches what you've been doing for 3 years, they're looking for you.
Agricultural service contractors provide agricultural services such as livestock and poultry breeding, soil preparation, crop planting, crop spraying, cultivating or harvesting. Farm supervisors supervise the work of general farm workers and harvesting labourers. Specialized livestock workers carry out feeding, health and breeding programs on dairy, beef, sheep, poultry, hog and other livestock farms.
Industrial butchers slaughter livestock using stunning devices and knives; skin, clean and trim carcasses; remove viscera and other inedible parts from carcasses; split carcasses into smaller portions to facilitate handling; and may slaughter cattle, calves and sheep as prescribed by religious laws. Industrial butchers cut beef, lamb, pork or veal carcasses or sides or quarters of carcasses into primal cuts for further cutting, processing or packaging; remove bones from meat; and cut meat and poultry into specific cuts for institutional, commercial or other wholesale use. Trimmers remove skin, excess fat, bruises or other blemishes from carcasses or meat portions.
Graphic designers Consult with clients to establish the overall look, graphic elements and content of communications materials in order to meet their needs. They determine the medium best suited to produce the desired visual effect and the most appropriate vehicle for communication. Graphic Designers Prepare sketches, layouts and graphic elements of the subjects to be rendered using traditional tools, multimedia software and image processing, layout and design software.
Printing press operators review job orders to determine job specifications such as production time, colour sequence and quantities required, and advise press crew of these specifications. They mount plates or cylinders and make necessary adjustments, Fill ink fountains and take measurements, make adjustments and determine settings to control colour and viscosity. Operators set up press and check samples for ink coverage, alignment and registration, Monitor regular press runs for quality and consistency using computer control console and make adjustments as required while removing and cleaning plates and cylinders at end of press run.
Plastics processing machine operators set up and operate plastic mixing, calendering, extruding and moulding processing machines used in the manufacture of plastic parts and plastic products. They Weigh resins, colorants and other chemicals according to formula. They Set up and operate calender machines which transform dough-consistent plastic mass into continuous sheets or films of specified thickness. They are responsible for setting up and operating one or more extruding machines which extrude plastic composites products through a nozzle or die.
Bindery Production Support assist in Transporting raw materials, finished products and equipment throughout plant manually or using powered equipment. They check and weigh materials and products, sort, pack, crate and package materials and products while assisting machine operators, assemblers and other workers. They are required to Clean work areas and equipment and perform other labouring and elemental activities.
Welders perform some or all of the following duties including reading and interpret blueprints or welding process specifications, operating manual or semi-automatic welding equipment to fuse metal segments using processes such as gas tungsten arc welding (GTAW), gas metal arc welding (GMAW), flux-cored arc welding (FCAW), plasma arc welding (PAW), shielded metal arc welding (SMAW), oxy-acetylene welding (OAW), resistance welding and submerged arc welding (SAW). They also operate manual or semi-automatic flame-cutting equipment, brazing and soldering equipment and metal shaping machines. Welders may specialize in certain types of welding such as custom fabrication or machinery and equipment repair welding.
This is a great initiative by the province of Manitoba and an excellent opportunity for those who have been dreaming of coming to Canada. Make sure you grab your chance right away!
Remember to share this to your family and friends!


I have worked with Jeremy at more than a dozen events, and can say that he is consistently resourceful. He will bring whatever gadget is necessary to make your production look and sound professional. Jeremy is very concerned with making your show run smoothly. Most of the time, no one notices the elaborate workings of the lights, sound system, or projector. He stresses over them so you don't have to.


text:
What Is Vascular Disease Preventing Vascular Disease Vascular Diseases
Orbit Study Continuum Study
Why Help
We invite you. Join us in our endeavor to be the leader in the application of new technology and advances in vascular biotechnology, pharmaceuticals, and medical devices.
The Houston Center for Vascular Health (HCVH)
The Houston Center for Vascular Health (HCVH) is a nonprofit foundation dedicated to the treatment of vascular disease, prevention of amputations, sharing knowledge of arterial and venous diseases, and training physicians in the most current and innovative technologies to save limbs in patients with critical arterial and/or venous disease. Peripheral Vascular Disease (PVD) effects between 8 and 10 million people in the United States. In the Houston area, 160,000 to 200,000 individuals suffer from the complications of PVD. The disease is primarily caused by atherosclerosis and is associated with many risk factors including diabetes, obesity, smoking, elevated cholesterol, and genetic factors. When circulatory blockages threaten the viability of a person's limbs or extremities, complex interventions may be the only option available to patients with extensive PVD. A common result of undiagnosed PVD is the reduction of blood flow to the body's extremities, especially the lower legs and feet. More than 200,000 amputations are done each year in the U.S., and most of them involve people who are diabetic or have kidney disease. The loss of a limb has very profound physical, emotional and financial impacts on the patient, his or her family, and society in general.
Oscar Rosales, MD
Formerly The President of Medical Staff at Memorial Hermann TMC and Currently the Medical Director of the Cardiac Catheterization Lab at Memorial Hermann TMC
Dr. Oscar Rosales is a board-certified interventional cardiologist formerly the President of Medical Staff for Memorial Hermann Hospital in Houston, Texas. He completed his medical training at Tulane University, New Orleans, Louisiana; Yale University, New Haven, CT and University of Texas Medical School, Houston, Texas. Dr. Rosales is also the Medical Director of the Memorial Hermann Hospital Cath Lab. He founded the Houston Center for Vascular Health, a non-profit foundation devoted to the dissemination of knowledge about PVD, training of physicians and the investigation of new treatment modalities for PVD.
About the Program Coordinators
Victoria Hawkins, DrPH, RN
Senior Research Nurse
University of Texas Clinical Research Unit
Victoria.Hawkins@uth.tmc.edu
Contact the Program Coordinator
Houston Center for Vascular Health
6400 Fannin St. Suite #3000
Mary H. Pierce, RN, BSN, MBA
Mary.H.Pierce@uth.tmc.edu
Rosales: It's time to raise awareness of peripheral arterial disease - Friday, March 28, 2014
Houston Chronicle March 21, 2014
[View News Archive]
Site by Global Graffiti Inc.
Copyright © 2021 Houston Center for Vascular Health. All rights reserved.

redpajama_set_name: RedPajamaCommonCrawl


text:
Public health is biased, and you should be glad
Posted on April 23, 2018 by Dr. Trevor Hancock
From time to time, those who work in public health are accused of being biased – and it's true. In spite of the urgings of some – usually from the corporate or neo-liberal world – that pubic health be neutral, that is not their job. They are and should be biased in favour of health, and biased against anything that harms health – be it government policies, corporate practices or individual behaviours. For that, we should be glad.
That is not to say that public health assessments of potential health hazards are biased – they are not. Public health begins with an objective assessment of the evidence as to possible harm to health from whatever it is that is of concern. If the conclusion is that it is not a health hazard, then no action is taken.
But if there is an assessment that something is harmful, public health is duty-bound to do something about it, based on an assessment of the severity of the problem. Is this a minor problem, something that only affects a small number of people and has only short-lived and non-life-threatening effects? Or is it a major problem, one that affects many people and has potentially serious, even life-threatening consequences? Most often, it is somewhere in between.
The challenge, of course, is that often there is incomplete or insufficient evidence to come to a definitive answer. But that is understood and indeed an approach to dealing with uncertainty is even written into law. For example, BC's Public Health Act states "A health officer may issue an order . . . only if the health officer reasonably believes thata health hazard exists", and there are numerous other places in the Act where it is clear the reasonable belief of a health officer is sufficient reason to take action.
Ontario's Health Protection and Promotion Act is even broader, stating in numerous places, regarding numerous situations, that "A medical officer of health or a public health inspector may [take some form of action] where he or she is of the opinion, upon reasonable and probable grounds", that there is a health hazard of some sort and that action is needed to reduce or eliminate it.
Note that public health officers are expected to form an opinion, and that there does not have to be definitive proof, just "reasonable belief" or "reasonable and probable grounds" to act to protect the health of the public.
This is, in effect, a codification of the precautionary principle, which was defined as follows in the 1992 Rio Declaration of the Earth Summit: "Where there are threats of serious or irreversible damage, lack of full scientific certainty shall not be used as a reason for postponing cost-effective measures to prevent environmental degradation".
This principle is in a number of international treaties to which Canada is a signatory, and is one of the guiding principles in the 1999 Canadian Environmental Protection Act, which the government has the duty to administer – although how well it is implemented is debatable.
I can think of very few cases in a 40-year career in public health where the hazard to health turns out to be less than expected; it almost always is worse. Which is why public health must be biased in favour of protecting the health of the public, and be guided by the precautionary principle.
Almost inevitably, this brings public health into conflict with powerful forces, be they private corporations interested in making money, or governments implementing their policies – or, more often, declining to take action in the face of a threat, especially if that threat comes from a powerful corporation that is a supporter, funder or ideological partner.
That is why both these powerful forces want public health to be neutral; just stick to the facts, don't have opinions, don't act until you have definitive proof, don't speak out. The problem is that only too often, definitive proof comes a bit late, in the shape of dead, sick or injured citizens.
So as citizens we should be glad of and support strong and independent health officers, acting in the public interest, biased towards health, and applying the precautionary principle. We must not let governments weaken our protectors and thus our health.
← It's in national, global interest to stop Kinder Morgan pipeline
We need to shed a couple of planet's worth of footprint →


text:
Amber Goldhammer
Mixed Media, Acrylic, Latex, Spray Paint, Ink on Canvas
Artspace Warehouse (Los Angeles)
Los Angeles artist Amber Goldhammer paints dramatic abstract compositions in acrylic on canvas featuring energetic brushstrokes. Goldhammer uses her contemporary paintings to express emotions akin to silent poetry while drawing inspiration for her palette from the layered world around her. Her artworks include unique textures and beautiful details along the surfaces.
This colorful and unique graffiti inspired painting is 30 inches square. The sides are painted light grey and it does not require framing, it is wired and ready to hang. This painting is signed and titled by the artist on the back. Convenient local Los Angeles area shipping. Affordable U.S. and global shipping are also available. A certificate of authenticity issued by the art gallery is included.
Amber Goldhammer is best known for creating vibrant abstract paintings with a street art edge. She originally started painting with pigments, powders, and waxes and went on to experimenting with different mediums and processes to keep evolving her artworks. As love and joy are paramount emotions in life, Goldhammer hopes her series incorporating the "I Love You" message expands to reach a wide audience. Connecting people through public art is one way she believes her street murals can impact lives, as it is impossible to view her work and not feel a sense of joy and love.
Painting a convergence of color and emotion, she builds and layers bold colors organically, allowing the process to determine the outcome. There is no analyzing, conceptualizing, or judging that takes place. It all happens in the moment, as a union between her, the canvas, and the paint. Amber Goldhammer frequently draws inspiration for her palette from the colors of the ocean, saying, "I get to take in the essence of the ocean every day, which fuels my creativity and brings me peace."
A worldwide collected young artist with ongoing concurrent exhibitions in galleries throughout the United States and Switzerland, Goldhammer's artworks have also been exhibited at major international art fairs. Her original paintings have been showcased in print and online publications, and on such TV series as "Million Dollar Listing," "Being Mary Jane," "The Catch" as well as both multi-Emmy® nominated series, "Crazy Ex- Girlfriend", and "Scandal." Goldhammer's art is also featured on the Netflix's original series, "G.L.O.W." by "Weeds" creator, Jenji Kohan.
$125.00	Shipping within Continental US arrives in 5-8 business days
Artspace Warehouse Delivery within Los Angeles (1-3 days): $50
Amber Goldhammer is best known for creating vibrant abstract paintings with a street art edge. She originally started painting with pigments, powders, and waxes and went on to experimenting with mixed mediums and processes to keep evolving her artworks. As love and joy are paramount emotions in life, Amber hopes her series incorporating the "I Love You" message expands to reach a wide audience. Connecting people through public art is one way she believes her street murals can impact lives, as it is impossible to view her work and not feel a sense of joy and love.
Building upon layers of bold colors and sweeping gestural movements, her newest work includes positive messages of love and hope, written in a graffiti-style script. The new mixed-media series is a testament to Goldhammer's own emotive interpretation of the ebb and flow of her life's experiences. She frequently draws inspiration for her palette from the colors of the Southern California ocean, saying, "I get to take in the essence of the ocean every day, which fuels my creativity and brings me peace."
Rainbow Love Affair
Spring Vacation
Way of the Wind
Positive Interception
In The Golden Hour Of Love
Sean Keith
Bold Batch
Jonas Fisch


Tata Safari Storme price in Ahmedabad starts from ₹ 11.3 Lakh (Onroad Price Ahmedabad). Tata offers Tata Safari Storme in 4 different variants. Out of these Tata Safari Storme versions, 4 are powered by Diesel. Tata Safari Storme Lx Refreshed is the base version, which comes with a price tag of ₹ 11.3 Lakh. On the other hand, Tata Safari Storme VX Refreshed 4x4 (400 NM) is the top-end version that costs you ₹ 16.86 Lakh. Know Tata Safari Storme on-road price in Ahmedabad at CarAndBike. For Tata Safari Storme offers in Ahmedabad, please contact your closest Tata dealership.


text:
Friends of Animals (FoA) is a non-profit international animal advocacy organization, established in New York City in 1957, working to free animals around the world from cruelty and institutionalized exploitation. The organization's headquarters is in Darien, Connecticut, with an additional office in Colorado.

Founding
The organization was founded by Alice Herrington in 1957, to protect cats and dogs. "To that end it offered low-cost spaying and neutering services to cut down the number of strays across the country. The organization eventually built its own clinic for this in Neptune, N.J." The organization states that it has assisted in more than 2.5 million spay/neuter procedures.

The organization soon widened its activities to preserve animals in general, including wildlife, marine mammals and zoo animals. Ms. Herrington led the organization until retiring in 1986. The current president is Priscilla Feral.

Fighting animal testing
In 1981, the organization lobbied with United Action for Animals for the introduction in Congress of the Research Modernization Act. This bill sought to develop alternatives to animal testing in research, along with the development of a National Center for Alternatives Research. The bill was ultimately defeated. Animal law professor Gary Francione expressed the view that the bill was opposed by almost all institutional users of animals, because they believed it would require a diversion of funds from animal experiments.

Primarily Primates
In 2006, the organization came to the defense of operators of Primarily Primates, a sanctuary near San Antonio, Texas, that housed "hundreds of chimpanzees, monkeys and other animals that had outlived their usefulness as research subjects, movie props or pets." After People for the Ethical Treatment of Animals made unsubstantiated, false allegations to the Texas Attorney General that were later dismissed, control of the sanctuary was temporarily put into the control of a receiver by way of an emergency injunction. Friends of Animals paid the legal bills of Primarily Primates, who were trying to get control back of their sanctuary. The Texas Attorney General asked Priscilla Feral, Friends of Animals' president to establish a new board of directors, and on May 1, 2007, returned the sanctuary to Feral who serves as PPI's voluntary president of the board. Friends of Animals manages the sanctuary as a project with a $1.1 million budget in 2018, a staff of 16 and one full-time veterinarian to assure the highest standards and animal care possible. The sanctuary houses 347 primates, birds and other animals including three rescued wild horses.

Wildlife Law Program
In 2013, the organization established a Wildlife Law Program, focusing on the defense of wildlife and their habitats throughout the world. FoA's Wildlife Law Program works at putting an end to animals being treated as property within the legal system, and along with winning 12 legal challenges to protect wild horses from government roundups, has secured Endangered Species Act protections for birds and other animals.

In August 2014, the Wildlife Law Program challenged federal agencies at John F. Kennedy International Airport in New York for killing protected Snowy Owls and other migratory birds. The lawsuit argues that the agencies did not disclose the scope and impacts of the bird-reduction program or "discuss all reasonable alternatives to lethal" options, as they were required to do.

Even before the program was established, the organization worked through the legal system to protect the rights of animals. In 2005, many species of endangered African antelopes living on US ranches were listed as endangered as a result of a lawsuit by the organization. However, an exemption for captive breeding programs thwarted the move. In 2009, a further lawsuit resulted in a finding that the exemption was unlawful, restoring the protection against hunting the antelopes.

See also
List of animal rights groups

References

External links
 Official website

Animal welfare organizations based in the United States
Non-profit organizations based in Connecticut
Environmental organizations established in 1957
1957 establishments in New York City

redpajama_set_name: RedPajamaWikipedia


"We want everybody who works here to be able to answer your questions" said John Gibeau when asked about his farm philosophy and approach to the business. The Honeybee Centre, located on 176 Street in the busy area of Highway 15 and the Fraser Highway, is a favourite stop for many people looking for "one crop source" honey. There can be as many as 13 employees at this farm and if you are interested in the products and activities of the energetic and helpful honeybee, it's a good place to go.
The Gibeau's are a 13th generation farm family with roots back to Samuel de Champlain. "Our family has always had bees" said John, "but my father was a dairy farmer too. He was taught his bee skills by a Quebec monk". John's current farm is 10 acres in size and he started his commercial bee operation in 2000. "We really have three operations here" said John. "The pollination side of our business is pretty important. We bring in about 6000 bee colonies from Alberta to help with pollination for the blueberry farmers. Then we have our own honey retail sales". You might be surprised to know that another one-third of the Honeybee Centre's business is health related. "We do a lot of bee therapy" John explained. "A lot of people use bees to treat wounds, attack sore throats and generally to keep themselves healthy".
John takes extra care in his operation to make sure his bees make "one source" honey. And there are a lot of varieties to be had. This past year, squash honey was a good source. Normally honey is gathered over a four to five week bloom cycle. "We move our bees at night" John said. "That way they are all inside the hive and we make sure they are located where the crop we want nectar from is right handy when the bees start work in the morning".
"We are usually involved whenever the movie industry does something involving bees" John mentioned. "But it isn't a big part of what we do although certainly an interesting one. Basically my wife and I really like the idea of using our own food and we like using a natural product for healing and for vitamins. Bees have been helping people since medieval times" John stated.


Here at Hollywood Bowl, we are committed to providing the best service and experience for our customers. If you have any questions or comments, please don't hesitate to contact us. Simply fill out the form below and click submit; our dedicated customer care team are here to answer your queries.
If your enquiry relates to a booking, current pricing information, or party packages – please call the number for your local Hollywood Bowl, where a designated member of our Customer Contact Centre will be able to assist you.
Visit the 'Find Your Nearest Centre' page for more information. Calls cost 7 pence per minute, plus your companies access charge and network call charge. These charges vary by network.
Email our team on: customerservice@hollywoodbowl.co.uk.


text:
Q: Cannot find property of undefined I am getting error   Cannot read property 'data' of undefined in my angular 8 application when making a service call. If i put the if condition in the component code in my component
  I dont get error but if i put th if condition in the html logic i still get the error. What is the issue ?
UI
<div *ngIf="!hideEverything && !endOfAgreements && myData" class="agreementContainer">
  <ul class="agreementSectionList">
    <li *ngFor="let agreement of myData; let i=index;"
        class="agreementSection"
        [ngClass]="{
          'disabled': (i > activeBtn),
          'current': (i === activeBtn),
          'accepted': (i <= previousSection)
        }">
      <a> {{ agreement.code }}
        <ng-container *ngIf="i <= previousSection">
          <fa-icon [icon]="['fas', 'check-circle']" style="float: right;"></fa-icon>
        </ng-container>
        <ng-container *ngIf="i > previousSection">
          <fa-icon [icon]="['fas', 'window-close']" style="float: right;"></fa-icon>
        </ng-container>
      </a> <!-- (click)="termClicked(i)" -->
    </li>
  </ul>

Component
   ngOnInit() {
    this.getOutstandingAgreements(this.currentUser);
  }

  public getOutstandingAgreements(Id: number) {
    console.log(Id);
    this.agreementsService.getOutstandingAgreements(Id).subscribe((data: AgreementsModel[]) => {
         this.myData = data;
          // if (this.myData) {
         this.agreementData = this.myData[0].data;
         this.agreementLength = this.myData.length;

         this.calculateRemainingDaysLeft(0);
        }
        );
    }

A: In component declare myData variable like below
myData = [];

and in html check
<div *ngIf="!hideEverything && !endOfAgreements && myData.length > 0" class="agreementContainer">

redpajama_set_name: RedPajamaStackExchange


text:
'The Other Woman' is top movie download on iTunes
QMI Agency
Jul 30, 2014 • Last Updated July 30, 2014 • < 1 minute read
Cameron Diaz, Leslie Mann and model Kate Upton apparently make a good team for movie fans.
Their comedy "The Other Woman," about three women all cheated on by the same man, is the top movie download on iTunes this week.
Rounding out the top five are Darren Aronofsky's biblical epic "Noah" in second place, "Heaven Is For Real" in third, Johnny Depp's sci-fi box office flop "Transcendence" in fourth and Jonathan Glazer's "Under the Skin" at No. 5


text:
Juhász Pál (Debrecen, 1944. február 20.) közgazdász, agrárszociológus.

Szakmai, politikai tevékenysége

1962-65 között az ELTE Természettudományi Kar (ELTE TTK) matematika-filozófia szakára járt, majd 1965-től a Marx Károly Közgazdasági Egyetemre, ahol 1969-ben végzett elméleti-tervezési szakon. 1971-től az ELTE Bölcsészettudományi Kar (ELTE BTK) hároméves történelem kiegészítő szakát is elvégezte. 1969-től mint okleveles közgazdász és faluszociológus a Szövetkezeti Kutató Intézetben kapott állást, 1987-ig agrár- és faluszociológiai vizsgálatokat vezetett. 1988-tól két évig a Pénzügykutató Rt. tudományos főmunkatársa.

Az 1970-es években több tanulmányt írt az agrárgazdaság vállalatrendszere, az "első, második és harmadik gazdaság", illetve a falusi társadalom rétegződése témaköreiből.

A hatvanas évek derekán az ELTE-n megismerkedett az akkori filozófushallgatókkal – így Kis Jánossal, Zsille Zoltánnal, Ludassy Máriával - és velük marxológiai és szociológiai önképzőkört szervezett. 1968-ban, Csehszlovákia megszállása idején szembefordult az MSZMP-vel. Álnéven publikált a Beszélőben. Több száz előadást tartott falukutató táborokban, szamizdatot terjesztett. 1982-től dokumentumfilmeket készített a hagyományos parasztság pusztulásáról és az új keletű vállalkozók helyzetéről.

1987-ben a Magyar Közgazdasági Társaság gazdaságszociológiai osztályának elnökévé választották. 1988. májusban a Szabad Kezdeményezések Hálózatának vezetői közé került. 1988-tól a Szabad Demokraták Szövetségének az ügyvivője lett.

Az 1990-es választásokon az SZDSZ területi listájáról bekerült a parlamentbe. 1992-ben az Országgyűlés gazdasági állandó bizottságának a tagja volt. 1991-92 az SZDSZ Országos Tanácsa elnöke volt. 1994-ben újra területi listán került a Parlamentbe, számos bizottságban tevékenykedett.

Elismerései
 1990 – Eötvös József-emlékszobor az Antall-kormány belügyminiszterétől
 2004 – Magyar Köztársasági Érdemrend tiszti keresztje

Tudományos publikációi
Tudományos publikációi főleg az agrárgazdaság témakörében készültek.

Emberek és intézmények. Két zsákutca az agráriumban; bibliogr. Nagy Petra; ÚMK–Jelenkutató Alapítvány, Bp., 2006 (Terepmunkák)
"Történelemformáló ostobaság a magyar agrárkérdésben" címmel tanulmányt írt a Magyar Bálint által szerkesztett, 2013 őszén megjelent Magyar polip című kötetbe.
A Magyar polip 2. című kötetbe Politika és versenyképesség a magyar agrárgazdaságban címmel írt tanulmányt.

Jegyzetek

Források
 Önéletrajz az Országgyűlés honlapjáról

További információk
 A rendszerváltás utáni agrárátalakulást bíráló cikke a Magyar Narancsban (1998)

Magyar közgazdászok
1944-ben született személyek
Az SZDSZ korábbi tagjai
Országgyűlési képviselők (SZDSZ)
Országgyűlési képviselők (1990–1994)
Országgyűlési képviselők (1994–1998)
Élő személyek
A Charta '77 aláírói


text:
Abortion in Austria has been fully legalized since 1 January 1975. Elective abortions can be performed in hospitals for women during the first three months from the beginning of the pregnancy. Abortions can be performed later if there is a physical or mental health threat to the pregnant woman, if there is an incurable problem with the development of the fetus, or if the patient is under the age of 14.

There is no punishment for doctors who choose not to perform abortions based on personal or religious convictions, except if the life of the woman is at stake and a lack of abortion causes the woman's death. The 1975 law protects doctors who choose not to perform abortions. There are very few abortion clinics or hospitals with abortion capability outside major cities, making it next to impossible to have an abortion in rural areas. Abortions are not paid for by the government health system.

In 2000, the abortion rate was 1.4 abortions per 1000 women aged 15-44 years.

Abortion in Liechtenstein, which borders Austria, remains illegal. Some women who choose to terminate an unwanted pregnancy cross the border into Austria to undergo the procedure.

History
For more than a century, the Austrian abortion policy was largely governed by the 1852 legislation that criminalized abortion. Both the woman willingly attempting to end her pregnancy and the individual conducting the abortion faced up to five years in jail. However, there were a few legal exceptions. If the pregnant woman's life were in urgent danger or her bodily and mental health would be significantly harmed by prolonging the pregnancy, there was no penalty if the pregnancy was the result of rape and use of force. Only the medical practitioner was permitted to conduct the abortion in these rare situations.

The Austrian Social Democratic Party, a party with a long history of women's movement activity, led the charge to relax nineteenth-century abortion laws. Female social democratic MPs proposed legalizing abortion during the first trimester of pregnancy in 1920. Party officials brought forth a fresh proposal in 1924 to allow abortion for medical, social, or eugenic grounds and recommendations for more excellent sex education and the construction of information centers. The abortion issue received a whole paragraph in the 1926 party platform.

References

Austria
Healthcare in Austria
Austria
Women in Austria


How To Inflate A Basketball Without A Needle?
>> How To Inflate A Basketball Without A Needle?
For you to enjoy the hoops game, your ball must be inflated to the right amount air pressure.
Inflating a basketball requires you to have an air pump with a needle by your side. However, your pump might be out of reach when you need it most, or the needle might be damaged altogether.
Is there any other way you can inflate your basketball without using the needle?
In the post below, we'll discuss with some practical methods that you can employ to inflate your ball to the recommended amount of air pressure without the needle.
The easiest method of inflating your basketball without a needle involves using air from a balloon.
Get a bigger and stronger balloon- say a punch balloon- and blow it up as much as you can. Then use a paper clipper/clamp to seal its lip and prevent the air from escaping.
Now, you'll need a means of getting the air out of the balloon into your ball—you can use an extremely thin straw or coffee stirrer. Insert the straw/stirrer inside the ball and insert the other end into the inflation hole of your ball.
Release the paper clamp/clip to initiate the process of transferring air from the balloon into the ball (you can squeeze the ball to quicken the transfer process).
The next hack involves using an air compressor to blow up your basketball.
This is also a relatively easy process and involves using the compressed air inside the canister to inflate your basketball.
Like in our previous step, here you'll also need to find something that can fit in the small hole of the ball. Luckily, the can comes with a small straw that easily and smoothly gets into the basketball hole.
When using this trick, make sure you do inflate the ball in air bursts as the canister tends to chill up pretty quickly.
Also, note that this method will work better for a ball that's not entirely flat.
The ink tube of your pen can also act as a perfect solution for getting into the tiny basketball hole. It works if you have an air pump the needle is damaged/broken.
Remove the tube from your pen and drain any ink inside. Remove the writing point too. Make sure you keep the writing cap somewhere you can easily retrieve it as it'll help hold the makeshift needle when inserting it into the ball.
Using a pair of scissors, cut a small piece of the tube and insert it into the writing cap.
Next, you'll need a metal paper clip with plastic coating to make the ball tube. Take the metal paper clip, straighten it, and insert it into the ball air hole. Cut around the end sticking out and pull out the metal such that you mostly leave the plastic 'tube' inside the ball.
The idea now is to place the writing cap needle you've just made above into the plastic casing.
With someone to help you hold the fragile contraption together, you'll be able to fill up your ball easily and quickly.
The popular basketball brands, like Spalding, have come up with a new design of balls, which have air pumps integrated into them.
Using this feature doesn't need any needle, and it only involves pulling out the rubber top to reveal the pump and then pumping your ball until you ball achieves the level of firmness you want.
If you ever find yourself in a situation where you need to inflate your basketball but don't have the needle within reach, you can always use the hand tricks we've shared with you above to inflate your basketball correctly.
As you can see from the methods we've discussed, you'll just need to find something that will fit inside the small air hole of your basketball for easy inflation.
How To Palm A Basketball: 10 Drills To Get Better!
Basketball Fouls and Penalties: A Complete List With Videos!
Field Goal In Basketball: What Is It and Effective Percentage!


Start growing Marijuana in California. Thanks to California voters in Fall 2016, Proposition 64 was passed allowing citizens in this state that are 21 or older to grow marijuana for recreational use. That means you can grow up to 6 plants in your private house and have the right to carry 28.5 grams. I decided to make this video for others, like me, who wanted to learn about growing cannabis in your own home by showcasing an item that have been proven to work.
PS. I am not selling, nor endorsing the use of Marijuana in locations where it is not legal, nor advocating it's use by minors. Know the law, and live by it.
"EasyRyder" grow. Lowryder #2 x Ak-47 !


text:
Every time I look at the Eiffel Tower, it completely blows my mind - Brian Fallon (American political activist)
The Eiffel Tower, the most popular attraction in Paris turns 130 this year.
The Eiffel Tower has been a symbol of Paris, France, originally constructed as a temporary structure by Gustave Eiffel in 1889 for the 100th anniversary of the French Revolution and it's building was met with opposition stating the tower was a threat to the aesthetic nature of Paris. Viewed as magnificent and iconic this structure was once described as "ungainly" that would disfigure the city. The concerns proved to be unfounded, attracting more than 200 million visitors, even more during the 1900 Universal Exposition
and served many a purpose during the First World War for military communications and finally as a permanent radio antenna tower.
Every year approximately 7 million visitors climb the tower, easily recognized in pictures by most people. The Paris skyline wouldn't be the same without it and many countries have replicated the tower more or less identically to the original including China, Macau, Las Vegas, and Japan. Paris, Texas has a version with a cowboy hat.
Architecture Culture Design Icons