code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.vo; public class VTERiskAssessmentTCIVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public VTERiskAssessmentTCIVo() { } public VTERiskAssessmentTCIVo(ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean) { this.patient = bean.getPatient() == null ? null : bean.getPatient().buildVo(); this.patientsummaryrecord = bean.getPatientSummaryRecord() == null ? null : bean.getPatientSummaryRecord().buildVo(); this.tci = bean.getTCI() == null ? null : bean.getTCI().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean) { this.patient = bean.getPatient() == null ? null : bean.getPatient().buildVo(map); this.patientsummaryrecord = bean.getPatientSummaryRecord() == null ? null : bean.getPatientSummaryRecord().buildVo(map); this.tci = bean.getTCI() == null ? null : bean.getTCI().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean = null; if(map != null) bean = (ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public boolean getPatientIsNotNull() { return this.patient != null; } public ims.core.vo.PatientForVTERiskAssessmentVo getPatient() { return this.patient; } public void setPatient(ims.core.vo.PatientForVTERiskAssessmentVo value) { this.isValidated = false; this.patient = value; } public boolean getPatientSummaryRecordIsNotNull() { return this.patientsummaryrecord != null; } public ims.clinical.vo.PatientSummaryRecordForVteVo getPatientSummaryRecord() { return this.patientsummaryrecord; } public void setPatientSummaryRecord(ims.clinical.vo.PatientSummaryRecordForVteVo value) { this.isValidated = false; this.patientsummaryrecord = value; } public boolean getTCIIsNotNull() { return this.tci != null; } public ims.clinical.vo.TCIForVTEWorklistVo getTCI() { return this.tci; } public void setTCI(ims.clinical.vo.TCIForVTEWorklistVo value) { this.isValidated = false; this.tci = value; } public final String getIItemText() { return toString(); } public final Integer getBoId() { return null; } public final String getBoClassName() { return null; } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof VTERiskAssessmentTCIVo)) return false; VTERiskAssessmentTCIVo compareObj = (VTERiskAssessmentTCIVo)obj; if(this.getTCI() == null && compareObj.getTCI() != null) return false; if(this.getTCI() != null && compareObj.getTCI() == null) return false; if(this.getTCI() != null && compareObj.getTCI() != null) if(!this.getTCI().equals(compareObj.getTCI())) return false; if(this.getPatient() == null && compareObj.getPatient() != null) return false; if(this.getPatient() != null && compareObj.getPatient() == null) return false; if(this.getPatient() != null && compareObj.getPatient() != null) if(!this.getPatient().equals(compareObj.getPatient())) return false; if(this.getPatientSummaryRecord() == null && compareObj.getPatientSummaryRecord() != null) return false; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() == null) return false; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() != null) return this.getPatientSummaryRecord().equals(compareObj.getPatientSummaryRecord()); return super.equals(obj); } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; VTERiskAssessmentTCIVo clone = new VTERiskAssessmentTCIVo(); if(this.patient == null) clone.patient = null; else clone.patient = (ims.core.vo.PatientForVTERiskAssessmentVo)this.patient.clone(); if(this.patientsummaryrecord == null) clone.patientsummaryrecord = null; else clone.patientsummaryrecord = (ims.clinical.vo.PatientSummaryRecordForVteVo)this.patientsummaryrecord.clone(); if(this.tci == null) clone.tci = null; else clone.tci = (ims.clinical.vo.TCIForVTEWorklistVo)this.tci.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(VTERiskAssessmentTCIVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A VTERiskAssessmentTCIVo object cannot be compared an Object of type " + obj.getClass().getName()); } VTERiskAssessmentTCIVo compareObj = (VTERiskAssessmentTCIVo)obj; int retVal = 0; if (retVal == 0) { if(this.getTCI() == null && compareObj.getTCI() != null) return -1; if(this.getTCI() != null && compareObj.getTCI() == null) return 1; if(this.getTCI() != null && compareObj.getTCI() != null) retVal = this.getTCI().compareTo(compareObj.getTCI()); } if (retVal == 0) { if(this.getPatient() == null && compareObj.getPatient() != null) return -1; if(this.getPatient() != null && compareObj.getPatient() == null) return 1; if(this.getPatient() != null && compareObj.getPatient() != null) retVal = this.getPatient().compareTo(compareObj.getPatient()); } if (retVal == 0) { if(this.getPatientSummaryRecord() == null && compareObj.getPatientSummaryRecord() != null) return -1; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() == null) return 1; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() != null) retVal = this.getPatientSummaryRecord().compareTo(compareObj.getPatientSummaryRecord()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patient != null) count++; if(this.patientsummaryrecord != null) count++; if(this.tci != null) count++; return count; } public int countValueObjectFields() { return 3; } protected ims.core.vo.PatientForVTERiskAssessmentVo patient; protected ims.clinical.vo.PatientSummaryRecordForVteVo patientsummaryrecord; protected ims.clinical.vo.TCIForVTEWorklistVo tci; private boolean isValidated = false; private boolean isBusy = false; }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/clinical/vo/VTERiskAssessmentTCIVo.java
Java
agpl-3.0
10,084
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {bool, func, number, shape, string} from 'prop-types' import {FormFieldGroup} from '@instructure/ui-form-field' import SubmissionTrayRadioInput from './SubmissionTrayRadioInput' import {statusesTitleMap} from '../constants/statuses' import I18n from 'i18n!gradebook' function checkedValue(submission) { if (submission.excused) { return 'excused' } else if (submission.missing) { return 'missing' } else if (submission.late) { return 'late' } return 'none' } export default class SubmissionTrayRadioInputGroup extends React.Component { state = {pendingUpdateData: null} componentWillReceiveProps(nextProps) { if ( this.props.submissionUpdating && !nextProps.submissionUpdating && this.state.pendingUpdateData ) { this.props.updateSubmission(this.state.pendingUpdateData) this.setState({pendingUpdateData: null}) } } handleRadioInputChanged = ({target: {value}}) => { const alreadyChecked = checkedValue(this.props.submission) === value if (alreadyChecked && !this.props.submissionUpdating) { return } const data = value === 'excused' ? {excuse: true} : {latePolicyStatus: value} if (value === 'late') { data.secondsLateOverride = this.props.submission.secondsLate } if (this.props.submissionUpdating) { this.setState({pendingUpdateData: data}) } else { this.props.updateSubmission(data) } } render() { const radioOptions = ['none', 'late', 'missing', 'excused'].map(status => ( <SubmissionTrayRadioInput key={status} checked={checkedValue(this.props.submission) === status} color={this.props.colors[status]} disabled={this.props.disabled} latePolicy={this.props.latePolicy} locale={this.props.locale} onChange={this.handleRadioInputChanged} updateSubmission={this.props.updateSubmission} submission={this.props.submission} text={statusesTitleMap[status] || I18n.t('None')} value={status} /> )) return ( <FormFieldGroup description={I18n.t('Status')} disabled={this.props.disabled} layout="stacked" rowSpacing="none" > {radioOptions} </FormFieldGroup> ) } } SubmissionTrayRadioInputGroup.propTypes = { colors: shape({ late: string.isRequired, missing: string.isRequired, excused: string.isRequired }).isRequired, disabled: bool.isRequired, latePolicy: shape({ lateSubmissionInterval: string.isRequired }).isRequired, locale: string.isRequired, submission: shape({ excused: bool.isRequired, late: bool.isRequired, missing: bool.isRequired, secondsLate: number.isRequired }).isRequired, submissionUpdating: bool.isRequired, updateSubmission: func.isRequired }
djbender/canvas-lms
app/jsx/gradebook/default_gradebook/components/SubmissionTrayRadioInputGroup.js
JavaScript
agpl-3.0
3,563
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "stdpch.h" ///////////// // INCLUDE // ///////////// // misc #include "nel/misc/path.h" #include "nel/misc/vectord.h" #include "nel/misc/i18n.h" #include "nel/misc/progress_callback.h" // 3D Interface. #include "nel/3d/u_landscape.h" // Georges #include "nel/georges/u_form.h" #include "nel/georges/u_form_elm.h" #include "nel/georges/u_form_loader.h" // Client #include "continent_manager.h" #include "client_cfg.h" #include "sheet_manager.h" #include "sound_manager.h" #include "entities.h" // \todo Hld : a enlever lorsque unselect aura son bool bien pris en compte #include "init_main_loop.h" #include "weather.h" #include "weather_manager_client.h" #include "interface_v3/interface_manager.h" #include "interface_v3/group_map.h" // #include "input.h" #include "continent_manager_build.h" /////////// // USING // /////////// using namespace NLPACS; using namespace NLMISC; using namespace NL3D; using namespace std; using namespace NLGEORGES; //////////// // EXTERN // //////////// extern ULandscape *Landscape; extern UMoveContainer *PACS; extern UGlobalRetriever *GR; extern URetrieverBank *RB; extern class CIGCallback *IGCallbacks; extern NLLIGO::CLigoConfig LigoConfig; UMoveContainer *PACSHibernated = NULL; UGlobalRetriever *GRHibernated = NULL; URetrieverBank *RBHibernated = NULL; CIGCallback *IGCallbacksHibernated = NULL; //////////// // GLOBAL // //////////// // Hierarchical timer H_AUTO_DECL ( RZ_Client_Continent_Mngr_Update_Streamable ) ///////////// // METHODS // ///////////// //----------------------------------------------- // CContinentManager : // Constructor. //----------------------------------------------- CContinentManager::CContinentManager() { _Current = 0; _Hibernated = NULL; }// CContinentManager // void CContinentManager::reset() { // stop the background sound if (SoundMngr) SoundMngr->stopBackgroundSound(); // Unselect continent if (_Current) _Current->unselect(); // Shared data must be NULL now _Current = NULL; nlassert (GR == NULL); nlassert (RB == NULL); nlassert (PACS == NULL); nlassert (IGCallbacks == NULL); // Swap the hibernated data std::swap(GR, GRHibernated); std::swap(RB, RBHibernated); std::swap(PACS, PACSHibernated); std::swap(_Current, _Hibernated); std::swap(IGCallbacks, IGCallbacksHibernated); // Unselect continent if (_Current) _Current->unselect(); // remove villages removeVillages(); // NB: landscape zones are deleted in USCene::deleteLandscape() // clear continents DB for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { delete it->second; } _Continents.clear(); _Current = NULL; _Hibernated = NULL; } //----------------------------------------------- // load : // Load all continent. //----------------------------------------------- /* // Oldies now all these data are stored in the ryzom.world const uint32 NBCONTINENT = 8; SContInit vAllContinents[NBCONTINENT] = { { "fyros", "fyros", 15767, 20385, -27098, -23769 }, { "tryker", "tryker", 15285, 18638, -34485, -30641 }, { "matis", "lesfalaises", 235, 6316, -7920, -256 }, { "zorai", "lepaysmalade", 6805, 12225, -5680, -1235 }, { "bagne", "lebagne", 434, 1632, -11230, -9715 }, { "route", "laroutedesombres", 5415, 7400, -17000, -9575 }, { "sources", "sources", 2520, 3875, -11400, -9720 }, { "terres", "lesterres", 100, 3075, -15900, -13000 } }; */ // Read the ryzom.world which give the names and bboxes //----------------------------------------------- void CContinentManager::preloadSheets() { reset(); CEntitySheet *sheet = SheetMngr.get(CSheetId("ryzom.world")); if (!sheet || sheet->type() != CEntitySheet::WORLD) { nlerror("World sheet not found or bad type"); } uint32 i; CWorldSheet *ws = (CWorldSheet *) sheet; // Copy datas from the sheet for (i = 0; i < ws->ContLocs.size(); ++i) { const SContLoc &clTmp = ws->ContLocs[i]; std::string continentSheetName = NLMISC::strlwr(clTmp.ContinentName); if (continentSheetName.find(".continent") == std::string::npos) { continentSheetName += ".continent"; } // Get the continent form CSheetId continentId(continentSheetName); sheet = SheetMngr.get(continentId); if (sheet) { if (sheet->type() == CEntitySheet::CONTINENT) { CContinent *pCont = new CContinent; pCont->SheetName = continentSheetName; _Continents.insert(make_pair(clTmp.SelectionName, pCont)); } else { nlwarning("Bad type for continent form %s.", continentSheetName.c_str()); } } else { nlwarning("cant find continent sheet : %s.", continentSheetName.c_str()); } } } //----------------------------------------------- void CContinentManager::load () { // Continents are preloaded so setup them TContinents::iterator it = _Continents.begin(); while (it != _Continents.end()) { it->second->setup(); it++; } loadContinentLandMarks(); // \todo GUIGUI : Do it better when there will be "ecosystem"/Wind/etc. // Initialize the Landscape Vegetable. if(ClientCfg.MicroVeget) { if (Landscape) { // if configured, enable the vegetable and load the texture. Landscape->enableVegetable(true); // Default setup. TODO later by gameDev. Landscape->setVegetableWind(CVector(0.5, 0.5, 0).normed(), 0.5, 1, 0); // Default setup. should work well for night/day transition in 30 minutes. // Because all vegetables will be updated every 20 seconds => 90 steps. Landscape->setVegetableUpdateLightingFrequency(1/20.f); // Density (percentage to ratio) Landscape->setVegetableDensity(ClientCfg.MicroVegetDensity/100.f); } } }// load // //----------------------------------------------- // select : // Select continent from a name. // \param const string &name : name of the continent to select. //----------------------------------------------- void CContinentManager::select(const string &name, const CVectorD &pos, NLMISC::IProgressCallback &progress) { CNiceInputAuto niceInputs; // Find the continent. TContinents::iterator itCont = _Continents.find(name); if(itCont == _Continents.end()) { nlwarning("CContinentManager::select: Continent '%s' is Unknown. Cannot Select it.", name.c_str()); return; } // Dirt weather { H_AUTO(InitRZWorldSetLoadingContinent) // Set the loading continent setLoadingContinent (itCont->second); } // ** Update the weather manager for loading information // Update the weather manager { H_AUTO(InitRZWorldUpdateWeatherManager ) updateWeatherManager (itCont->second); } // startup season can be changed now the player is safe StartupSeason = RT.getRyzomSeason(); // Modify this season according to the continent reached. eg: newbieland continent force the winter to be autumn if(StartupSeason<EGSPD::CSeason::Invalid) StartupSeason= (*itCont).second->ForceDisplayedSeason[StartupSeason]; // Compute the current season according to StartupSeason, Server driver season, R2 Editor season or manual debug season CurrSeason = computeCurrSeason(); // Is it the same continent than the old one. { H_AUTO(InitRZWorldSelectCont) if(((*itCont).second != _Current) || ((*itCont).second->Season != CurrSeason)) { // New continent is not an indoor ? if (!(*itCont).second->Indoor && _Current) { // Unselect the current continent _Current->unselect(); // Shared data must be NULL now _Current = NULL; nlassert (GR == NULL); nlassert (RB == NULL); nlassert (PACS == NULL); nlassert (IGCallbacks == NULL); } else { // Remove the primitive for all entitites (new PACS coming soon and need new primitives). EntitiesMngr.removeCollision(); } // Swap the hibernated data std::swap(GR, GRHibernated); std::swap(RB, RBHibernated); std::swap(PACS, PACSHibernated); std::swap(_Current, _Hibernated); std::swap(IGCallbacks, IGCallbacksHibernated); // Is it the same continent than the old one. if(((*itCont).second != _Current) || ((*itCont).second->Season != CurrSeason)) { // Unselect the old continent. if(_Current) _Current->unselect(); _Current = (*itCont).second; // Teleport in a new continent, complete load _Current->select(pos, progress, true, false, CurrSeason); // New continent is not an indoor ? if (!_Current->Indoor) { // Stop the background sound if (SoundMngr) SoundMngr->stopBackgroundSound(); } } else { // Teleport in the hibernated continent _Current->select(pos, progress, false, true, CurrSeason); } } else { // Teleport in the same continent _Current->select(pos, progress, false, false, CurrSeason); } } { H_AUTO(InitRZWorldSound) // New continent is not an indoor ? if (!_Current->Indoor) { if(SoundMngr) SoundMngr->loadContinent(name, pos); } } // Map handling { H_AUTO(InitRZWorldMapHandling) CWorldSheet *pWS = dynamic_cast<CWorldSheet*>(SheetMngr.get(CSheetId("ryzom.world"))); for (uint32 i = 0; i < pWS->Maps.size(); ++i) if (pWS->Maps[i].ContinentName == name) { CInterfaceManager *pIM = CInterfaceManager::getInstance(); CGroupMap *pMap = dynamic_cast<CGroupMap*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:map:content:map_content:actual_map")); if (pMap != NULL) pMap->setMap(pWS->Maps[i].Name); pMap = dynamic_cast<CGroupMap*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:respawn_map:content:map_content:actual_map")); if (pMap != NULL) pMap->setMap(pWS->Maps[i].Name); break; } } }// select // //----------------------------------------------- // select : // Select closest continent from a vector. //----------------------------------------------- void CContinentManager::select(const CVectorD &pos, NLMISC::IProgressCallback &progress) { CVector2f fPos; fPos.x = (float)pos.x; fPos.y = (float)pos.y; TContinents::iterator it = _Continents.begin(); while (it != _Continents.end()) { CContinent *pCont = it->second; nlinfo("Looking into %s", pCont->SheetName.c_str()); if (pCont->Zone.VPoints.size() > 0) // Patch because some continent have not been done yet { if (pCont->Zone.contains(fPos)) { // load the continent selected. select (it->first, pos, progress); return; } else { /* nlwarning("**********************************************"); nlwarning("Start position (%s) not found in continent %s", NLMISC::toString(pos.asVector()).c_str(), it->first.c_str()); for(uint k = 0; k < pCont->Zone.VPoints.size(); ++k) { nlwarning("zone point %d = %s", (int)k, NLMISC::toString(pCont->Zone.VPoints[k]).c_str()); } */ } } it++; } nlwarning("cannot select any continent at pos (%f, %f)", fPos.x, fPos.y); /* ***************** PLEASE DO *****NOT***** PUT AN ASSERT HERE While this is a bug, it is a data bug. Crashing is not a good solution in this case. If you put an assert, it can happens this scenario for example: - A levelDesigner put a bad Teleporter which teleport to an invalid position - The player teleport, but its position is invalid => crash - the next time he logs, it crashes at start, AND HENCE CANNOT ASK A GM TO TELEPORT HIM AWAY Other scenarios can happens like Data change, Continent change => Player no more at valid position etc... HENCE MUST NOT CRASH, but display a "Lost In Space screen" leaving the player the possibility to ask HELP. ***************** */ //nlassertex(0, ("can't select any continent")); }// select // bool CContinentManager::isLoadingforced(const NLMISC::CVector &playerPos) const { if(_Current == 0) return false; return _Current->isLoadingforced(playerPos); } void CContinentManager::updateStreamable(const NLMISC::CVector &playerPos) { H_AUTO_USE ( RZ_Client_Continent_Mngr_Update_Streamable ) if(_Current) _Current->updateStreamable(playerPos); } void CContinentManager::forceUpdateStreamable(const NLMISC::CVector &playerPos, NLMISC::IProgressCallback &progress) { H_AUTO_USE ( RZ_Client_Continent_Mngr_Update_Streamable ) if (ClientCfg.VillagesEnabled) { if(_Current) _Current->forceUpdateStreamable(playerPos, progress); } } void CContinentManager::removeVillages() { for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { if (it->second) it->second->removeVillages(); } } void CContinentManager::getFogState(TFogType fogType, float dayNight, float duskRatio, CLightCycleManager::TLightState lightState, const NLMISC::CVectorD &pos, CFogState &result) { if(_Current) _Current->getFogState(fogType, dayNight, duskRatio, lightState, pos, result); } CContinent *CContinentManager::get(const std::string &contName) { TContinents::iterator it = _Continents.find(contName); if (it != _Continents.end()) return it->second; return NULL; } void CContinentManager::serialUserLandMarks(NLMISC::IStream &f) { f.serialVersion(1); if (!f.isReading()) { uint32 numCont = (uint32)_Continents.size(); f.serial(numCont); for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { std::string name = it->first; f.serial(name); if (it->second) { f.serialCont(it->second->UserLandMarks); } else { std::vector<CUserLandMark> dummy; f.serialCont(dummy); } } } else { uint32 numCont; f.serial(numCont); for(uint k = 0; k < numCont; ++k) { std::string contName; f.serial(contName); TContinents::iterator it = _Continents.find(contName); if (it != _Continents.end() && it->second) { f.serialCont(it->second->UserLandMarks); } else { std::vector<CUserLandMark> dummy; f.serialCont(dummy); } } // The number of stored landmarks is not checked at this time, but if we receive a // lower value in the server database, we will cut down using checkNumberOfUserLandmarks() } } //----------------------------------------------- // checkNumberOfLandmarks //----------------------------------------------- void CContinentManager::checkNumberOfUserLandmarks( uint maxNumber ) { for ( TContinents::iterator it=_Continents.begin(); it!=_Continents.end(); ++it ) { CContinent *cont = (*it).second; if ( cont->UserLandMarks.size() > maxNumber ) { // Just cut down the last landmarks (in case of hacked file) if ( cont == _Current ) { CGroupMap *pMap = dynamic_cast<CGroupMap*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:map:content:map_content:actual_map")); if ( pMap ) pMap->removeExceedingUserLandMarks( maxNumber ); } else { cont->UserLandMarks.resize( maxNumber ); } } } } //----------------------------------------------- // serialFOWMaps //----------------------------------------------- void CContinentManager::serialFOWMaps() { for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { CContinent *pCont = it->second; //nlinfo("Saving fow continent %s of name %s", it->first.c_str(), pCont->Name.c_str()); it->second->FoW.save(pCont->Name); } } const std::string &CContinentManager::getCurrentContinentSelectName() { TContinents::iterator it; for (it = _Continents.begin(); it != _Continents.end(); ++it) { if (it->second == _Current) return it->first; } static const string emptyString; return emptyString; } void CContinentManager::reloadWeather() { WeatherManager.release(); // reload the sheet std::vector<std::string> extensions; extensions.push_back("weather_setup"); extensions.push_back("weather_function_params"); extensions.push_back("continent"); extensions.push_back("light_cycle"); NLMISC::IProgressCallback pc; SheetMngr.loadAllSheet(pc, true, false, true, true, &extensions); WeatherManager.init(); // Load description of light cycles for each season. loadWorldLightCycle(); // Load global weather function parameters loadWeatherFunctionParams(); for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { NLMISC::CSheetId contSI(it->second->SheetName); CContinentSheet *cs = dynamic_cast<CContinentSheet *>(SheetMngr.get(contSI)); if (cs) { // update continent weather part for(uint l = 0; l < EGSPD::CSeason::Invalid; ++l) { it->second->WeatherFunction[l].buildFromSheet(cs->WeatherFunction[l], WeatherManager); } // update misc params it->second->FogStart = cs->Continent.FogStart; it->second->FogEnd = cs->Continent.FogEnd; it->second->RootFogStart = cs->Continent.RootFogStart; it->second->RootFogEnd = cs->Continent.RootFogEnd; it->second->LandscapeLightDay = cs->Continent.LandscapeLightDay; it->second->LandscapeLightDusk = cs->Continent.LandscapeLightDusk; it->second->LandscapeLightNight = cs->Continent.LandscapeLightNight; it->second->EntityLightDay = cs->Continent.EntityLightDay; it->second->EntityLightDusk = cs->Continent.EntityLightDusk; it->second->EntityLightNight = cs->Continent.EntityLightNight; it->second->RootLightDay = cs->Continent.RootLightDay; it->second->RootLightDusk = cs->Continent.RootLightDusk; it->second->RootLightNight = cs->Continent.RootLightNight; } } } void CContinentManager::reloadSky() { // reload new style sky std::vector<std::string> exts; CSheetManager sheetManager; exts.push_back("sky"); exts.push_back("continent"); NLMISC::IProgressCallback progress; sheetManager.loadAllSheet(progress, true, false, false, true, &exts); // const CSheetManager::TEntitySheetMap &sm = SheetMngr.getSheets(); for(CSheetManager::TEntitySheetMap::const_iterator it = sm.begin(); it != sm.end(); ++it) { if (it->second.EntitySheet) { CEntitySheet::TType type = it->second.EntitySheet->Type; if (type == CEntitySheet::CONTINENT) { // find matching sheet in new sheetManager const CEntitySheet *other = sheetManager.get(it->first); if (other) { const CContinentParameters &cp = static_cast<const CContinentSheet *>(other)->Continent; // find matching continent in manager for(TContinents::iterator it = _Continents.begin(); it != _Continents.end(); ++it) { if (it->second && nlstricmp(it->second->Name, cp.Name) == 0) { std::copy(cp.SkySheet, cp.SkySheet + EGSPD::CSeason::Invalid, it->second->SkySheet); break; } } } } else if(type == CEntitySheet::SKY) { // find matching sheet in new sheetManager const CEntitySheet *other = sheetManager.get(it->first); if (other) { // replace data in place ((CSkySheet &) *it->second.EntitySheet) = ((const CSkySheet &) *other); } } } } if (_Current) { _Current->releaseSky(); _Current->initSky(); } } // *************************************************************************** void CContinentManager::loadContinentLandMarks() { std::string dataPath = "../../client/data"; if (ClientCfg.UpdatePackedSheet == false) { readLMConts(dataPath); } else { buildLMConts("ryzom.world", "../../common/data_leveldesign/primitives", dataPath); readLMConts(dataPath); } } // *************************************************************************** void CContinentManager::readLMConts(const std::string &dataPath) { CIFile f; string sPackedFileName = CPath::lookup(LM_PACKED_FILE, false); if (sPackedFileName.empty()) sPackedFileName = CPath::standardizePath(dataPath) + LM_PACKED_FILE; if (f.open(sPackedFileName)) { uint32 nNbCont = 0; sint ver= f.serialVersion(1); f.serial(nNbCont); for (uint32 i = 0; i < nNbCont; ++i) { string sContName; f.serial(sContName); TContinents::iterator itCont = _Continents.find(sContName); if(itCont != _Continents.end()) { CContinent *pCont = itCont->second; f.serial(pCont->Zone); f.serial(pCont->ZoneCenter); f.serialCont(pCont->ContLandMarks); } else { CContinent dummy; f.serial(dummy.Zone); f.serial(dummy.ZoneCenter); f.serialCont(dummy.ContLandMarks); nlwarning("continent not found : %s", sContName.c_str()); } } f.serialCont(WorldMap); if (ver >= 1) f.serialCont(aliasToRegionMap); } else { nlwarning("cannot load " LM_PACKED_FILE); } } // *************************************************************************** string CContinentManager::getRegionNameByAlias(uint32 i) { return aliasToRegionMap[i]; }
KostasLifeboy/RyzomCore
ryzom/client/src/continent_manager.cpp
C++
agpl-3.0
21,153
using Elasticsearch.Net; using System; using System.Collections.Concurrent; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using static System.Net.DecompressionMethods; namespace Slamby.Common.SlambyConnection { internal class WebProxy : IWebProxy { private readonly Uri _uri; public WebProxy(Uri uri) { _uri = uri; } public ICredentials Credentials { get; set; } public Uri GetProxy(Uri destination) => _uri; public bool IsBypassed(Uri host) => host.IsLoopback; } public class SlambyHttpConnection : IConnection { private readonly object _lock = new object(); private readonly ConcurrentDictionary<int, HttpClient> _clients = new ConcurrentDictionary<int, HttpClient>(); private string DefaultContentType => "application/json"; public SlambyHttpConnection() { } private HttpClient GetClient(RequestData requestData) { var hashCode = requestData.GetHashCode(); HttpClient client; if (this._clients.TryGetValue(hashCode, out client)) return client; lock (_lock) { if (this._clients.TryGetValue(hashCode, out client)) return client; var handler = new HttpClientHandler { AutomaticDecompression = requestData.HttpCompression ? GZip | Deflate : None }; if (!string.IsNullOrEmpty(requestData.ProxyAddress)) { var uri = new Uri(requestData.ProxyAddress); var proxy = new WebProxy(uri); var credentials = new NetworkCredential(requestData.ProxyUsername, requestData.ProxyPassword); proxy.Credentials = credentials; handler.Proxy = proxy; } if (requestData.DisableAutomaticProxyDetection) handler.Proxy = null; client = new HttpClient(handler, false) { Timeout = requestData.RequestTimeout }; client.DefaultRequestHeaders.ExpectContinue = false; //TODO add headers //client.DefaultRequestHeaders = this._clients.TryAdd(hashCode, client); return client; } } public virtual ElasticsearchResponse<TReturn> Request<TReturn>(RequestData requestData) where TReturn : class { var client = this.GetClient(requestData); var builder = new ResponseBuilder<TReturn>(requestData); HttpRequestMessage requestMessage = null; try { requestMessage = CreateHttpRequestMessage(requestData); var response = client.SendAsync(requestMessage, requestData.CancellationToken).GetAwaiter().GetResult(); builder.StatusCode = (int)response.StatusCode; if (response.Content != null) builder.Stream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); } catch (HttpRequestException e) { builder.Exception = e; } finally { if (requestMessage != null && requestMessage.Content != null) { if (requestMessage.Content is SlambyStreamContent) ((SlambyStreamContent)requestMessage.Content).DisposeManually(true); if (requestMessage.Content is SlambyByteArrayContent) ((SlambyByteArrayContent)requestMessage.Content).DisposeManually(true); } } return builder.ToResponse(); } public virtual async Task<ElasticsearchResponse<TReturn>> RequestAsync<TReturn>(RequestData requestData) where TReturn : class { var client = this.GetClient(requestData); var builder = new ResponseBuilder<TReturn>(requestData); HttpRequestMessage requestMessage = null; try { requestMessage = CreateHttpRequestMessage(requestData); var response = await client.SendAsync(requestMessage, requestData.CancellationToken).ConfigureAwait(false); builder.StatusCode = (int)response.StatusCode; if (response.Content != null) builder.Stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); } catch (HttpRequestException e) { builder.Exception = e; } finally { if (requestMessage != null && requestMessage.Content != null) { if (requestMessage.Content is SlambyStreamContent) ((SlambyStreamContent)requestMessage.Content).DisposeManually(true); if (requestMessage.Content is SlambyByteArrayContent) ((SlambyByteArrayContent)requestMessage.Content).DisposeManually(true); } } return await builder.ToResponseAsync().ConfigureAwait(false); } private static HttpRequestMessage CreateHttpRequestMessage(RequestData requestData) { var method = ConvertHttpMethod(requestData.Method); var requestMessage = new HttpRequestMessage(method, requestData.Uri); foreach (string key in requestData.Headers) { requestMessage.Headers.TryAddWithoutValidation(key, requestData.Headers.GetValues(key)); } requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(requestData.ContentType)); string userInfo = null; if (!string.IsNullOrEmpty(requestData.Uri.UserInfo)) userInfo = Uri.UnescapeDataString(requestData.Uri.UserInfo); else if (requestData.BasicAuthorizationCredentials != null) userInfo = requestData.BasicAuthorizationCredentials.ToString(); if (!string.IsNullOrEmpty(userInfo)) { var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(userInfo)); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials); } var data = requestData.PostData; if (data != null) { var stream = requestData.MemoryStreamFactory.Create(); if (requestData.HttpCompression) { using (var zipStream = new GZipStream(stream, CompressionMode.Compress)) data.Write(zipStream, requestData.ConnectionSettings); requestMessage.Headers.Add("Content-Encoding", "gzip"); requestMessage.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); requestMessage.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); } else data.Write(stream, requestData.ConnectionSettings); stream.Position = 0; requestMessage.Content = new SlambyStreamContent(stream); } else { // Set content in order to set a Content-Type header. // Content gets diposed so can't be shared instance requestMessage.Content = new SlambyByteArrayContent(new byte[0]); } requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(requestData.ContentType); return requestMessage; } private static System.Net.Http.HttpMethod ConvertHttpMethod(Elasticsearch.Net.HttpMethod httpMethod) { switch (httpMethod) { case Elasticsearch.Net.HttpMethod.GET: return System.Net.Http.HttpMethod.Get; case Elasticsearch.Net.HttpMethod.POST: return System.Net.Http.HttpMethod.Post; case Elasticsearch.Net.HttpMethod.PUT: return System.Net.Http.HttpMethod.Put; case Elasticsearch.Net.HttpMethod.DELETE: return System.Net.Http.HttpMethod.Delete; case Elasticsearch.Net.HttpMethod.HEAD: return System.Net.Http.HttpMethod.Head; default: throw new ArgumentException("Invalid value for HttpMethod", nameof(httpMethod)); } } void IDisposable.Dispose() => this.DisposeManagedResources(); protected virtual void DisposeManagedResources() { foreach (var c in _clients) c.Value.Dispose(); } } }
slamby/slamby-api
src/Slamby.Common/SlambyConnection/SlambyHttpConnection.cs
C#
agpl-3.0
8,790
// -- // Copyright (C) 2001-2016 OTRS AG, http://otrs.com/ // -- // This software comes with ABSOLUTELY NO WARRANTY. For details, see // the enclosed file COPYING for license information (AGPL). If you // did not receive this file, see http://www.gnu.org/licenses/agpl.txt. // -- "use strict"; var Core = Core || {}; Core.UI = Core.UI || {}; /** * @namespace Core.UI.Datepicker * @memberof Core.UI * @author OTRS AG * @description * This namespace contains the datepicker functions. */ Core.UI.Datepicker = (function (TargetNS) { /** * @private * @name VacationDays * @memberof Core.UI.Datepicker * @member {Object} * @description * Vacation days, defined in SysConfig. */ var VacationDays, /** * @private * @name VacationDaysOneTime * @memberof Core.UI.Datepicker * @member {Object} * @description * One time vacations, defined in SysConfig. */ VacationDaysOneTime, /** * @private * @name LocalizationData * @memberof Core.UI.Datepicker * @member {Object} * @description * Translations. */ LocalizationData, /** * @private * @name DatepickerCount * @memberof Core.UI.Datepicker * @member {Number} * @description * Number of initialized datepicker. */ DatepickerCount = 0; if (!Core.Debug.CheckDependency('Core.UI.Datepicker', '$([]).datepicker', 'jQuery UI datepicker')) { return false; } /** * @private * @name CheckDate * @memberof Core.UI.Datepicker * @function * @returns {Array} First element is always true, second element contains the name of a CSS class, third element a description for the date. * @param {DateObject} DateObject - A JS date object to check. * @description * Check if date is on of the defined vacation days. */ function CheckDate(DateObject) { var DayDescription = '', DayClass = ''; // Get defined days from Config, if not done already if (typeof VacationDays === 'undefined') { VacationDays = Core.Config.Get('Datepicker.VacationDays').TimeVacationDays; } if (typeof VacationDaysOneTime === 'undefined') { VacationDaysOneTime = Core.Config.Get('Datepicker.VacationDays').TimeVacationDaysOneTime; } // Check if date is one of the vacation days if (typeof VacationDays[DateObject.getMonth() + 1] !== 'undefined' && typeof VacationDays[DateObject.getMonth() + 1][DateObject.getDate()] !== 'undefined') { DayDescription += VacationDays[DateObject.getMonth() + 1][DateObject.getDate()]; DayClass = 'Highlight '; } // Check if date is one of the one time vacation days if (typeof VacationDaysOneTime[DateObject.getFullYear()] !== 'undefined' && typeof VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1] !== 'undefined' && typeof VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1][DateObject.getDate()] !== 'undefined') { DayDescription += VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1][DateObject.getDate()]; DayClass = 'Highlight '; } if (DayClass.length) { return [true, DayClass, DayDescription]; } else { return [true, '']; } } /** * @name Init * @memberof Core.UI.Datepicker * @function * @returns {Boolean} false, if Parameter Element is not of the correct type. * @param {jQueryObject|Object} Element - The jQuery object of a text input field which should get a datepicker. * Or a hash with the Keys 'Year', 'Month' and 'Day' and as values the jQueryObjects of the select drop downs. * @description * This function initializes the datepicker on the defined elements. */ TargetNS.Init = function (Element) { var $DatepickerElement, HasDateSelectBoxes = false, Options, ErrorMessage; if (typeof Element.VacationDays === 'object') { Core.Config.Set('Datepicker.VacationDays', Element.VacationDays); } /** * @private * @name LeadingZero * @memberof Core.UI.Datepicker.Init * @function * @returns {String} A number with leading zero, if needed. * @param {Number} Number - A number to convert. * @description * Converts a one digit number to a string with leading zero. */ function LeadingZero(Number) { if (Number.toString().length === 1) { return '0' + Number; } else { return Number; } } if (typeof LocalizationData === 'undefined') { LocalizationData = Core.Config.Get('Datepicker.Localization'); if (typeof LocalizationData === 'undefined') { throw new Core.Exception.ApplicationError('Datepicker localization data could not be found!', 'InternalError'); } } // Increment number of initialized datepickers on this site DatepickerCount++; // Check, if datepicker is used with three input element or with three select boxes if (typeof Element === 'object' && typeof Element.Day !== 'undefined' && typeof Element.Month !== 'undefined' && typeof Element.Year !== 'undefined' && isJQueryObject(Element.Day, Element.Month, Element.Year) && // Sometimes it can happen that BuildDateSelection was called without placing the full date selection. // Ignore in this case. Element.Day.length ) { $DatepickerElement = $('<input>').attr('type', 'hidden').attr('id', 'Datepicker' + DatepickerCount); Element.Year.after($DatepickerElement); if (Element.Day.is('select') && Element.Month.is('select') && Element.Year.is('select')) { HasDateSelectBoxes = true; } } else { return false; } // Define options hash Options = { beforeShowDay: function (DateObject) { return CheckDate(DateObject); }, showOn: 'focus', prevText: LocalizationData.PrevText, nextText: LocalizationData.NextText, firstDay: Element.WeekDayStart, showMonthAfterYear: 0, monthNames: LocalizationData.MonthNames, monthNamesShort: LocalizationData.MonthNamesShort, dayNames: LocalizationData.DayNames, dayNamesShort: LocalizationData.DayNamesShort, dayNamesMin: LocalizationData.DayNamesMin, isRTL: LocalizationData.IsRTL }; Options.onSelect = function (DateText, Instance) { var Year = Instance.selectedYear, Month = Instance.selectedMonth + 1, Day = Instance.selectedDay; // Update the three select boxes if (HasDateSelectBoxes) { Element.Year.find('option[value=' + Year + ']').prop('selected', true); Element.Month.find('option[value=' + Month + ']').prop('selected', true); Element.Day.find('option[value=' + Day + ']').prop('selected', true); } else { Element.Year.val(Year); Element.Month.val(LeadingZero(Month)); Element.Day.val(LeadingZero(Day)); } }; Options.beforeShow = function (Input) { $(Input).val(''); return { defaultDate: new Date(Element.Year.val(), Element.Month.val() - 1, Element.Day.val()) }; }; $DatepickerElement.datepicker(Options); // Add some DOM notes to the datepicker, but only if it was not initialized previously. // Check if one additional DOM node is already present. if (!$('#' + Core.App.EscapeSelector(Element.Day.attr('id')) + 'DatepickerIcon').length) { // add datepicker icon and click event $DatepickerElement.after('<a href="#" class="DatepickerIcon" id="' + Element.Day.attr('id') + 'DatepickerIcon" title="' + LocalizationData.IconText + '"><i class="fa fa-calendar"></i></a>'); if (Element.DateInFuture) { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessageDateInFuture'); } else if (Element.DateNotInFuture) { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessageDateNotInFuture'); } else { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessage'); } // Add validation error messages for all dateselection elements Element.Year .after('<div id="' + Element.Day.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Month.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Year.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>'); // only insert time element error messages if time elements are present if (Element.Hour && Element.Hour.length) { Element.Hour .after('<div id="' + Element.Hour.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Minute.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>'); } } $('#' + Core.App.EscapeSelector(Element.Day.attr('id')) + 'DatepickerIcon').unbind('click.Datepicker').bind('click.Datepicker', function () { $DatepickerElement.datepicker('show'); return false; }); // do not show the datepicker container div. $('#ui-datepicker-div').hide(); }; return TargetNS; }(Core.UI.Datepicker || {}));
nilei/otrs
var/httpd/htdocs/js/Core.UI.Datepicker.js
JavaScript
agpl-3.0
10,316
<?php /* * ItemDelete.php * * Copyright 2012 edhelas <edhelas@edhelas-laptop> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ namespace Moxl\Xec\Action\Notification; use Moxl\Xec\Action; use Moxl\Stanza\Notification; class ItemDelete extends Action { private $_to; private $_id; public function request() { $this->store(); Notification::itemDelete($this->_to, $this->_id); } public function setTo($to) { $this->_to = $to; return $this; } public function setId($id) { $this->_id = $id; return $this; } public function handle($stanza, $parent = false) { $this->event('notificationdelete', $this->_id); } }
movim/moxl
src/Moxl/Xec/Action/Notification/ItemDelete.php
PHP
agpl-3.0
1,412
/* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.documents.dao; import com.concursive.commons.db.DatabaseUtils; import com.concursive.commons.text.StringUtils; import com.concursive.commons.web.mvc.beans.GenericBean; import java.sql.*; import java.util.ArrayList; /** * Can be used for creating document folders from a template * * @author Kailash Bhoopalam * @created August 12, 2008 */ public class DocumentFolderTemplate extends GenericBean { private int id = -1; private int projectCategoryId = -1; private String folderNames = ""; private boolean enabled = true; private Timestamp entered = null; public DocumentFolderTemplate() { } public DocumentFolderTemplate(ResultSet rs) throws SQLException { buildRecord(rs); } public DocumentFolderTemplate(Connection db, int id) throws SQLException { queryRecord(db, id); } public void queryRecord(Connection db, int templateId) throws SQLException { StringBuffer sql = new StringBuffer(); sql.append( "SELECT dft.* " + "FROM project_document_folder_template dft " + "WHERE template_id = ? "); PreparedStatement pst = db.prepareStatement(sql.toString()); int i = 0; pst.setInt(++i, templateId); ResultSet rs = pst.executeQuery(); if (rs.next()) { buildRecord(rs); } rs.close(); pst.close(); if (id == -1) { throw new SQLException("Template record not found."); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setId(String tmp) { this.id = Integer.parseInt(tmp); } public int getProjectCategoryId() { return projectCategoryId; } public void setProjectCategoryId(int projectCategoryId) { this.projectCategoryId = projectCategoryId; } public void setProjectCategoryId(String tmp) { this.projectCategoryId = Integer.parseInt(tmp); } /** * @return the folderNames */ public String getFolderNames() { return folderNames; } /** * @param folderNames the folderNames to set */ public void setFolderNames(String folderNames) { this.folderNames = folderNames; } public Timestamp getEntered() { return entered; } public void setEntered(Timestamp entered) { this.entered = entered; } public void setEntered(String tmp) { this.entered = DatabaseUtils.parseTimestamp(tmp); } public boolean getEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setEnabled(String enabled) { this.enabled = DatabaseUtils.parseBoolean(enabled); } private void buildRecord(ResultSet rs) throws SQLException { id = rs.getInt("template_id"); projectCategoryId = DatabaseUtils.getInt(rs, "project_category_id"); folderNames = rs.getString("folder_names"); enabled = rs.getBoolean("enabled"); entered = rs.getTimestamp("entered"); } public boolean isValid() { if (folderNames == null || folderNames.trim().equals("")) { errors.put("folderNamesError", "Required field"); } return !hasErrors(); } public ArrayList<String> getFolderNamesArrayList() { ArrayList<String> folderNames = new ArrayList<String>(); String[] tempNames = StringUtils.replaceReturns(this.getFolderNames(), "|").split("[|]"); for (String name : tempNames) { if (name != null && !"".equals(name.trim())) { folderNames.add(name); } } return folderNames; } public boolean insert(Connection db) throws SQLException { if (!isValid()) { return false; } boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } StringBuffer sql = new StringBuffer(); sql.append( "INSERT INTO project_document_folder_template " + "(" + (id > -1 ? "template_id, " : "") + "project_category_id, folder_names, "); if (entered != null) { sql.append("entered, "); } sql.append( "enabled) "); sql.append("VALUES (?, ?, "); if (id > -1) { sql.append("?, "); } if (entered != null) { sql.append("?, "); } sql.append("?) "); int i = 0; PreparedStatement pst = db.prepareStatement(sql.toString()); if (id > -1) { pst.setInt(++i, id); } DatabaseUtils.setInt(pst, ++i, projectCategoryId); pst.setString(++i, folderNames); if (entered != null) { pst.setTimestamp(++i, entered); } pst.setBoolean(++i, enabled); pst.execute(); pst.close(); id = DatabaseUtils.getCurrVal(db, "project_document_folder_template_template_id_seq", id); if (commit) { db.commit(); } } catch (SQLException e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } return true; } public int update(Connection db) throws SQLException { int resultCount = 0; boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } if (this.getId() == -1) { throw new SQLException("ID was not specified"); } if (!isValid()) { return -1; } int i = 0; PreparedStatement pst = db.prepareStatement( "UPDATE project_document_folder_template " + "SET project_category_id = ?, folder_names = ?, " + "enabled = ? " + "WHERE template_id = ? "); DatabaseUtils.setInt(pst, ++i, projectCategoryId); pst.setString(++i, folderNames); pst.setBoolean(++i, enabled); pst.setInt(++i, id); resultCount = pst.executeUpdate(); pst.close(); if (commit) { db.commit(); } } catch (SQLException e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } return resultCount; } public void delete(Connection db) throws SQLException { boolean autoCommit = db.getAutoCommit(); try { if (autoCommit) { db.setAutoCommit(false); } PreparedStatement pst = db.prepareStatement( "DELETE FROM project_document_folder_template " + "WHERE template_id = ? "); pst.setInt(1, id); pst.execute(); pst.close(); if (autoCommit) { db.commit(); } } catch (Exception e) { if (autoCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (autoCommit) { db.setAutoCommit(true); } } } }
Concursive/concourseconnect-community
src/main/java/com/concursive/connect/web/modules/documents/dao/DocumentFolderTemplate.java
Java
agpl-3.0
8,997
# frozen_string_literal: true require "spec_helper" describe "Admin imports assembly", type: :system do include_context "when admin administrating an assembly" before do switch_to_host(organization.host) login_as user, scope: :user visit decidim_admin_assemblies.assemblies_path end context "with context" do before "Imports the assembly with the basic fields" do click_link "Import", match: :first within ".import_assembly" do fill_in_i18n( :assembly_title, "#assembly-title-tabs", en: "Import assembly", es: "Importación de la asamblea", ca: "Importació de l'asamblea" ) fill_in :assembly_slug, with: "as-import" attach_file :assembly_document, Decidim::Dev.asset("assemblies.json") end click_button "Import" end it "imports the json document" do expect(page).to have_content("successfully") expect(page).to have_content("Import assembly") expect(page).to have_content("Not published") click_link "Import assembly" click_link "Categories" within ".table-list" do expect(page).to have_content(translated("Veritatis provident nobis reprehenderit tenetur.")) expect(page).to have_content(translated("Quidem aliquid reiciendis incidunt iste.")) end click_link "Components" expect(Decidim::Assembly.last.components.size).to eq(9) within ".table-list" do Decidim::Assembly.last.components.each do |component| expect(page).to have_content(translated(component.name)) end end click_link "Files" if Decidim::Assembly.last.attachments.any? within ".table-list" do Decidim::Assembly.last.attachments.each do |attachment| expect(page).to have_content(translated(attachment.title)) end end end end end end
AjuntamentdeBarcelona/decidim
decidim-assemblies/spec/system/admin/admin_imports_assembly_spec.rb
Ruby
agpl-3.0
1,926
function initializeDataTable(formId, tableId, storageKey, pageNumber, itemsPerPage, ajaxUrl, columnDefs, extra){ let domTable = $('#' + tableId); let options = { 'createdRow': function (row, data, dataIndex) { let url = ""; if (data['osis_url']) { url = data['osis_url']; } else { url = data['url']; } $(row).attr('data-id', url); $(row).attr('data-value', data['acronym']); }, columnDefs: columnDefs, "stateSave": true, "paging" : false, "ordering" : true, "orderMulti": false, "order": [[1, 'asc']], "serverSide": true, "ajax" : { "url": ajaxUrl, "accepts": { json: 'application/json' }, "type": "GET", "dataSrc": "object_list", "data": function (d){ let querystring = getDataAjaxTable(formId, domTable, d, pageNumber); querystring["paginator_size"] = itemsPerPage; return querystring; }, "traditional": true }, "info" : false, "searching" : false, 'processing': false, "language": { "oAria": { "sSortAscending": gettext("activate to sort column ascending"), "sSortDescending": gettext("activate to sort column descending") } } }; return domTable.DataTable($.extend(true, {}, options, extra)); } function outputAnchorOuterHtml(urlPath, textContent){ const anchor = document.createElement("a"); anchor.setAttribute("href", urlPath); anchor.textContent = textContent; return anchor.outerHTML; }
uclouvain/OSIS-Louvain
base/static/js/osis_datatable.js
JavaScript
agpl-3.0
1,779
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.forms.appointmenttrakingstatuscolorconfig; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); } }
open-health-hub/openmaxims-linux
openmaxims_workspace/Admin/src/ims/admin/forms/appointmenttrakingstatuscolorconfig/GlobalContext.java
Java
agpl-3.0
2,027
require 'rails_helper' RSpec.describe 'runs/forbidden' do it 'renders the forbidden template' do render expect(view).to render_template('runs/forbidden') end end
glacials/splits-io
spec/views/runs/forbidden_spec.rb
Ruby
agpl-3.0
176
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.person.creditsplit; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocumentForm; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentViewHelperServiceImpl; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.container.CollectionGroupBase; import org.kuali.rice.krad.uif.field.DataFieldBase; import org.kuali.rice.krad.uif.lifecycle.ViewLifecycleRestriction; import org.kuali.rice.krad.uif.util.*; import java.util.ArrayList; import java.util.List; public class CreditSplitCustomColumnsCollection extends CollectionGroupBase { private static final Logger LOG = Logger.getLogger(CreditSplitCustomColumnsCollection.class); private DataFieldBase columnFieldPrototype; private BindingInfo columnBindingInfo; private Class<?> columnObjectClass; private String columnLabelPropertyName; @Override public void performInitialization(Object model) { ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) model; ((ProposalDevelopmentViewHelperServiceImpl) pdForm.getViewHelperService()).setInvestigatorCreditTypes(pdForm); if (CollectionUtils.isNotEmpty(((ProposalDevelopmentDocumentForm) model).getDevelopmentProposal().getInvestigators())) { List<Object> columnCollection = ObjectPropertyUtils.getPropertyValue(model, getColumnBindingInfo().getBindingPath()); List<Component> columns = new ArrayList<Component>(); for (Component component : this.getItems()) { if (component.isRender() || component.isHidden()) { columns.add(component); } } int index = 0; for (Object column : columnCollection) { DataFieldBase columnField = ComponentUtils.copy(columnFieldPrototype); String columnLabel = StringUtils.isEmpty(columnLabelPropertyName)?"description":columnLabelPropertyName; try { columnField.getFieldLabel().setLabelText(PropertyUtils.getNestedProperty(column,columnLabel).toString()); columnField.getBindingInfo().setBindingName("creditSplits[" + index + "].credit"); columnField.setPropertyName("creditSplits.credit"); columnField.setOrder(100 + index); columns.add(columnField); } catch (Exception e) { LOG.error("Could not retrieve column label from column collection item",e); } index++; } this.setItems(columns); } super.performInitialization(model); } @ViewLifecycleRestriction public DataFieldBase getColumnFieldPrototype() { return columnFieldPrototype; } public void setColumnFieldPrototype(DataFieldBase columnFieldPrototype) { this.columnFieldPrototype = columnFieldPrototype; } public BindingInfo getColumnBindingInfo() { return columnBindingInfo; } public void setColumnBindingInfo(BindingInfo columnBindingInfo) { this.columnBindingInfo = columnBindingInfo; } public Class<?> getColumnObjectClass() { return columnObjectClass; } public void setColumnObjectClass(Class<?> columnObjectClass) { this.columnObjectClass = columnObjectClass; } public String getColumnLabelPropertyName() { return columnLabelPropertyName; } public void setColumnLabelPropertyName(String columnLabelPropertyName) { this.columnLabelPropertyName = columnLabelPropertyName; } }
iu-uits-es/kc
coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/person/creditsplit/CreditSplitCustomColumnsCollection.java
Java
agpl-3.0
4,678
# -*- coding: UTF-8 -*- import logging unicode_string = u"Татьяна" utf8_string = "'Татьяна' is an invalid string value" logging.warning(unicode_string) logging.warning(utf8_string) try: raise Exception(utf8_string) except Exception,e: print "--- (Log a traceback of the exception):" logging.exception(e) print "--- Everything okay until here, but now we run into trouble:" logging.warning(u"1 Deferred %s : %s",unicode_string,e) logging.warning(u"2 Deferred %s : %s",unicode_string,utf8_string) print "--- some workarounds:" logging.warning(u"3 Deferred %s : %s",unicode_string,utf8_string.decode('UTF-8')) from django.utils.encoding import force_unicode logging.warning(u"4 Deferred %s : %s",unicode_string,force_unicode(utf8_string))
lsaffre/blog
docs/blog/2011/0527.py
Python
agpl-3.0
806
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.web.pdc.control; import java.util.ArrayList; import java.util.List; import org.silverpeas.core.pdc.form.displayers.PdcFieldDisplayer; import org.silverpeas.core.pdc.pdc.model.ClassifyPosition; import org.silverpeas.core.pdc.pdc.model.ClassifyValue; import org.silverpeas.core.pdc.pdc.model.UsedAxis; /** * Manages the positions of a PDC field. * @author ahedin */ public class PdcFieldPositionsManager { // If true, indicates that the controller which refers to this manager is in PDC field mode. private boolean enabled; // Positions of the field. private ArrayList<ClassifyPosition> positions; // Available axis to order the object (publication) containing the field. private ArrayList<UsedAxis> usedAxisList; // Field name. private String fieldName; // PDC field displayer. private PdcFieldDisplayer displayer; /** * Constructor */ protected PdcFieldPositionsManager() { reset(); } public boolean isEnabled() { return enabled; } public String getFieldName() { return fieldName; } public ArrayList<ClassifyPosition> getPositions() { return positions; } public ArrayList<UsedAxis> getUsedAxisList() { return usedAxisList; } /** * Initializes and enables the manager. * @param fieldName The field name. * @param pattern The description of positions, following the pattern : * axisId1_1,valueId1_1;axisId1_2,valueId1_2.axisId2_1,valueId2_1... where axisIdi_j and * valueIdi_j correspond to the value #j of the position #i. * @param axis */ public void init(String fieldName, String pattern, String axis) { enabled = true; this.fieldName = fieldName; displayer = new PdcFieldDisplayer(); positions = displayer.getPositions(pattern); usedAxisList = displayer.getUsedAxisList(axis); } /** * Resets and disables the manager. */ public void reset() { enabled = false; fieldName = null; displayer = null; positions = null; usedAxisList = null; } /** * Add the position to the positions list. * @param position The new position to add. */ public void addPosition(ClassifyPosition position) { position.setPositionId(positions.size()); positions.add(position); refreshPositions(); } /** * Update the position. * @param position The position to update. * @return the status of the update. */ public int updatePosition(ClassifyPosition position) { ClassifyPosition currentPosition; int i = 0; boolean positionFound = false; while (i < positions.size() && !positionFound) { currentPosition = positions.get(i); if (currentPosition.getPositionId() == position.getPositionId()) { positions.set(i, position); positionFound = true; } i++; } refreshPositions(); return -1; } /** * Deletes the position which id corresponds to the one given as parameter. * @param positionId The id of the position to delete. */ public void deletePosition(int positionId) { ClassifyPosition position; boolean axisRemoved = false; int i = 0; while (i < positions.size() && !axisRemoved) { position = positions.get(i); if (position.getPositionId() == positionId) { positions.remove(i); axisRemoved = true; } else { i++; } } if (axisRemoved) { while (i < positions.size()) { positions.get(i).setPositionId(i); i++; } } refreshPositions(); } /** * Calls the PDC field displayer to update and complete the description of positions. */ private void refreshPositions() { positions = displayer.getPositions(getPositionsToString()); } /** * @return A pattern describing the positions : * axisId1_1,valueId1_1;axisId1_2,valueId1_2.axisId2_1,valueId2_1... where axisIdi_j and * valueIdi_j correspond to the value #j of the position #i. */ public String getPositionsToString() { StringBuffer result = new StringBuffer(); if (positions != null) { ClassifyPosition position; ClassifyValue classifyValue; String[] values; String valuesPath; for (int i = 0; i < positions.size(); i++) { if (i > 0) { result.append("."); } position = positions.get(i); List<ClassifyValue> classifyValues = position.getValues(); for (int j = 0; j < classifyValues.size(); j++) { if (j > 0) { result.append(";"); } classifyValue = classifyValues.get(j); result.append(classifyValue.getAxisId()).append(","); valuesPath = classifyValue.getValue(); if (valuesPath != null && valuesPath.length() > 0) { values = valuesPath.split("/"); result.append(values[values.length - 1]); } } } } return result.toString(); } }
auroreallibe/Silverpeas-Core
core-war/src/main/java/org/silverpeas/web/pdc/control/PdcFieldPositionsManager.java
Java
agpl-3.0
6,060
package com.jogamp.opengl; public interface GLRunnable { boolean run(GLAutoDrawable drawable); }
gama-platform/gama.cloud
ummisco.gama.opengl_web/src/com/jogamp/opengl/GLRunnable.java
Java
agpl-3.0
102
export interface Environment { readonly production: boolean; readonly geoLocation: { readonly timeoutMillis: number readonly firefoxWorkaroundTimeoutMillis: number readonly updateMillis: number }; readonly gastroLocationsUrl: string; readonly shoppingLocationsUrl?: string; readonly reviewsBaseUrl: string; readonly homePage: { readonly url: string readonly title: string }; readonly nativeAppUrl?: string; readonly reportNewLocationUrl?: string; readonly reportProblemEmail: string; readonly area: { /** * Two-letter county code in lowercase. * * E.g. "de" */ readonly country: string /** * The initial center of the map */ readonly center: { readonly lat: number readonly lng: number } /** * The initial bounds of the map */ readonly bounds: { readonly north: number readonly south: number readonly west: number readonly east: number } /** * The initial zoom of the map */ readonly zoom: 12 }; readonly googleAnalyticsTrackingIds: { readonly website?: string readonly map?: string }; }
Berlin-Vegan/berlin-vegan-map
angular/src/environments/environment-type-def.ts
TypeScript
agpl-3.0
1,352
# -*- coding: utf-8 -*- # Copyright (C) 2010 Samalyse SARL # Copyright (C) 2010-2014 Parisson SARL # This file is part of Telemeta. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: Olivier Guilyardi <olivier@samalyse.com> # David LIPSZYC <davidlipszyc@gmail.com> # Guillaume Pellerin <yomguy@parisson.com> from __future__ import division from django.utils.translation import ugettext_lazy as _ from telemeta.models.core import * from telemeta.models.resource import * from telemeta.models.collection import * class MediaCorpus(MediaBaseResource): "Describe a corpus" element_type = 'corpus' children_type = 'collections' children = models.ManyToManyField(MediaCollection, related_name="corpus", verbose_name=_('collections'), blank=True) recorded_from_year = IntegerField(_('recording year (from)'), help_text=_('YYYY')) recorded_to_year = IntegerField(_('recording year (until)'), help_text=_('YYYY')) objects = MediaCorpusManager() permissions = (("can_download_corpus_epub", "Can download corpus EPUB"),) @property def public_id(self): return self.code @property def has_mediafile(self): for child in self.children.all(): if child.has_mediafile: return True return False def computed_duration(self): duration = Duration() for child in self.children.all(): duration += child.computed_duration() return duration computed_duration.verbose_name = _('total available duration') class Meta(MetaCore): db_table = 'media_corpus' verbose_name = _('corpus') verbose_name_plural = _('corpus') ordering = ['code'] class MediaCorpusRelated(MediaRelated): "Corpus related media" resource = ForeignKey(MediaCorpus, related_name="related", verbose_name=_('corpus')) class Meta(MetaCore): db_table = 'media_corpus_related' verbose_name = _('corpus related media') verbose_name_plural = _('corpus related media')
ANR-kamoulox/Telemeta
telemeta/models/corpus.py
Python
agpl-3.0
2,752
#!/usr/bin/env python3 # Sifer Aseph """Prints a "hello world" statement.""" def main(): """Utterly standard.""" print("Hello cruel world.") if __name__ == "__main__": main()
Surufel/Personal
2.pysifer/Older/hello_world.py
Python
agpl-3.0
189
require 'rails_helper' RSpec.describe "Moves" do before(:each) { sign_in_as('Editor') } get_basic_editor_views('move',['reason']) end
moritzsternemann/ReadyResponder
spec/features/moves_spec.rb
Ruby
agpl-3.0
140
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Peter Martin using IMS Development Environment (version 1.70 build 3545.21176) // Copyright (C) 1995-2009 IMS MAXIMS. All rights reserved. package ims.RefMan.domain.impl; import java.util.ArrayList; import java.util.List; import ims.admin.domain.HcpAdmin; import ims.admin.domain.impl.HcpAdminImpl; import ims.RefMan.domain.base.impl.BaseClinicalNotesComponentImpl; import ims.RefMan.domain.objects.ConsultationClinicalNotes; import ims.domain.DomainFactory; import ims.domain.exceptions.StaleObjectException; import ims.domain.exceptions.UniqueKeyViolationException; import ims.framework.enumerations.SortOrder; import ims.framework.exceptions.CodingRuntimeException; import ims.RefMan.vo.ConsultationClinicalNotesRefVo; import ims.RefMan.vo.ConsultationClinicalNotesVoCollection; import ims.RefMan.vo.domain.ConsultationClinicalNotesVoAssembler; import ims.clinical.domain.Allergies; import ims.clinical.domain.impl.AllergiesImpl; import ims.core.patient.vo.PatientRefVo; import ims.core.vo.HcpLiteVoCollection; import ims.core.vo.PatientAllergyCollection; import ims.core.vo.PatientNoAllergyInfoVo; import ims.core.vo.PatientShort; import ims.core.vo.domain.PatientShortAssembler; public class ClinicalNotesComponentImpl extends BaseClinicalNotesComponentImpl { private static final long serialVersionUID = 1L; public ims.RefMan.vo.ConsultationClinicalNotesVo getConsultationClinicalNotesVo(ims.RefMan.vo.CatsReferralRefVo refVoCatsReferral) { DomainFactory factory = getDomainFactory(); StringBuffer hql = new StringBuffer(" from ConsultationClinicalNotes ccn"); ArrayList<String> markers = new ArrayList<String>(); ArrayList<Integer> values = new ArrayList<Integer>(); hql.append(" where ccn.catsReferral.id = :crId "); markers.add("crId"); values.add(refVoCatsReferral.getID_CatsReferral()); List listNotes = factory.find(hql.toString(), markers,values); if(listNotes != null && listNotes.size() > 0) { ConsultationClinicalNotesVoCollection voColl = ConsultationClinicalNotesVoAssembler.createConsultationClinicalNotesVoCollectionFromConsultationClinicalNotes(listNotes); if(voColl != null && voColl.size() > 0) { voColl.sort(SortOrder.DESCENDING); return voColl.get(0); } } return null; } public ims.RefMan.vo.ConsultationClinicalNotesVo getNote(ConsultationClinicalNotesRefVo note) { if (note == null) throw new RuntimeException("Cannot get ConsultationClinicalNotesVo for null ConsultationClinicalNotesRefVo"); ConsultationClinicalNotes doConsultationClinicalNotes = (ConsultationClinicalNotes) getDomainFactory().getDomainObject(ConsultationClinicalNotes.class, note.getID_ConsultationClinicalNotes()); return ConsultationClinicalNotesVoAssembler.create(doConsultationClinicalNotes); } public ims.RefMan.vo.ConsultationClinicalNotesVo saveConsultationClinicalNotesVo(ims.RefMan.vo.ConsultationClinicalNotesVo voConsultationClinicalNotes) throws ims.domain.exceptions.StaleObjectException { if(voConsultationClinicalNotes == null) throw new CodingRuntimeException("ConsultationClinicalNotesVo is null"); if(!voConsultationClinicalNotes.isValidated()) throw new CodingRuntimeException("ConsultationClinicalNotesVo has not been validated"); DomainFactory factory = getDomainFactory(); ConsultationClinicalNotes doConsultationClinicalNotes = ConsultationClinicalNotesVoAssembler.extractConsultationClinicalNotes(factory, voConsultationClinicalNotes); factory.save(doConsultationClinicalNotes); return ConsultationClinicalNotesVoAssembler.create(doConsultationClinicalNotes); } public HcpLiteVoCollection listHcpLiteByName(String hcpName) { HcpAdmin hcpAdmin = (HcpAdmin)getDomainImpl(HcpAdminImpl.class); return hcpAdmin.listHcpLiteByName(hcpName); } public PatientAllergyCollection listPatientAllergies(PatientShort patient) { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.listPatientAllergies(patient, true); } public PatientNoAllergyInfoVo getPatientNoAllergyInfo(PatientRefVo patientRefVo) { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.getPatientNoAllergyInfo(patientRefVo); } public PatientNoAllergyInfoVo savePatientNoAllergyInfo(PatientNoAllergyInfoVo patientNoAllergyInfo) throws StaleObjectException, UniqueKeyViolationException { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.savePatientNoAllergyInfo(patientNoAllergyInfo); } //wdev-10534 public PatientShort getPatientShort(PatientRefVo patientRefVo) { DomainFactory factory = getDomainFactory(); ims.core.patient.domain.objects.Patient patBo = (ims.core.patient.domain.objects.Patient) factory.getDomainObject(ims.core.patient.domain.objects.Patient.class, patientRefVo.getID_Patient().intValue()); return PatientShortAssembler.create(patBo); } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/domain/impl/ClinicalNotesComponentImpl.java
Java
agpl-3.0
6,912
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. module AWS module Core module Signature module Version2 def add_authorization! credentials add_param('AWSAccessKeyId', credentials.access_key_id) if token = credentials.session_token add_param("SecurityToken", token) end add_param('SignatureVersion', '2') add_param('SignatureMethod', 'HmacSHA256') add_param('Signature', signature(credentials)) self.body = url_encoded_params end protected def signature credentials Signer.sign(credentials.secret_access_key, string_to_sign) end def string_to_sign host = case port when 80, 443 then self.host else "#{self.host}:#{port}" end [ http_method, host.to_s.downcase, path, params.sort.collect { |p| p.encoded }.join('&'), ].join("\n") end end end end end
usmschuck/canvas
vendor/bundle/ruby/1.9.1/gems/aws-sdk-1.8.3.1/lib/aws/core/signature/version_2.rb
Ruby
agpl-3.0
1,576
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var tb_pathToImage = "images/loadingAnimation.gif"; /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init $(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ $(domChunk).click(function(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; }); } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 $("body","html").css({height: "100%", width: "100%"}); $("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page $('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = $("a[@rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar'>Cerrar</a></div>"); $("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);} $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } $("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } $("#TB_next").click(goNext); } document.onkeydown = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } else if(keycode == 190){ // display previous image if(!(TB_NextHTML == "")){ document.onkeydown = ""; goNext(); } } else if(keycode == 188){ // display next image if(!(TB_PrevHTML == "")){ document.onkeydown = ""; goPrev(); } } }; tb_position(); $("#TB_load").remove(); $("#TB_ImageOff").click(tb_remove); $("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); $("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar'>Cerrar</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>"); }else{//iframe modal $("#TB_overlay").unbind(); $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>"); } }else{// not an iframe, ajax if($("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Cerrar</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal $("#TB_overlay").unbind(); $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; $("#TB_ajaxContent")[0].scrollTop = 0; $("#TB_ajaxWindowTitle").html(caption); } } $("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ $("#TB_ajaxContent").append($('#' + params['inlineId']).children()); $("#TB_window").unload(function () { $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); $("#TB_load").remove(); $("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if($.browser.safari){//safari needs help because it will not fire iframe onload $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } }else{ $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); $("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); $("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ document.onkeyup = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } }; } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } function tb_remove() { $("#TB_imageOff").unbind("click"); $("#TB_closeWindowButton").unbind("click"); $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); $("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 $("body","html").css({height: "auto", width: "auto"}); $("html").css("overflow",""); } document.onkeydown = ""; document.onkeyup = ""; return false; } function tb_position() { $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6 $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
manuchis/10.000-ideas
admin/js/jquery.thickbox.js
JavaScript
agpl-3.0
11,601
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.71 build 3642.24101) // Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved. package ims.core.forms.patientmergemanager; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } public boolean isReadOnly() { if(super.isReadOnly()) return true; // TODO: Add your conditions here. return false; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/patientmergemanager/AccessLogic.java
Java
agpl-3.0
2,547
// // Copyright (C) 2017 - present Instructure, Inc. // // This file is part of Canvas. // // Canvas is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License as published by the Free // Software Foundation, version 3 of the License. // // Canvas is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. import $ from 'jquery' import I18n from 'i18n!broken_images' export function attachErrorHandler(imgElement) { $(imgElement).on('error', e => { if (e.currentTarget.src) { $.get(e.currentTarget.src).fail(response => { if (response.status === 403) { // Replace the image with a lock image $(e.currentTarget).attr({ src: '/images/svg-icons/icon_lock.svg', alt: I18n.t('Locked image'), width: 100, height: 100 }) } else { // Add the broken-image class $(e.currentTarget).addClass('broken-image') } }) } else { // Add the broken-image class (if there is no source) $(e.currentTarget).addClass('broken-image') } }) } export function getImagesAndAttach() { Array.from(document.querySelectorAll('img:not([src=""])')).forEach(attachErrorHandler) } // this behavior will set up all broken images on the page with an error handler that // can apply the broken-image class if there is an error loading the image. $(document).ready(() => getImagesAndAttach())
djbender/canvas-lms
app/coffeescripts/behaviors/broken-images.js
JavaScript
agpl-3.0
1,809
/// <reference path="../../../public/app/headers/common.d.ts" /> export default class TimeSeries { datapoints: any; id: string; label: string; alias: string; color: string; valueFormater: any; stats: any; legend: boolean; allIsNull: boolean; allIsZero: boolean; decimals: number; scaledDecimals: number; hasMsResolution: boolean; isOutsideRange: boolean; lines: any; bars: any; points: any; yaxis: any; zindex: any; stack: any; nullPointMode: any; fillBelowTo: any; transform: any; flotpairs: any; unit: any; constructor(opts: any); applySeriesOverrides(overrides: any): void; getFlotPairs(fillStyle: any): any[]; updateLegendValues(formater: any, decimals: any, scaledDecimals: any): void; formatValue(value: any): any; isMsResolutionNeeded(): boolean; hideFromLegend(options: any): boolean; }
n0rad/housecream
public/app/core/time_series2.d.ts
TypeScript
agpl-3.0
923
/** ****************************************************************************** * @file hal_dynalib_export.c * @author Matthew McGowan ****************************************************************************** Copyright (c) 2015 Particle Industries, Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #define DYNALIB_EXPORT #include "hal_dynalib.h" #include "hal_dynalib_core.h" #include "hal_dynalib_gpio.h" #include "hal_dynalib_i2c.h" #include "hal_dynalib_ota.h" #include "hal_dynalib_peripherals.h" #include "hal_dynalib_socket.h" #include "hal_dynalib_spi.h" #include "hal_dynalib_usart.h" #include "hal_dynalib_wlan.h" #include "hal_dynalib_concurrent.h" #include "hal_dynalib_cellular.h" #include "hal_dynalib_can.h" #include "hal_dynalib_rgbled.h" #include "hal_dynalib_dct.h" #ifndef HAL_USB_EXCLUDE #include "hal_dynalib_usb.h" #endif #ifndef HAL_BOOTLOADER_EXCLUDE #include "hal_dynalib_bootloader.h" #endif
BrewPi/firmware
platform/spark/firmware/hal/src/stm32f2xx/hal_dynalib_export.cpp
C++
agpl-3.0
1,653
""" Django Views for service status app """ from __future__ import absolute_import import json import time from celery.exceptions import TimeoutError from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_): """ An empty view """ return HttpResponse() def celery_status(_): """ A view that returns Celery stats """ stats = celery.control.inspect().stats() or {} return HttpResponse(json.dumps(stats, indent=4), content_type="application/json") def celery_ping(_): """ A Simple view that checks if Celery can process a simple task """ start = time.time() result = delayed_ping.apply_async(('ping', 0.1)) task_id = result.id # Wait until we get the result try: value = result.get(timeout=4.0) success = True except TimeoutError: value = None success = False output = { 'success': success, 'task_id': task_id, 'value': value, 'time': time.time() - start, } return HttpResponse(json.dumps(output, indent=4), content_type="application/json")
ESOedX/edx-platform
openedx/core/djangoapps/service_status/views.py
Python
agpl-3.0
1,236
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.forms.dailypatientprogress; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.nursing.domain.DailyPatientProgress.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.nursing.domain.DailyPatientProgress domain) { setContext(engine, form); this.domain = domain; } protected final void oncmbStatusValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatus().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusLookup(); return; } } } } else if(value instanceof ims.core.vo.lookups.PatientAssessmentStatusReason) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = (ims.core.vo.lookups.PatientAssessmentStatusReason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatus().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusLookup() { this.form.cmbStatus().clear(); ims.core.vo.lookups.PatientAssessmentStatusReasonCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatus().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusLookupValue(int id) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatus().setValue(instance); } protected final void defaultcmbStatusLookupValue() { this.form.cmbStatus().setValue((ims.core.vo.lookups.PatientAssessmentStatusReason)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.PatientAssessmentStatusReason.class, engine.getFormName().getID(), ims.core.vo.lookups.PatientAssessmentStatusReason.TYPE_ID)); } protected final void oncmbStatusReasonValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatusReason().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusReasonLookup(); return; } } } } else if(value instanceof ims.core.vo.lookups.PatientAssessmentStatusReason) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = (ims.core.vo.lookups.PatientAssessmentStatusReason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusReasonLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatusReason().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusReasonLookup() { this.form.cmbStatusReason().clear(); ims.core.vo.lookups.PatientAssessmentStatusReasonCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatusReason().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusReasonLookupValue(int id) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatusReason().setValue(instance); } protected final void defaultcmbStatusReasonLookupValue() { this.form.cmbStatusReason().setValue((ims.core.vo.lookups.PatientAssessmentStatusReason)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.PatientAssessmentStatusReason.class, engine.getFormName().getID(), ims.core.vo.lookups.PatientAssessmentStatusReason.TYPE_ID)); } protected final void oncmbAssessmentTypeValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbAssessmentType().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.assessment.vo.lookups.DPPType existingInstance = (ims.assessment.vo.lookups.DPPType)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbAssessmentTypeLookup(); return; } } } } else if(value instanceof ims.assessment.vo.lookups.DPPType) { ims.assessment.vo.lookups.DPPType instance = (ims.assessment.vo.lookups.DPPType)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbAssessmentTypeLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.assessment.vo.lookups.DPPType existingInstance = (ims.assessment.vo.lookups.DPPType)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbAssessmentType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbAssessmentTypeLookup() { this.form.cmbAssessmentType().clear(); ims.assessment.vo.lookups.DPPTypeCollection lookupCollection = ims.assessment.vo.lookups.LookupHelper.getDPPType(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbAssessmentType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbAssessmentTypeLookupValue(int id) { ims.assessment.vo.lookups.DPPType instance = ims.assessment.vo.lookups.LookupHelper.getDPPTypeInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbAssessmentType().setValue(instance); } protected final void defaultcmbAssessmentTypeLookupValue() { this.form.cmbAssessmentType().setValue((ims.assessment.vo.lookups.DPPType)domain.getLookupService().getDefaultInstance(ims.assessment.vo.lookups.DPPType.class, engine.getFormName().getID(), ims.assessment.vo.lookups.DPPType.TYPE_ID)); } protected void clearScreen() { this.form.txtStatusReason().setValue(""); this.form.txtOtherType().setValue(""); this.form.cmbStatus().setValue(null); this.form.cmbStatusReason().setValue(null); this.form.cmbAssessmentType().setValue(null); } protected void populateScreenFromData(ims.assessment.vo.PatientAssessmentVo value) { clearScreen(); if(value == null) return; this.form.txtStatusReason().setValue(value.getStatusReasonTextIsNotNull() ? value.getStatusReasonText(): null); this.form.txtOtherType().setValue(value.getDPPTypeTextIsNotNull() ? value.getDPPTypeText(): null); this.form.cmbStatus().setValue(value.getStatusIsNotNull() ? value.getStatus() : null); this.form.cmbStatusReason().setValue(value.getStatusReasonIsNotNull() ? value.getStatusReason() : null); this.form.cmbAssessmentType().setValue(value.getDPPTypeIsNotNull() ? value.getDPPType() : null); } protected ims.assessment.vo.PatientAssessmentVo populateDataFromScreen(ims.assessment.vo.PatientAssessmentVo value) { if(value == null) value = new ims.assessment.vo.PatientAssessmentVo(); value.setStatusReasonText(this.form.txtStatusReason().getValue()); value.setDPPTypeText(this.form.txtOtherType().getValue()); value.setStatus(this.form.cmbStatus().getValue()); value.setStatusReason(this.form.cmbStatusReason().getValue()); value.setDPPType(this.form.cmbAssessmentType().getValue()); return value; } protected ims.assessment.vo.PatientAssessmentVo populateDataFromScreen() { return populateDataFromScreen(new ims.assessment.vo.PatientAssessmentVo()); } public final void free() { super.free(); domain = null; } protected ims.nursing.domain.DailyPatientProgress domain; }
open-health-hub/openmaxims-linux
openmaxims_workspace/Nursing/src/ims/nursing/forms/dailypatientprogress/BaseLogic.java
Java
agpl-3.0
11,025
<?php namespace Guzzle\Iterator; use Guzzle\Common\Exception\InvalidArgumentException; /** * Filters values using a callback * * Used when PHP 5.4's {@see \CallbackFilterIterator} is not available */ class FilterIterator extends \FilterIterator { /** @var mixed Callback used for filtering */ protected $callback; /** * @param \Iterator $iterator Traversable iterator * @param array|\Closure $callback Callback used for filtering. Return true to keep or false to filter. * * @throws InvalidArgumentException if the callback if not callable */ public function __construct( \Iterator $iterator, $callback ) { parent::__construct( $iterator ); if (!is_callable( $callback )) { throw new InvalidArgumentException( 'The callback must be callable' ); } $this->callback = $callback; } public function accept() { return call_user_func( $this->callback, $this->current() ); } }
KWZwickau/KREDA-Sphere
Sphere/Common/Extension/GitHub/Vendor/Guzzle/src/Guzzle/Iterator/FilterIterator.php
PHP
agpl-3.0
999
<?php /* homepage: http://arc.semsol.org/ license: http://arc.semsol.org/license class: ARC2 POSH RDF Serializer author: Benjamin Nowack version: 2008-11-18 (Tweak: Updated to poshRDF spec draft) */ ARC2::inc('RDFSerializer'); class ARC2_POSHRDFSerializer extends ARC2_RDFSerializer { function __construct($a = '', &$caller) { parent::__construct($a, $caller); } function ARC2_POSHRDFSerializer($a = '', &$caller) {/* ns */ $this->__construct($a, $caller); } function __init() { parent::__init(); $this->content_header = 'text/html'; } /* */ function getLabel($res, $ps = '') { if (!$ps) $ps = array(); foreach ($ps as $p => $os) { if (preg_match('/[\/\#](name|label|summary|title|fn)$/i', $p)) { return $os[0]['value']; } } if (preg_match('/^\_\:/', $res)) return "An unnamed resource"; return preg_replace("/^(.*[\/\#])([^\/\#]+)$/", '\\2', str_replace('_', ' ', $res)); } function getSerializedIndex($index, $res = '') { $r = ''; $n = "\n"; if ($res) $index = array($res => $index[$res]); //return Trice::dump($index); foreach ($index as $s => $ps) { /* node */ $r .= ' <div class="rdf-node dump"> <h3><a class="rdf-s" href="' . $s . '">' . $this->getLabel($s, $ps) . '</a></h3> '; /* arcs */ foreach ($ps as $p => $os) { $r .= ' <div class="rdf-arcs"> <a class="rdf-p" href="' . $p . '">' . ucfirst($this->getLabel($p)) . '</a> '; foreach ($os as $o) { $r .= $n . $this->getObjectValue($o); } $r .= ' </div> '; } /* node */ $r .= ' <div class="clb"></div> </div> '; } return $r; } function getObjectValue($o) { if ($o['type'] == 'uri') { if (preg_match('/(jpe?g|gif|png)$/i', $o['value'])) { return '<img class="rdf-o" src="' . htmlspecialchars($o['value']) . '" alt="img" />'; } return '<a class="rdf-o" href="' . htmlspecialchars($o['value']) . '">' . preg_replace('/^https?\:\/\/(www\.)?/', '', $o['value']) . '</a>'; } if ($o['type'] == "bnode") { return '<div class="rdf-o" title="' . $o['value']. '">An unnamed resource</div>'; } return '<div class="rdf-o">' . $o['value'] . '</div>'; } /* */ }
akbarhossain/openid4me
arc/serializers/ARC2_POSHRDFSerializer.php
PHP
agpl-3.0
2,384
<?php /* * ---------------------------------------------------------------------------- * Decoro Urbano version 0.4.0 * ---------------------------------------------------------------------------- * Copyright Maiora Labs Srl (c) 2012 * ---------------------------------------------------------------------------- * * This file is part of Decoro Urbano. * * Decoro Urbano is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Decoro Urbano is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Decoro Urbano. If not, see <http://www.gnu.org/licenses/>. */ /** * Chiamata AJAX per eliminare un commento dalla lista dei commenti * * @param int id id del commento da cancellare */ session_start(); require_once("../include/config.php"); require_once("../include/db_open.php"); require_once("../include/db_open_funzioni.php"); require_once("../include/funzioni.php"); require_once("../include/controlli.php"); require_once('../include/decorourbano.php'); // verifico la presenza dei parametri if (!$_GET['id']) { echo '0'; exit; } // recupera i dati dell'utente loggato Auth::init(); $user = Auth::user_get(); // se l'utente non è loggato esci if (!$user) { echo "0"; exit; } $id_utente = (int) $user['id_utente']; $id = (int) cleanField($_GET['id']); // effettua la cancellazione if (!checkNumericField($id) || !commento_delete($id, $id_utente)) { echo "0"; } else { echo "1"; } ?>
Wikitalia/Decoro-Urbano
ajax/commento_elimina.php
PHP
agpl-3.0
1,905
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.specimenintraopdialog; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); Clinical = new ClinicalContext(context); } public final class ClinicalContext implements Serializable { private static final long serialVersionUID = 1L; private ClinicalContext(ims.framework.Context context) { this.context = context; } public boolean getTheatreAppointmentRefIsNotNull() { return !cx_ClinicalTheatreAppointmentRef.getValueIsNull(context); } public ims.scheduling.vo.Booking_AppointmentRefVo getTheatreAppointmentRef() { return (ims.scheduling.vo.Booking_AppointmentRefVo)cx_ClinicalTheatreAppointmentRef.getValue(context); } public void setTheatreAppointmentRef(ims.scheduling.vo.Booking_AppointmentRefVo value) { cx_ClinicalTheatreAppointmentRef.setValue(context, value); } private ims.framework.ContextVariable cx_ClinicalTheatreAppointmentRef = new ims.framework.ContextVariable("Clinical.TheatreAppointmentRef", "_cv_Clinical.TheatreAppointmentRef"); public boolean getIntraOpSpecimenVoIsNotNull() { return !cx_ClinicalIntraOpSpecimenVo.getValueIsNull(context); } public ims.clinical.vo.SpecimenIntraOpVo getIntraOpSpecimenVo() { return (ims.clinical.vo.SpecimenIntraOpVo)cx_ClinicalIntraOpSpecimenVo.getValue(context); } public void setIntraOpSpecimenVo(ims.clinical.vo.SpecimenIntraOpVo value) { cx_ClinicalIntraOpSpecimenVo.setValue(context, value); } private ims.framework.ContextVariable cx_ClinicalIntraOpSpecimenVo = new ims.framework.ContextVariable("Clinical.IntraOpSpecimenVo", "_cv_Clinical.IntraOpSpecimenVo"); private ims.framework.Context context; } public ClinicalContext Clinical; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/forms/specimenintraopdialog/GlobalContext.java
Java
agpl-3.0
4,062
<?php /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2017 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ $module_name = 'bh_marketing_company_history'; $viewdefs[$module_name]['DetailView'] = array( 'templateMeta' => array( 'form' => array( 'buttons' => array( 'EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES', ) ), 'maxColumns' => '2', 'widths' => array( array('label' => '10', 'field' => '30'), array('label' => '10', 'field' => '30') ), ), 'panels' => array( array( 'name', 'assigned_user_name', ), array( array( 'name' => 'date_entered', 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', 'label' => 'LBL_DATE_ENTERED', ), array( 'name' => 'date_modified', 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', 'label' => 'LBL_DATE_MODIFIED', ), ), array( 'description', ), ) );
ByersHouse/crmwork
modules/bh_marketing_company_history/metadata/detailviewdefs.php
PHP
agpl-3.0
3,233
<?php if(isset($_GET['articleID'])){ $articleID = intval($_GET['articleID']); } else { die('Invalid Request'); } require dirname(__DIR__)."/connection.php"; $result = $conn->query("SELECT * FROM articles WHERE id = $articleID"); $row = $result->fetch_assoc(); echo $row["name"] .'; '.$row["description"] .'; '. $row['price'] .'; '.$row['unit'].'; '.$row['taxID'].'; '.$row['purchase']; ?>
eitea/Connect
src/ajaxQuery/AJAX_getArticles.php
PHP
agpl-3.0
395
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.domain; // Generated from form domain impl public interface DocumentWorkList extends ims.domain.DomainInterface { }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/domain/DocumentWorkList.java
Java
agpl-3.0
2,244
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo.beans; public class CareContextForClinicalNotesVoBean extends ims.vo.ValueObjectBean { public CareContextForClinicalNotesVoBean() { } public CareContextForClinicalNotesVoBean(ims.RefMan.vo.CareContextForClinicalNotesVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.CareContextForClinicalNotesVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); } public ims.RefMan.vo.CareContextForClinicalNotesVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.RefMan.vo.CareContextForClinicalNotesVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.CareContextForClinicalNotesVo vo = null; if(map != null) vo = (ims.RefMan.vo.CareContextForClinicalNotesVo)map.getValueObject(this); if(vo == null) { vo = new ims.RefMan.vo.CareContextForClinicalNotesVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.vo.RefVoBean getEpisodeOfCare() { return this.episodeofcare; } public void setEpisodeOfCare(ims.vo.RefVoBean value) { this.episodeofcare = value; } private Integer id; private int version; private ims.vo.RefVoBean episodeofcare; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/beans/CareContextForClinicalNotesVoBean.java
Java
agpl-3.0
3,984
/** * JUNIT SS7Firewall class * * SigFW * Open Source SS7/Diameter firewall * By Martin Kacer, Philippe Langlois * Copyright 2017, P1 Security S.A.S and individual contributors * * See the AUTHORS in the distribution for a * full listing of individual contributors. * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package sigfw.tests; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mobicents.protocols.api.IpChannelType; import org.mobicents.protocols.ss7.indicator.NatureOfAddress; import org.mobicents.protocols.ss7.indicator.RoutingIndicator; import org.mobicents.protocols.ss7.sccp.message.SccpDataMessage; import org.mobicents.protocols.ss7.sccp.parameter.GlobalTitle; import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress; import static ss7fw.SS7Client.hexStringToByteArray; import ss7fw.SS7Firewall; import ss7fw.SS7FirewallConfig; public class Test_SS7Firewall { private static SS7Firewall sigfw = null; private static SccpAddress callingParty; private static SccpAddress calledParty; private static void initializeSS7Firewall() { try { // Use last config SS7FirewallConfig.loadConfigFromFile("ss7fw_junit.json"); // TODO use the following directive instead to do not use .last configs //SS7FirewallConfig.loadConfigFromFile(configName); } catch (Exception ex) { java.util.logging.Logger.getLogger(SS7FirewallConfig.class.getName()).log(Level.SEVERE, null, ex); } sigfw = new SS7Firewall(); sigfw.unitTesting = true; try { sigfw.initializeStack(IpChannelType.SCTP); } catch (Exception e) { e.printStackTrace(); } // set the calling and called GT for unittests GlobalTitle callingGT = sigfw.sccpStack.getSccpProvider().getParameterFactory().createGlobalTitle("111111111111", 0, org.mobicents.protocols.ss7.indicator.NumberingPlan.ISDN_MOBILE, null, NatureOfAddress.INTERNATIONAL); GlobalTitle calledGT = sigfw.sccpStack.getSccpProvider().getParameterFactory().createGlobalTitle("000000000000", 0, org.mobicents.protocols.ss7.indicator.NumberingPlan.ISDN_MOBILE, null, NatureOfAddress.INTERNATIONAL); callingParty = sigfw.sccpStack.getSccpProvider().getParameterFactory().createSccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, callingGT, 1, 8); calledParty = sigfw.sccpStack.getSccpProvider().getParameterFactory().createSccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, calledGT, 2, 8); } @BeforeClass public static void testSS7FirewallInit() { initializeSS7Firewall(); } @Test public void testATI() { // anyTimeInterrogation sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("627e4804000000026b432841060700118605010101a036603480020780a109060704000001001d03be232821060704000001010101a016a01480099611111111111111f18107961111111111f16c31a12f0201000201473027a009800711111111111111a10f80008100830084010086008500870083099611111111111111f1"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("anyTimeInterrogation message (opCode 71, TCAP Begin) should be blocked by Cat1", !sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testPSL() { // provideSubscriberLocation sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("62454804000000536b1a2818060700118605010101a00d600ba1090607040000010026036c21a11f020101020153301730038001010407911111111111118307111111111111f1"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("provideSubscriberLocation message (opCode 83, TCAP Begin) should be blocked by Cat1", !sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testSAI() { // sendAuthenticationInfo sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("6516480433119839490402035ea26c08a106020102020138"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("sendAuthenticationInfo message (opCode 56, TCAP Continue) should be allowed", sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testUSSD() { // processUnstructuredSSRequest sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("62754804000000016b432841060700118605010101a036603480020780a109060704000001001302be232821060704000001010101a016a01480099611111111111111f18107961111111111f16c28a12602010002013b301e04010f0410aa582ca65ac562b1582c168bc562b1118007911111111111f1"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("processUnstructuredSSRequest message (opCode 59, TCAP Begin) should be allowed", sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testCL() { // cancelLocation sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("623b4804000000036b1a2818060700118605010101a00d600ba1090607040000010002036c17a115020101020103a30d040811111111111111f10a0100"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("cancelLocation message (opCode 3, TCAP Begin) should be blocked by Cat2", !sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testPSI() { // Provide Subscriber Info sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("623e4804000000466b1a2818060700118605010101a00d600ba109060704000001001c036c1aa1180201010201463010800811111111111111f1a20480008300"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("provideSubscriberInfo message (opCode 70, TCAP Begin) should be blocked by Cat2", !sigfw.unitTestingFlags_sendSccpMessage); } @Test public void testPRN() { // provideRoamingNumber sigfw.resetUnitTestingFlags(); SccpDataMessage sccpDataMessage = sigfw.sccpStack.getSccpProvider().getMessageFactory().createDataMessageClass0(calledParty, callingParty, hexStringToByteArray("625d4804000000046b1a2818060700118605010101a00d600ba1090607040000010003026c39a137020101020104302f800811111111111111f18107111111111111f18207111111111111f1a5080a010104030401a0880791111111111111"), 0, true, null, null); sigfw.onMessage(sccpDataMessage); try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test_SS7Firewall.class.getName()).log(Level.SEVERE, null, ex); } Assert.assertTrue("provideRoamingNumber message (opCode 4, TCAP Begin) should be blocked by Cat2", !sigfw.unitTestingFlags_sendSccpMessage); } }
P1sec/SigFW
sigfw/sigfw.sigfw/src/test/java/sigfw/tests/Test_SS7Firewall.java
Java
agpl-3.0
9,601
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseCumulateResultsImpl extends DomainImpl implements ims.ocrr.domain.CumulateResults, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatelistResults(ims.core.patient.vo.PatientRefVo patient, ims.ocrr.configuration.vo.AnalyteRefVoCollection analytes, ims.framework.utils.Date startDate, ims.framework.utils.Date endDate, Boolean isTabularView) { } @SuppressWarnings("unused") public void validategetDataset(ims.ocrr.configuration.vo.AnalyteRefVo analyte) { } @SuppressWarnings("unused") public void validategetOrder(ims.ocrr.orderingresults.vo.OrderInvestigationRefVo orderRef) { } @SuppressWarnings("unused") public void validategetOrderSpecimen(ims.ocrr.orderingresults.vo.OrderSpecimenRefVo specimenRef) { } @SuppressWarnings("unused") public void validategetDTFOrderInvestigation(ims.ocrr.orderingresults.vo.OrderInvestigationRefVo orderInvestigationRef) { } @SuppressWarnings("unused") public void validategetOrderInvestigation(ims.ocrr.orderingresults.vo.OrderInvestigationRefVo orderInvestigationRef) { } }
open-health-hub/openmaxims-linux
openmaxims_workspace/OCRR/src/ims/ocrr/domain/base/impl/BaseCumulateResultsImpl.java
Java
agpl-3.0
2,950
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseDementiaAssessmentAMTSComponentImpl extends DomainImpl implements ims.clinical.domain.DementiaAssessmentAMTSComponent, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validategetHintByLookupID(ims.clinicaladmin.vo.lookups.DementiaTermConfig volookup) { } @SuppressWarnings("unused") public void validatesaveDementia(ims.clinical.vo.DementiaVo voDementia) { } @SuppressWarnings("unused") public void validategetDementia(ims.core.clinical.vo.DementiaRefVo dementiaRef) { } }
open-health-hub/openmaxims-linux
openmaxims_workspace/Clinical/src/ims/clinical/domain/base/impl/BaseDementiaAssessmentAMTSComponentImpl.java
Java
agpl-3.0
2,382
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.ui.form.on("Supplier", { before_load: function(frm) { frappe.setup_language_field(frm); }, refresh: function(frm) { if(frappe.defaults.get_default("supp_master_name")!="Naming Series") { frm.toggle_display("naming_series", false); } else { erpnext.toggle_naming_series(); } if(frm.doc.__islocal){ hide_field(['address_html','contact_html']); erpnext.utils.clear_address_and_contact(frm); } else { unhide_field(['address_html','contact_html']); erpnext.utils.render_address_and_contact(frm); } }, }); cur_frm.fields_dict['default_price_list'].get_query = function(doc, cdt, cdn) { return{ filters:{'buying': 1} } } cur_frm.fields_dict['accounts'].grid.get_field('account').get_query = function(doc, cdt, cdn) { var d = locals[cdt][cdn]; return { filters: { 'account_type': 'Payable', 'company': d.company, "is_group": 0 } } }
anandpdoshi/erpnext
erpnext/buying/doctype/supplier/supplier.js
JavaScript
agpl-3.0
1,029
package qa.qcri.aidr.manager.dto; import qa.qcri.aidr.dbmanager.dto.CollectionDTO; public class TaggerCrisisRequest { private String code; private String name; private TaggerCrisisType crisisType; private TaggerUserRequest users; public TaggerCrisisRequest() { } public TaggerCrisisRequest(String code, String name, TaggerCrisisType crisisType, TaggerUserRequest users) { this.code = code; this.name = name; this.crisisType = crisisType; this.users = users; } public CollectionDTO toDTO() throws Exception { CollectionDTO dto = new CollectionDTO(); dto.setCode(this.getCode()); dto.setName(this.getName()); dto.setIsTrashed(false); dto.setUsersDTO(this.getUsers() != null ? this.getUsers().toDTO() : null); dto.setCrisisTypeDTO(this.getCrisisType() != null ? this.getCrisisType().toDTO() : null); return dto; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TaggerCrisisType getCrisisType() { return crisisType; } public void setCrisisType(TaggerCrisisType crisisType) { this.crisisType = crisisType; } public TaggerUserRequest getUsers() { return users; } public void setUsers(TaggerUserRequest users) { this.users = users; } }
qcri-social/Crisis-Computing
aidr-manager/src/main/java/qa/qcri/aidr/manager/dto/TaggerCrisisRequest.java
Java
agpl-3.0
1,518
# Copyright (C) 2007, 2008, 2009, 2010, 2011 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. require 'spec_helper' describe Place, "in the Perinatal Hep B plugin" do it "should return expected delivery facility place types" do Place.expected_delivery_type_codes.size.should == 3 ["H", "C", "O"].each do |place_type_code| Place.expected_delivery_type_codes.include?(place_type_code).should be_true end end it "should return actual delivery facility place types" do Place.actual_delivery_type_codes.size.should == 3 ["H", "C", "O"].each do |place_type_code| Place.actual_delivery_type_codes.include?(place_type_code).should be_true end end it "should return active, expected delivery facilities" do good = create_place_entity!('Hillcrest', 'expected_delivery') Place.expected_delivery_facilities.include?(good.place).should be_true deleted = create_place_entity!('Gonecrest', 'expected_delivery') deleted.update_attributes!(:deleted_at => DateTime.now) Place.expected_delivery_facilities.include?(deleted.place).should be_false wrong = create_place_entity!('Wrongcrest', 'lab') Place.expected_delivery_facilities.include?(wrong.place).should be_false end end
JayBoyer/new-trisano
plugins/trisano_perinatal_hep_b/spec/models/place_spec.rb
Ruby
agpl-3.0
1,914
/* * RapidMiner * * Copyright (C) 2001-2013 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.tools.dialogs; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.KeyStroke; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.components.LinkButton; import com.rapidminer.tools.LogService; import com.rapidminer.tools.Tools; import com.rapidminer.tools.plugin.Plugin; /** * This dialog displays some informations about the product. The product logo should have a size of approximately 270 * times 70 pixels. * * @author Ingo Mierswa */ public class AboutBox extends JDialog { private static final long serialVersionUID = -3889559376722324215L; private static final String PROPERTY_FILE = "about_infos.properties"; private static final String RAPID_MINER_LOGO_NAME = "rapidminer_logo.png"; public static final Image RAPID_MINER_LOGO; public static Image backgroundImage = null; static { URL url = Tools.getResource(RAPID_MINER_LOGO_NAME); Image rmLogo = null; if (url != null) { try { rmLogo = ImageIO.read(url); } catch (IOException e) { //LogService.getGlobal().logWarning("Cannot load logo for about box. Using empty image..."); LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.tools.dialogs.AboutBox.loading_logo_error"); } } RAPID_MINER_LOGO = rmLogo; url = Tools.getResource("splashscreen_community.png"); if (url != null) { try { backgroundImage = ImageIO.read(url); } catch (IOException e) { //LogService.getGlobal().logWarning("Cannot load background for about box. Using empty image..."); LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.tools.dialogs.AboutBox.loading_background_error"); } } } private ContentPanel contentPanel; private static class ContentPanel extends JPanel { private static final long serialVersionUID = -1763842074674706654L; private static final Paint MAIN_PAINT = Color.LIGHT_GRAY; private static final int MARGIN = 10; private Properties properties; private transient Image productLogo; public ContentPanel(Properties properties, Image productLogo) { this.properties = properties; this.productLogo = productLogo; int width = 450; int height = 350; if (backgroundImage != null) { width = backgroundImage.getWidth(this); height = backgroundImage.getHeight(this); } setPreferredSize(new Dimension(width, height)); setMinimumSize(new Dimension(width, height)); setMaximumSize(new Dimension(width, height)); } @Override public void paint(Graphics g) { super.paint(g); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawMain((Graphics2D) g); g.setColor(Color.black); g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); } public void drawMain(Graphics2D g) { g.setPaint(MAIN_PAINT); g.fillRect(0, 0, getWidth(), getHeight()); if (backgroundImage != null) g.drawImage(backgroundImage, 0, 0, this); int nameY = 100 + 26; g.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 26)); g.setColor(SwingTools.RAPID_I_BROWN); if (productLogo != null) { if ("true".equals(properties.getProperty("textNextToLogo"))) { g.drawImage(productLogo, 20, 90, this); g.drawString(properties.getProperty("name"), 20 + productLogo.getWidth(null) + 10, nameY); } else { g.drawImage(productLogo, getWidth() / 2 - productLogo.getWidth(this) / 2, 90, this); } } else { g.drawString(properties.getProperty("name"), 20, nameY); } int y = 240; g.setColor(SwingTools.BROWN_FONT_COLOR); g.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 11)); drawString(g, properties.getProperty("name") + " " + properties.getProperty("version"), y); y += 20; g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 10)); y = drawStringAndAdvance(g, properties.getProperty("name") + " " + properties.getProperty("version"), y); y = drawStringAndAdvance(g, properties.getProperty("copyright"), y); y = drawStringAndAdvance(g, properties.getProperty("licensor"), y); y = drawStringAndAdvance(g, properties.getProperty("license"), y); y = drawStringAndAdvance(g, properties.getProperty("warranty"), y); y = drawStringAndAdvance(g, properties.getProperty("more"), y); } private int drawStringAndAdvance(Graphics2D g, String string, int y) { if (string == null) { return y; } else { List<String> lines = new LinkedList<String>(); String[] words = string.split("\\s+"); String current = ""; for (String word : words) { if (current.length() + word.length() < 80) { current += word + " "; } else { lines.add(current); current = word + " "; } } if (!current.isEmpty()) { lines.add(current); } for (String line : lines) { drawString(g, line, y); y += 15; } return y; } } private void drawString(Graphics2D g, String text, int y) { if (text == null) return; float xPos = MARGIN; float yPos = y; g.drawString(text, xPos, yPos); } } public AboutBox(Frame owner, String productName, String productVersion, String licensor, String url, String text, boolean renderTextNextToLogo, Image productLogo) { this(owner, createProperties(productName, productVersion, licensor, url, text, renderTextNextToLogo), productLogo); } public AboutBox(Frame owner, String productVersion, Image productLogo) { this(owner, createProperties(productVersion), productLogo); } public AboutBox(Frame owner, Properties properties, Image productLogo) { super(owner, "About", true); // if (productLogo == null) { // productLogo = rapidMinerLogo; // } setResizable(false); setLayout(new BorderLayout()); String name = properties.getProperty("name"); if (name != null) { setTitle("About " + name); } contentPanel = new ContentPanel(properties, productLogo); add(contentPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new GridBagLayout()); // FlowLayout(FlowLayout.RIGHT)); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; final String url = properties.getProperty("url"); if (url != null) { c.weightx = 1; c.gridwidth = GridBagConstraints.RELATIVE; buttonPanel.add(new LinkButton(new ResourceAction("simple_link_action", url) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI(url)); } catch (Exception e1) { e1.printStackTrace(); } } }), c); } ResourceAction closeAction = new ResourceAction("close") { private static final long serialVersionUID = 1407089394491740308L; public void actionPerformed(ActionEvent e) { dispose(); } }; JButton closeButton = new JButton(closeAction); c.weightx = 0; c.gridwidth = GridBagConstraints.REMAINDER; buttonPanel.add(closeButton, c); add(buttonPanel, BorderLayout.SOUTH); getRootPane().setDefaultButton(closeButton); getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CANCEL"); getRootPane().getActionMap().put("CANCEL", closeAction); pack(); setLocationRelativeTo(owner); } public static Properties createProperties(InputStream inputStream, String productVersion) { Properties properties = new Properties(); if (inputStream != null) { try { properties.load(inputStream); } catch (Exception e) { //LogService.getGlobal().logError("Cannot read splash screen infos: " + e.getMessage()); LogService.getRoot().log(Level.SEVERE, "com.rapidminer.gui.tools.dialogs.AboutBox.reading_splash_screen_error", e.getMessage()); } } properties.setProperty("version", productVersion); Plugin.initAboutTexts(properties); return properties; } private static Properties createProperties(String productVersion) { Properties properties = new Properties(); try { URL propUrl = Tools.getResource(PROPERTY_FILE); if (propUrl != null) { InputStream in = propUrl.openStream(); properties.load(in); in.close(); } } catch (Exception e) { //LogService.getGlobal().logError("Cannot read splash screen infos: " + e.getMessage()); LogService.getRoot().log(Level.SEVERE, "com.rapidminer.gui.tools.dialogs.AboutBox.reading_splash_screen_error", e.getMessage()); } properties.setProperty("version", productVersion); Plugin.initAboutTexts(properties); return properties; } private static Properties createProperties(String productName, String productVersion, String licensor, String url, String text, boolean renderTextNextToLogo) { Properties properties = new Properties(); properties.setProperty("name", productName); properties.setProperty("version", productVersion); properties.setProperty("licensor", licensor); properties.setProperty("license", "URL: " + url); properties.setProperty("more", text); properties.setProperty("textNextToLogo", "" + renderTextNextToLogo); properties.setProperty("url", url); return properties; } }
aborg0/RapidMiner-Unuk
src/com/rapidminer/gui/tools/dialogs/AboutBox.java
Java
agpl-3.0
10,719
<?php // phpSysInfo - A PHP System Information Script // http://phpsysinfo.sourceforge.net/ // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // $Id: class.Linux.inc.php,v 1.88 2007/02/25 20:50:52 bigmichi1 Exp $ if (!defined('IN_PHPSYSINFO')) { die("No Hacking"); } require_once(APP_ROOT . '/includes/os/class.BSD.common.inc.php'); class sysinfo { var $inifile = "distros.ini"; var $icon = "unknown.png"; var $distro = "unknown"; var $parser; // get the distro name and icon when create the sysinfo object function sysinfo() { $this->parser = new Parser(); $this->parser->df_param = 'P'; $list = @parse_ini_file(APP_ROOT . "/" . $this->inifile, true); if (!$list) { return; } $distro_info = execute_program('lsb_release','-a 2> /dev/null', false); // We have the '2> /dev/null' because Ubuntu gives an error on this command which causes the distro to be unknown if ( $distro_info != 'ERROR') { $distro_tmp = split("\n",$distro_info); foreach( $distro_tmp as $info ) { $info_tmp = split(':', $info, 2); $distro[ $info_tmp[0] ] = trim($info_tmp[1]); } if( !isset( $list[$distro['Distributor ID']] ) ){ return; } $this->icon = isset($list[$distro['Distributor ID']]["Image"]) ? $list[$distro['Distributor ID']]["Image"] : $this->icon; $this->distro = $distro['Description']; } else { // Fall back in case 'lsb_release' does not exist ;) foreach ($list as $section => $distribution) { if (!isset($distribution["Files"])) { continue; } else { foreach (explode(";", $distribution["Files"]) as $filename) { if (file_exists($filename)) { $buf = rfts( $filename ); $this->icon = isset($distribution["Image"]) ? $distribution["Image"] : $this->icon; $this->distro = isset($distribution["Name"]) ? $distribution["Name"] . " " . trim($buf) : trim($buf); break 2; } } } } } } // get our apache SERVER_NAME or vhost function vhostname () { if (! ($result = getenv('SERVER_NAME'))) { $result = 'N.A.'; } return $result; } // get the IP address of our vhost name function vip_addr () { return gethostbyname($this->vhostname()); } // get our canonical hostname function chostname () { $result = rfts( '/proc/sys/kernel/hostname', 1 ); if ( $result == "ERROR" ) { $result = "N.A."; } else { $result = gethostbyaddr( gethostbyname( trim( $result ) ) ); } return $result; } // get the IP address of our canonical hostname function ip_addr () { if (!($result = getenv('SERVER_ADDR'))) { $result = gethostbyname($this->chostname()); } return $result; } function kernel () { $buf = rfts( '/proc/version', 1 ); if ( $buf == "ERROR" ) { $result = "N.A."; } else { if (preg_match('/version (.*?) /', $buf, $ar_buf)) { $result = $ar_buf[1]; if (preg_match('/SMP/', $buf)) { $result .= ' (SMP)'; } } } return $result; } function uptime () { $buf = rfts( '/proc/uptime', 1 ); $ar_buf = preg_split('/ /', $buf ); $result = trim( $ar_buf[0] ); return $result; } function users () { $strResult = 0; $strBuf = execute_program('who', '-q'); if( $strBuf != "ERROR" ) { $arrWho = preg_split('/=/', $strBuf ); $strResult = $arrWho[1]; } return $strResult; } function loadavg ($bar = false) { $buf = rfts( '/proc/loadavg' ); if( $buf == "ERROR" ) { $results['avg'] = array('N.A.', 'N.A.', 'N.A.'); } else { $results['avg'] = preg_split("/\s/", $buf, 4); unset($results['avg'][3]); // don't need the extra values, only first three } if ($bar) { $buf = rfts( '/proc/stat', 1 ); if( $buf != "ERROR" ) { sscanf($buf, "%*s %Ld %Ld %Ld %Ld", $ab, $ac, $ad, $ae); // Find out the CPU load // user + sys = load // total = total $load = $ab + $ac + $ad; // cpu.user + cpu.sys $total = $ab + $ac + $ad + $ae; // cpu.total // we need a second value, wait 1 second befor getting (< 1 second no good value will occour) sleep(1); $buf = rfts( '/proc/stat', 1 ); sscanf($buf, "%*s %Ld %Ld %Ld %Ld", $ab, $ac, $ad, $ae); $load2 = $ab + $ac + $ad; $total2 = $ab + $ac + $ad + $ae; $results['cpupercent'] = (100*($load2 - $load)) / ($total2 - $total); } } return $results; } function cpu_info () { $bufr = rfts( '/proc/cpuinfo' ); $results = array("cpus" => 0); if ( $bufr != "ERROR" ) { $bufe = explode("\n", $bufr); $results = array('cpus' => 0, 'bogomips' => 0); $ar_buf = array(); foreach( $bufe as $buf ) { $arrBuff = preg_split('/\s+:\s+/', trim($buf)); if( count( $arrBuff ) == 2 ) { $key = $arrBuff[0]; $value = $arrBuff[1]; // All of the tags here are highly architecture dependant. // the only way I could reconstruct them for machines I don't // have is to browse the kernel source. So if your arch isn't // supported, tell me you want it written in. switch ($key) { case 'model name': $results['model'] = $value; break; case 'cpu MHz': $results['cpuspeed'] = sprintf('%.2f', $value); break; case 'cycle frequency [Hz]': // For Alpha arch - 2.2.x $results['cpuspeed'] = sprintf('%.2f', $value / 1000000); break; case 'clock': // For PPC arch (damn borked POS) $results['cpuspeed'] = sprintf('%.2f', $value); break; case 'cpu': // For PPC arch (damn borked POS) $results['model'] = $value; break; case 'L2 cache': // More for PPC $results['cache'] = $value; break; case 'revision': // For PPC arch (damn borked POS) $results['model'] .= ' ( rev: ' . $value . ')'; break; case 'cpu model': // For Alpha arch - 2.2.x $results['model'] .= ' (' . $value . ')'; break; case 'cache size': $results['cache'] = $value; break; case 'bogomips': $results['bogomips'] += $value; break; case 'BogoMIPS': // For alpha arch - 2.2.x $results['bogomips'] += $value; break; case 'BogoMips': // For sparc arch $results['bogomips'] += $value; break; case 'cpus detected': // For Alpha arch - 2.2.x $results['cpus'] += $value; break; case 'system type': // Alpha arch - 2.2.x $results['model'] .= ', ' . $value . ' '; break; case 'platform string': // Alpha arch - 2.2.x $results['model'] .= ' (' . $value . ')'; break; case 'processor': $results['cpus'] += 1; break; case 'Cpu0ClkTck': // Linux sparc64 $results['cpuspeed'] = sprintf('%.2f', hexdec($value) / 1000000); break; case 'Cpu0Bogo': // Linux sparc64 & sparc32 $results['bogomips'] = $value; break; case 'ncpus probed': // Linux sparc64 & sparc32 $results['cpus'] = $value; break; } } } // sparc64 specific code follows // This adds the ability to display the cache that a CPU has // Originally made by Sven Blumenstein <bazik@gentoo.org> in 2004 // Modified by Tom Weustink <freshy98@gmx.net> in 2004 $sparclist = array('SUNW,UltraSPARC@0,0', 'SUNW,UltraSPARC-II@0,0', 'SUNW,UltraSPARC@1c,0', 'SUNW,UltraSPARC-IIi@1c,0', 'SUNW,UltraSPARC-II@1c,0', 'SUNW,UltraSPARC-IIe@0,0'); foreach ($sparclist as $name) { $buf = rfts( '/proc/openprom/' . $name . '/ecache-size',1 , 32, false ); if( $buf != "ERROR" ) { $results['cache'] = base_convert($buf, 16, 10)/1024 . ' KB'; } } // sparc64 specific code ends // XScale detection code if ( $results['cpus'] == 0 ) { foreach( $bufe as $buf ) { $fields = preg_split('/\s*:\s*/', trim($buf), 2); if (sizeof($fields) == 2) { list($key, $value) = $fields; switch($key) { case 'Processor': $results['cpus'] += 1; $results['model'] = $value; break; case 'BogoMIPS': //BogoMIPS are not BogoMIPS on this CPU, it's the speed, no BogoMIPS available $results['cpuspeed'] = $value; break; case 'I size': $results['cache'] = $value; break; case 'D size': $results['cache'] += $value; break; } } } $results['cache'] = $results['cache'] / 1024 . " KB"; } } $keys = array_keys($results); $keys2be = array('model', 'cpuspeed', 'cache', 'bogomips', 'cpus'); while ($ar_buf = each($keys2be)) { if (! in_array($ar_buf[1], $keys)) { $results[$ar_buf[1]] = 'N.A.'; } } $buf = rfts( '/proc/acpi/thermal_zone/THRM/temperature', 1, 4096, false ); if ( $buf != "ERROR" ) { $results['temp'] = substr( $buf, 25, 2 ); } return $results; } function pci () { $arrResults = array(); $booDevice = false; if( ! $arrResults = $this->parser->parse_lspci() ) { $strBuf = rfts( '/proc/pci', 0, 4096, false ); if( $strBuf != "ERROR" ) { $arrBuf = explode( "\n", $strBuf ); foreach( $arrBuf as $strLine ) { if( preg_match( '/Bus/', $strLine ) ) { $booDevice = true; continue; } if( $booDevice ) { list( $strKey, $strValue ) = preg_split('/: /', $strLine, 2 ); if( ! preg_match( '/bridge/i', $strKey ) && ! preg_match( '/USB/i ', $strKey ) ) { $arrResults[] = preg_replace( '/\([^\)]+\)\.$/', '', trim( $strValue ) ); } $booDevice = false; } } asort( $arrResults ); } } return $arrResults; } function ide () { $results = array(); $bufd = gdc( '/proc/ide', false ); foreach( $bufd as $file ) { if (preg_match('/^hd/', $file)) { $results[$file] = array(); $buf = rfts("/proc/ide/" . $file . "/media", 1 ); if ( $buf != "ERROR" ) { $results[$file]['media'] = trim($buf); if ($results[$file]['media'] == 'disk') { $results[$file]['media'] = 'Hard Disk'; $buf = rfts( "/proc/ide/" . $file . "/capacity", 1, 4096, false); if( $buf == "ERROR" ) { $buf = rfts( "/sys/block/" . $file . "/size", 1, 4096, false); } if ( $buf != "ERROR" ) { $results[$file]['capacity'] = trim( $buf ); } } elseif ($results[$file]['media'] == 'cdrom') { $results[$file]['media'] = 'CD-ROM'; unset($results[$file]['capacity']); } } else { unset($results[$file]); } $buf = rfts( "/proc/ide/" . $file . "/model", 1 ); if ( $buf != "ERROR" ) { $results[$file]['model'] = trim( $buf ); if (preg_match('/WDC/', $results[$file]['model'])) { $results[$file]['manufacture'] = 'Western Digital'; } elseif (preg_match('/IBM/', $results[$file]['model'])) { $results[$file]['manufacture'] = 'IBM'; } elseif (preg_match('/FUJITSU/', $results[$file]['model'])) { $results[$file]['manufacture'] = 'Fujitsu'; } else { $results[$file]['manufacture'] = 'Unknown'; } } } } asort($results); return $results; } function scsi () { $results = array(); $dev_vendor = ''; $dev_model = ''; $dev_rev = ''; $dev_type = ''; $s = 1; $get_type = 0; $bufr = execute_program('lsscsi', '-c', false); if( $bufr == "ERROR" ) { $bufr = rfts( '/proc/scsi/scsi', 0, 4096, false); } if ( $bufr != "ERROR" ) { $bufe = explode("\n", $bufr); foreach( $bufe as $buf ) { if (preg_match('/Vendor/', $buf)) { preg_match('/Vendor: (.*) Model: (.*) Rev: (.*)/i', $buf, $dev); list($key, $value) = preg_split('/: /', $buf, 2); $dev_str = $value; $get_type = true; continue; } if ($get_type) { preg_match('/Type:\s+(\S+)/i', $buf, $dev_type); $results[$s]['model'] = "$dev[1] $dev[2] ($dev_type[1])"; $results[$s]['media'] = "Hard Disk"; $s++; $get_type = false; } } } asort($results); return $results; } function usb () { $results = array(); $devnum = -1; $bufr = execute_program('lsusb', '', false); if( $bufr == "ERROR" ) { $bufr = rfts( '/proc/bus/usb/devices', 0, 4096, false ); if ( $bufr != "ERROR" ) { $bufe = explode("\n", $bufr); foreach( $bufe as $buf ) { if (preg_match('/^T/', $buf)) { $devnum += 1; $results[$devnum] = ""; } elseif (preg_match('/^S:/', $buf)) { list($key, $value) = preg_split('/: /', $buf, 2); list($key, $value2) = preg_split('/=/', $value, 2); if (trim($key) != "SerialNumber") { $results[$devnum] .= " " . trim($value2); $devstring = 0; } } } } } else { $bufe = explode( "\n", $bufr ); foreach( $bufe as $buf ) { $device = preg_split("/ /", $buf, 7); if( isset( $device[6] ) && trim( $device[6] ) != "" ) { $results[$devnum++] = trim( $device[6] ); } } } return $results; } function sbus () { $results = array(); $_results[0] = ""; // TODO. Nothing here yet. Move along. $results = $_results; return $results; } function network () { $results = array(); $bufr = rfts( '/proc/net/dev' ); if ( $bufr != "ERROR" ) { $bufe = explode("\n", $bufr); foreach( $bufe as $buf ) { if (preg_match('/:/', $buf)) { list($dev_name, $stats_list) = preg_split('/:/', $buf, 2); $stats = preg_split('/\s+/', trim($stats_list)); $results[$dev_name] = array(); $results[$dev_name]['rx_bytes'] = $stats[0]; $results[$dev_name]['rx_packets'] = $stats[1]; $results[$dev_name]['rx_errs'] = $stats[2]; $results[$dev_name]['rx_drop'] = $stats[3]; $results[$dev_name]['tx_bytes'] = $stats[8]; $results[$dev_name]['tx_packets'] = $stats[9]; $results[$dev_name]['tx_errs'] = $stats[10]; $results[$dev_name]['tx_drop'] = $stats[11]; $results[$dev_name]['errs'] = $stats[2] + $stats[10]; $results[$dev_name]['drop'] = $stats[3] + $stats[11]; } } } return $results; } function memory () { $results['ram'] = array('total' => 0, 'free' => 0, 'used' => 0, 'percent' => 0); $results['swap'] = array('total' => 0, 'free' => 0, 'used' => 0, 'percent' => 0); $results['devswap'] = array(); $bufr = rfts( '/proc/meminfo' ); if ( $bufr != "ERROR" ) { $bufe = explode("\n", $bufr); foreach( $bufe as $buf ) { if (preg_match('/^MemTotal:\s+(.*)\s*kB/i', $buf, $ar_buf)) { $results['ram']['total'] = $ar_buf[1]; } else if (preg_match('/^MemFree:\s+(.*)\s*kB/i', $buf, $ar_buf)) { $results['ram']['free'] = $ar_buf[1]; } else if (preg_match('/^Cached:\s+(.*)\s*kB/i', $buf, $ar_buf)) { $results['ram']['cached'] = $ar_buf[1]; } else if (preg_match('/^Buffers:\s+(.*)\s*kB/i', $buf, $ar_buf)) { $results['ram']['buffers'] = $ar_buf[1]; } } $results['ram']['used'] = $results['ram']['total'] - $results['ram']['free']; $results['ram']['percent'] = round(($results['ram']['used'] * 100) / $results['ram']['total']); // values for splitting memory usage if (isset($results['ram']['cached']) && isset($results['ram']['buffers'])) { $results['ram']['app'] = $results['ram']['used'] - $results['ram']['cached'] - $results['ram']['buffers']; $results['ram']['app_percent'] = round(($results['ram']['app'] * 100) / $results['ram']['total']); $results['ram']['buffers_percent'] = round(($results['ram']['buffers'] * 100) / $results['ram']['total']); $results['ram']['cached_percent'] = round(($results['ram']['cached'] * 100) / $results['ram']['total']); } $bufr = rfts( '/proc/swaps' ); if ( $bufr != "ERROR" ) { $swaps = explode("\n", $bufr); for ($i = 1; $i < (sizeof($swaps)); $i++) { if( trim( $swaps[$i] ) != "" ) { $ar_buf = preg_split('/\s+/', $swaps[$i], 6); $results['devswap'][$i - 1] = array(); $results['devswap'][$i - 1]['dev'] = $ar_buf[0]; $results['devswap'][$i - 1]['total'] = $ar_buf[2]; $results['devswap'][$i - 1]['used'] = $ar_buf[3]; $results['devswap'][$i - 1]['free'] = ($results['devswap'][$i - 1]['total'] - $results['devswap'][$i - 1]['used']); $results['devswap'][$i - 1]['percent'] = round(($ar_buf[3] * 100) / $ar_buf[2]); $results['swap']['total'] += $ar_buf[2]; $results['swap']['used'] += $ar_buf[3]; $results['swap']['free'] = $results['swap']['total'] - $results['swap']['used']; $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']); } } } } return $results; } function filesystems () { return $this->parser->parse_filesystems(); } function distro () { return $this->distro; } function distroicon () { return $this->icon; } } ?>
abdullahalmasum/a2billing-1.9.4-untar
admin/phpsysinfo/includes/os/class.Linux.inc.php
PHP
agpl-3.0
17,928
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.accessiweb22; import java.util.LinkedHashSet; import org.tanaguru.entity.audit.ProcessRemark; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.SourceCodeRemark; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.rules.accessiweb22.test.Aw22RuleImplementationTestCase; import org.tanaguru.rules.keystore.HtmlElementStore; import org.tanaguru.rules.keystore.RemarkMessageStore; /** * Unit test class for the implementation of the rule 8.9.1 of the referential Accessiweb 2.2. * * @author jkowalczyk */ public class Aw22Rule08091Test extends Aw22RuleImplementationTestCase { /** * Default constructor */ public Aw22Rule08091Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.tanaguru.rules.accessiweb22.Aw22Rule08091"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("AW22.Test.8.9.1-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-2Failed-01.html")); getWebResourceMap().put("AW22.Test.8.9.1-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-2Failed-02.html")); getWebResourceMap().put("AW22.Test.8.9.1-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-2Failed-03.html")); getWebResourceMap().put("AW22.Test.8.9.1-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-2Failed-04.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-01.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-02.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-03.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-04.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-05.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-06.html")); getWebResourceMap().put("AW22.Test.8.9.1-3NMI-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "accessiweb22/Aw22Rule08091/AW22.Test.8.9.1-3NMI-07.html")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //---------------------------2Failed-01--------------------------------- //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("AW22.Test.8.9.1-2Failed-01"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); SourceCodeRemark sourceCodeRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(TestSolution.FAILED, sourceCodeRemark.getIssue()); assertEquals(RemarkMessageStore.LINK_WITHOUT_TARGET_MSG, sourceCodeRemark.getMessageCode()); assertEquals(HtmlElementStore.A_ELEMENT, sourceCodeRemark.getTarget()); assertNotNull(sourceCodeRemark.getSnippet()); assertNull(sourceCodeRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------2Failed-02--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-2Failed-02"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); sourceCodeRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(TestSolution.FAILED, sourceCodeRemark.getIssue()); assertEquals(RemarkMessageStore.LINK_WITHOUT_TARGET_MSG, sourceCodeRemark.getMessageCode()); assertEquals(HtmlElementStore.A_ELEMENT, sourceCodeRemark.getTarget()); assertNotNull(sourceCodeRemark.getSnippet()); assertNull(sourceCodeRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------2Failed-03--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-2Failed-03"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); sourceCodeRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(TestSolution.FAILED, sourceCodeRemark.getIssue()); assertEquals(RemarkMessageStore.FIELDSET_NOT_WITHIN_FORM_MSG, sourceCodeRemark.getMessageCode()); assertEquals(HtmlElementStore.FIELDSET_ELEMENT, sourceCodeRemark.getTarget()); assertNotNull(sourceCodeRemark.getSnippet()); assertNull(sourceCodeRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------2Failed-04--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-2Failed-04"); // check number of elements in the page assertEquals(13, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); sourceCodeRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(TestSolution.FAILED, sourceCodeRemark.getIssue()); assertEquals(RemarkMessageStore.FIELDSET_NOT_WITHIN_FORM_MSG, sourceCodeRemark.getMessageCode()); assertEquals(HtmlElementStore.FIELDSET_ELEMENT, sourceCodeRemark.getTarget()); assertNotNull(sourceCodeRemark.getSnippet()); assertNull(sourceCodeRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-03--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-01"); // check number of elements in the page assertEquals(11, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); ProcessRemark processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-02------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-02"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-03------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-03"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-04------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-04"); // check number of elements in the page assertEquals(12, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-05------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-05"); // check number of elements in the page assertEquals(13, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-06------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-06"); // check number of elements in the page assertEquals(13, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); //---------------------------------------------------------------------- //---------------------------3NMI-07------------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("AW22.Test.8.9.1-3NMI-07"); // check number of elements in the page assertEquals(13, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = processResult.getRemarkSet().iterator().next(); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(getMessageKey(RemarkMessageStore.NO_PATTERN_DETECTED_MSG), processRemark.getMessageCode()); assertNull(processRemark.getElementList()); } @Override protected void setConsolidate() { assertEquals(TestSolution.FAILED, consolidate("AW22.Test.8.9.1-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.8.9.1-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.8.9.1-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("AW22.Test.8.9.1-2Failed-04").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-01").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-02").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-03").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-04").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-05").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-06").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("AW22.Test.8.9.1-3NMI-07").getValue()); } /** * * @param msg * @return the message suffixed with the test key identifier */ private String getMessageKey(String msg) { StringBuilder strb = new StringBuilder(msg); strb.append("_"); strb.append(getName()); return strb.toString(); } }
Tanaguru/Tanaguru
rules/accessiweb2.2/src/test/java/org/tanaguru/rules/accessiweb22/Aw22Rule08091Test.java
Java
agpl-3.0
17,246
""" Useful utilities for management commands. """ from django.core.management.base import CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey def get_mutually_exclusive_required_option(options, *selections): """ Validates that exactly one of the 2 given options is specified. Returns the name of the found option. """ selected = [sel for sel in selections if options.get(sel)] if len(selected) != 1: selection_string = ', '.join(f'--{selection}' for selection in selections) raise CommandError(f'Must specify exactly one of {selection_string}') return selected[0] def validate_mutually_exclusive_option(options, option_1, option_2): """ Validates that both of the 2 given options are not specified. """ if options.get(option_1) and options.get(option_2): raise CommandError(f'Both --{option_1} and --{option_2} cannot be specified.') def validate_dependent_option(options, dependent_option, depending_on_option): """ Validates that option_1 is specified if dependent_option is specified. """ if options.get(dependent_option) and not options.get(depending_on_option): raise CommandError(f'Option --{dependent_option} requires option --{depending_on_option}.') def parse_course_keys(course_key_strings): """ Parses and returns a list of CourseKey objects from the given list of course key strings. """ try: return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings] except InvalidKeyError as error: raise CommandError('Invalid key specified: {}'.format(str(error))) # lint-amnesty, pylint: disable=raise-missing-from
eduNEXT/edunext-platform
openedx/core/lib/command_utils.py
Python
agpl-3.0
1,739
require 'rails_helper' RSpec.describe OrganizationsController, type: :controller do fixtures :organizations, :users, :admins, :groups describe '#index' do let(:response) { get :index } let(:organization) { organizations(:singularities)} context 'when it is not authenticated' do it 'returns an unauthenticated response' do expect(response.status).to eq 401 end end context "when logged in as admin" do before { login_user } it "responds successfully" do expect(response).to be_success end it "includes admin's organization" do expect(response.body).to include(organization.name) end end context "when logged in as member" do before { login_user users(:lola) } it "responds successfully" do expect(response).to be_success end it "includes users's organization" do expect(response.body).to include(organization.name) end end context "when logged in as external user" do before { login_user users(:maria) } it "responds successfully" do expect(response).to be_success end it "does not include users's organization" do expect(response.body).not_to include(organization.name) end end end describe '#show' do let(:organization) { o = organizations(:singularities) # Fixtures does not call after_create callbacks o.refresh_token o } let(:params) { { id: organization.id } } let(:response) { get :show, params: params } context 'when it is not authenticated' do it 'returns an unauthenticated response' do expect(response.status).to eq 401 end end context "when logged in as admin" do before { login_user } it "responds successfully" do expect(response).to be_success end it "includes organization's name" do expect(response.body).to include(organization.name) end it "includes author email" do expect(response.body).to include(organizations(:singularities).author.email) end end context "when logged in as member" do before { login_user users(:lola) } it "responds successfully" do expect(response).to be_success end it "includes organization's name" do expect(response.body).to include(organization.name) end end context "when logged in as external user" do before { login_user users(:maria) } it "responds forbidden" do expect(response.status).to be 403 end it "does not include organization's name" do expect(response.body).not_to include(organization.name) end end context "when requesting with organization token" do let(:params) { { id: organization.id, token: organization.token } } it "responds successfully" do expect(response).to be_success end it "includes organization's name" do expect(response.body).to include(organization.name) end end context "when requesting with a different token" do let(:params) { { id: organization.id, token: '123456' } } it 'returns an unauthenticated response' do expect(response.status).to eq 401 end it "does not include organization's name" do expect(response.body).not_to include(organization.name) end end end describe '#create' do let(:response) { post :create, params: organization_data } let(:organization_data) do { data: { attributes: { name: "Testing" } } } end context 'when it is not authenticated' do it 'returns an unauthenticated response' do expect(response.status).to eq 401 end end context 'when the data is invalid' do before { login_user } let(:organization_data) do { data: { attributes: { name: nil } } } end it "responds unsuccessfully" do expect(response).not_to be_success end it 'returns a 422 status' do expect(response.status).to be 422 end end context 'when the data is valid' do before { login_user } context 'with only required parameters' do it "responds successfully" do expect(response).to be_success end it 'creates the organization' do response expect(Organization.find_by(name: "Testing")).not_to be nil end end end end describe '#update' do let(:organization) { organizations(:singularities) } let(:new_name) { 'New Singularities' } let(:organization_data) do { data: { attributes: { name: new_name } } } end let(:response) { patch :update, params: organization_data.merge(id: organization.id) } context "when logged in as admin" do before { login_user } it "responds successfully" do expect(response).to be_success end it "updates the organization" do response expect(Organization.find(organization.id).name).to eq(new_name) end end context "when logged in as other user" do before { login_user users(:lola)} it "responds forbidden" do expect(response.status).to be 403 end it "does not update the organization" do response expect(Organization.find(organization.id).name).not_to eq(new_name) end end end describe '#destroy' do let(:organization) { organizations(:singularities) } let(:response) { delete :destroy, params: { id: organization.id } } context "when logged in as admin" do before { login_user } it "responds successfully" do expect(response).to be_success end it 'destroys the organization' do response expect(Organization.find_by(id: organization.id)).to be nil end end context "when logged in as other user" do before { login_user users(:lola)} it "responds forbidden" do expect(response.status).to be 403 end it 'does not destroy the organization' do response expect(Organization.find_by(id: organization.id)).not_to be nil end end end end
singularities/circular-works
spec/controllers/organizations_controller_spec.rb
Ruby
agpl-3.0
6,527
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * The "devices" collection of methods. * Typical usage is: * <code> * $cloudiotService = new Google_Service_CloudIot(...); * $devices = $cloudiotService->devices; * </code> */ class Google_Service_CloudIot_Resource_ProjectsLocationsRegistriesDevices extends Google_Service_Resource { /** * Creates a device in a device registry. (devices.create) * * @param string $parent Required. The name of the device registry where this * device should be created. For example, `projects/example-project/locations * /us-central1/registries/my-registry`. * @param Google_Service_CloudIot_Device $postBody * @param array $optParams Optional parameters. * @return Google_Service_CloudIot_Device */ public function create($parent, Google_Service_CloudIot_Device $postBody, $optParams = array()) { $params = array('parent' => $parent, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('create', array($params), "Google_Service_CloudIot_Device"); } /** * Deletes a device. (devices.delete) * * @param string $name Required. The name of the device. For example, * `projects/p0/locations/us-central1/registries/registry0/devices/device0` or * `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`. * @param array $optParams Optional parameters. * @return Google_Service_CloudIot_CloudiotEmpty */ public function delete($name, $optParams = array()) { $params = array('name' => $name); $params = array_merge($params, $optParams); return $this->call('delete', array($params), "Google_Service_CloudIot_CloudiotEmpty"); } /** * Gets details about a device. (devices.get) * * @param string $name Required. The name of the device. For example, * `projects/p0/locations/us-central1/registries/registry0/devices/device0` or * `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`. * @param array $optParams Optional parameters. * * @opt_param string fieldMask The fields of the `Device` resource to be * returned in the response. If the field mask is unset or empty, all fields are * returned. * @return Google_Service_CloudIot_Device */ public function get($name, $optParams = array()) { $params = array('name' => $name); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_CloudIot_Device"); } /** * List devices in a device registry. * (devices.listProjectsLocationsRegistriesDevices) * * @param string $parent Required. The device registry path. Required. For * example, `projects/my-project/locations/us-central1/registries/my-registry`. * @param array $optParams Optional parameters. * * @opt_param string deviceIds A list of device string IDs. For example, * `['device0', 'device12']`. If empty, this field is ignored. Maximum IDs: * 10,000 * @opt_param string gatewayListOptions.associationsDeviceId If set, returns * only the gateways with which the specified device is associated. The device * ID can be numeric (`num_id`) or the user-defined string (`id`). For example, * if `456` is specified, returns only the gateways to which the device with * `num_id` 456 is bound. * @opt_param string deviceNumIds A list of device numeric IDs. If empty, this * field is ignored. Maximum IDs: 10,000. * @opt_param string gatewayListOptions.gatewayType If `GATEWAY` is specified, * only gateways are returned. If `NON_GATEWAY` is specified, only non-gateway * devices are returned. If `GATEWAY_TYPE_UNSPECIFIED` is specified, all devices * are returned. * @opt_param string gatewayListOptions.associationsGatewayId If set, only * devices associated with the specified gateway are returned. The gateway ID * can be numeric (`num_id`) or the user-defined string (`id`). For example, if * `123` is specified, only devices bound to the gateway with `num_id` 123 are * returned. * @opt_param string fieldMask The fields of the `Device` resource to be * returned in the response. The fields `id` and `num_id` are always returned, * along with any other fields specified. * @opt_param string pageToken The value returned by the last * `ListDevicesResponse`; indicates that this is a continuation of a prior * `ListDevices` call and the system should return the next page of data. * @opt_param int pageSize The maximum number of devices to return in the * response. If this value is zero, the service will select a default size. A * call may return fewer objects than requested. A non-empty `next_page_token` * in the response indicates that more data is available. * @return Google_Service_CloudIot_ListDevicesResponse */ public function listProjectsLocationsRegistriesDevices($parent, $optParams = array()) { $params = array('parent' => $parent); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_CloudIot_ListDevicesResponse"); } /** * Modifies the configuration for the device, which is eventually sent from the * Cloud IoT Core servers. Returns the modified configuration version and its * metadata. (devices.modifyCloudToDeviceConfig) * * @param string $name Required. The name of the device. For example, * `projects/p0/locations/us-central1/registries/registry0/devices/device0` or * `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`. * @param Google_Service_CloudIot_ModifyCloudToDeviceConfigRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_CloudIot_DeviceConfig */ public function modifyCloudToDeviceConfig($name, Google_Service_CloudIot_ModifyCloudToDeviceConfigRequest $postBody, $optParams = array()) { $params = array('name' => $name, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('modifyCloudToDeviceConfig', array($params), "Google_Service_CloudIot_DeviceConfig"); } /** * Updates a device. (devices.patch) * * @param string $name The resource path name. For example, * `projects/p1/locations/us-central1/registries/registry0/devices/dev0` or * `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. * When `name` is populated as a response from the service, it always ends in * the device numeric ID. * @param Google_Service_CloudIot_Device $postBody * @param array $optParams Optional parameters. * * @opt_param string updateMask Required. Only updates the `device` fields * indicated by this mask. The field mask must not be empty, and it must not * contain fields that are immutable or only set by the server. Mutable top- * level fields: `credentials`, `blocked`, and `metadata` * @return Google_Service_CloudIot_Device */ public function patch($name, Google_Service_CloudIot_Device $postBody, $optParams = array()) { $params = array('name' => $name, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('patch', array($params), "Google_Service_CloudIot_Device"); } /** * Sends a command to the specified device. In order for a device to be able to * receive commands, it must: 1) be connected to Cloud IoT Core using the MQTT * protocol, and 2) be subscribed to the group of MQTT topics specified by * /devices/{device-id}/commands/#. This subscription will receive commands * at the top-level topic /devices/{device-id}/commands as well as commands * for subfolders, like /devices/{device-id}/commands/subfolder. Note that * subscribing to specific subfolders is not supported. If the command could not * be delivered to the device, this method will return an error; in particular, * if the device is not subscribed, this method will return FAILED_PRECONDITION. * Otherwise, this method will return OK. If the subscription is QoS 1, at least * once delivery will be guaranteed; for QoS 0, no acknowledgment will be * expected from the device. (devices.sendCommandToDevice) * * @param string $name Required. The name of the device. For example, * `projects/p0/locations/us-central1/registries/registry0/devices/device0` or * `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`. * @param Google_Service_CloudIot_SendCommandToDeviceRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_CloudIot_SendCommandToDeviceResponse */ public function sendCommandToDevice($name, Google_Service_CloudIot_SendCommandToDeviceRequest $postBody, $optParams = array()) { $params = array('name' => $name, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('sendCommandToDevice', array($params), "Google_Service_CloudIot_SendCommandToDeviceResponse"); } }
Ereza/Fansubs.cat
services/libs/google-api-php-client-2.4.1/vendor/google/apiclient-services/src/Google/Service/CloudIot/Resource/ProjectsLocationsRegistriesDevices.php
PHP
agpl-3.0
9,562
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.reportparamsdialog; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Core"; } public String getFormName() { return "ReportParamsDialog"; } public int getWidth() { return 536; } public int getHeight() { return 440; } public String[] getContextVariables() { return new String[] { "_cv_Core.ImsReportId", "_cv_Admin.ReportSeedParsed" }; } public String getLocalVariablesPrefix() { return "_lv_Core.ReportParamsDialog.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[0]; return componentsInfo; } public String getImagePath() { return "Images/Admin/reports_params_48.png"; } }
openhealthcare/openMAXIMS
openmaxims_workspace/Core/src/ims/core/forms/reportparamsdialog/FormInfo.java
Java
agpl-3.0
2,672
class AddPostMarkdownToPosts < ActiveRecord::Migration def change add_column :posts, :post_markdown, :text end end
crowdAI/crowdai
doc/technical/archived_migrations/20161114141303_add_post_markdown_to_posts.rb
Ruby
agpl-3.0
123
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Neil McAnaspie using IMS Development Environment (version 1.51 build 2480.15886) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.nursing.forms.bradenscaleview; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } }
openhealthcare/openMAXIMS
openmaxims_workspace/Nursing/src/ims/nursing/forms/bradenscaleview/AccessLogic.java
Java
agpl-3.0
2,006
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author George Cristian Josan */ public class DischargeServicesAndAdviceVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.DischargeServicesAndAdviceVo copy(ims.emergency.vo.DischargeServicesAndAdviceVo valueObjectDest, ims.emergency.vo.DischargeServicesAndAdviceVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_DischargeServicesAndAdvice(valueObjectSrc.getID_DischargeServicesAndAdvice()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Patient valueObjectDest.setPatient(valueObjectSrc.getPatient()); // Episode valueObjectDest.setEpisode(valueObjectSrc.getEpisode()); // Attendance valueObjectDest.setAttendance(valueObjectSrc.getAttendance()); // PatientMobility valueObjectDest.setPatientMobility(valueObjectSrc.getPatientMobility()); // TransportArrangedType valueObjectDest.setTransportArrangedType(valueObjectSrc.getTransportArrangedType()); // TransportDateTime valueObjectDest.setTransportDateTime(valueObjectSrc.getTransportDateTime()); // Comments valueObjectDest.setComments(valueObjectSrc.getComments()); // BookingNo valueObjectDest.setBookingNo(valueObjectSrc.getBookingNo()); // SupportNetworkFamily valueObjectDest.setSupportNetworkFamily(valueObjectSrc.getSupportNetworkFamily()); // SupportNetworkProfessionals valueObjectDest.setSupportNetworkProfessionals(valueObjectSrc.getSupportNetworkProfessionals()); // SupportNetworkServices valueObjectDest.setSupportNetworkServices(valueObjectSrc.getSupportNetworkServices()); // Equipment valueObjectDest.setEquipment(valueObjectSrc.getEquipment()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.DischargeServicesAndAdvice objects. */ public static ims.emergency.vo.DischargeServicesAndAdviceVoCollection createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(java.util.Set domainObjectSet) { return createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.DischargeServicesAndAdvice objects. */ public static ims.emergency.vo.DischargeServicesAndAdviceVoCollection createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.DischargeServicesAndAdviceVoCollection voList = new ims.emergency.vo.DischargeServicesAndAdviceVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject = (ims.emergency.domain.objects.DischargeServicesAndAdvice) iterator.next(); ims.emergency.vo.DischargeServicesAndAdviceVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.DischargeServicesAndAdvice objects. */ public static ims.emergency.vo.DischargeServicesAndAdviceVoCollection createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(java.util.List domainObjectList) { return createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.DischargeServicesAndAdvice objects. */ public static ims.emergency.vo.DischargeServicesAndAdviceVoCollection createDischargeServicesAndAdviceVoCollectionFromDischargeServicesAndAdvice(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.DischargeServicesAndAdviceVoCollection voList = new ims.emergency.vo.DischargeServicesAndAdviceVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject = (ims.emergency.domain.objects.DischargeServicesAndAdvice) domainObjectList.get(i); ims.emergency.vo.DischargeServicesAndAdviceVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.DischargeServicesAndAdvice set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractDischargeServicesAndAdviceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVoCollection voCollection) { return extractDischargeServicesAndAdviceSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractDischargeServicesAndAdviceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.DischargeServicesAndAdviceVo vo = voCollection.get(i); ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject = DischargeServicesAndAdviceVoAssembler.extractDischargeServicesAndAdvice(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.DischargeServicesAndAdvice list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractDischargeServicesAndAdviceList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVoCollection voCollection) { return extractDischargeServicesAndAdviceList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractDischargeServicesAndAdviceList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.DischargeServicesAndAdviceVo vo = voCollection.get(i); ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject = DischargeServicesAndAdviceVoAssembler.extractDischargeServicesAndAdvice(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.DischargeServicesAndAdvice object. * @param domainObject ims.emergency.domain.objects.DischargeServicesAndAdvice */ public static ims.emergency.vo.DischargeServicesAndAdviceVo create(ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.DischargeServicesAndAdvice object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.DischargeServicesAndAdviceVo create(DomainObjectMap map, ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.DischargeServicesAndAdviceVo valueObject = (ims.emergency.vo.DischargeServicesAndAdviceVo) map.getValueObject(domainObject, ims.emergency.vo.DischargeServicesAndAdviceVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.DischargeServicesAndAdviceVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.DischargeServicesAndAdvice */ public static ims.emergency.vo.DischargeServicesAndAdviceVo insert(ims.emergency.vo.DischargeServicesAndAdviceVo valueObject, ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.DischargeServicesAndAdvice */ public static ims.emergency.vo.DischargeServicesAndAdviceVo insert(DomainObjectMap map, ims.emergency.vo.DischargeServicesAndAdviceVo valueObject, ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_DischargeServicesAndAdvice(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Patient if (domainObject.getPatient() != null) { if(domainObject.getPatient() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getPatient(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(id, -1)); } else { valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(domainObject.getPatient().getId(), domainObject.getPatient().getVersion())); } } // Episode if (domainObject.getEpisode() != null) { if(domainObject.getEpisode() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getEpisode(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setEpisode(new ims.core.admin.vo.EpisodeOfCareRefVo(id, -1)); } else { valueObject.setEpisode(new ims.core.admin.vo.EpisodeOfCareRefVo(domainObject.getEpisode().getId(), domainObject.getEpisode().getVersion())); } } // Attendance if (domainObject.getAttendance() != null) { if(domainObject.getAttendance() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getAttendance(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setAttendance(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setAttendance(new ims.core.admin.vo.CareContextRefVo(domainObject.getAttendance().getId(), domainObject.getAttendance().getVersion())); } } // PatientMobility java.util.List listPatientMobility = domainObject.getPatientMobility(); ims.core.vo.lookups.PatientMobilityCollection PatientMobility = new ims.core.vo.lookups.PatientMobilityCollection(); for(java.util.Iterator iterator = listPatientMobility.iterator(); iterator.hasNext(); ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; ims.domain.lookups.LookupInstance instance = (ims.domain.lookups.LookupInstance) iterator.next(); if (instance.getImage() != null) { img = new ims.framework.utils.ImagePath(instance.getImage().getImageId(), instance.getImage().getImagePath()); } else { img = null; } color = instance.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.PatientMobility voInstance = new ims.core.vo.lookups.PatientMobility(instance.getId(),instance.getText(), instance.isActive(), null, img, color); ims.core.vo.lookups.PatientMobility parentVoInstance = voInstance; ims.domain.lookups.LookupInstance parent = instance.getParent(); while (parent != null) { if (parent.getImage() != null) { img = new ims.framework.utils.ImagePath(parent.getImage().getImageId(), parent.getImage().getImagePath()); } else { img = null; } color = parent.getColor(); if (color != null) color.getValue(); parentVoInstance.setParent(new ims.core.vo.lookups.PatientMobility(parent.getId(),parent.getText(), parent.isActive(), null, img, color)); parentVoInstance = parentVoInstance.getParent(); parent = parent.getParent(); } PatientMobility.add(voInstance); } valueObject.setPatientMobility( PatientMobility ); // TransportArrangedType ims.domain.lookups.LookupInstance instance5 = domainObject.getTransportArrangedType(); if ( null != instance5 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance5.getImage() != null) { img = new ims.framework.utils.ImagePath(instance5.getImage().getImageId(), instance5.getImage().getImagePath()); } color = instance5.getColor(); if (color != null) color.getValue(); ims.scheduling.vo.lookups.ApptTransportType voLookup5 = new ims.scheduling.vo.lookups.ApptTransportType(instance5.getId(),instance5.getText(), instance5.isActive(), null, img, color); ims.scheduling.vo.lookups.ApptTransportType parentVoLookup5 = voLookup5; ims.domain.lookups.LookupInstance parent5 = instance5.getParent(); while (parent5 != null) { if (parent5.getImage() != null) { img = new ims.framework.utils.ImagePath(parent5.getImage().getImageId(), parent5.getImage().getImagePath() ); } else { img = null; } color = parent5.getColor(); if (color != null) color.getValue(); parentVoLookup5.setParent(new ims.scheduling.vo.lookups.ApptTransportType(parent5.getId(),parent5.getText(), parent5.isActive(), null, img, color)); parentVoLookup5 = parentVoLookup5.getParent(); parent5 = parent5.getParent(); } valueObject.setTransportArrangedType(voLookup5); } // TransportDateTime java.util.Date TransportDateTime = domainObject.getTransportDateTime(); if ( null != TransportDateTime ) { valueObject.setTransportDateTime(new ims.framework.utils.DateTime(TransportDateTime) ); } // Comments valueObject.setComments(domainObject.getComments()); // BookingNo valueObject.setBookingNo(domainObject.getBookingNo()); // SupportNetworkFamily valueObject.setSupportNetworkFamily(ims.core.vo.domain.SupportNetworkFamilyAssembler.createSupportNetworkFamilyCollectionFromSupportNetworkFamily(map, domainObject.getSupportNetworkFamily()) ); // SupportNetworkProfessionals valueObject.setSupportNetworkProfessionals(ims.core.vo.domain.SupportNetworkProfessionalVoAssembler.createSupportNetworkProfessionalVoCollectionFromSupportNetworkProfessional(map, domainObject.getSupportNetworkProfessionals()) ); // SupportNetworkServices valueObject.setSupportNetworkServices(ims.core.vo.domain.SupportNetworkServicesVoAssembler.createSupportNetworkServicesVoCollectionFromSupportNetworkServices(map, domainObject.getSupportNetworkServices()) ); // Equipment java.util.List listEquipment = domainObject.getEquipment(); ims.emergency.vo.lookups.DischargequipmentCollection Equipment = new ims.emergency.vo.lookups.DischargequipmentCollection(); for(java.util.Iterator iterator = listEquipment.iterator(); iterator.hasNext(); ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; ims.domain.lookups.LookupInstance instance = (ims.domain.lookups.LookupInstance) iterator.next(); if (instance.getImage() != null) { img = new ims.framework.utils.ImagePath(instance.getImage().getImageId(), instance.getImage().getImagePath()); } else { img = null; } color = instance.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.Dischargequipment voInstance = new ims.emergency.vo.lookups.Dischargequipment(instance.getId(),instance.getText(), instance.isActive(), null, img, color); ims.emergency.vo.lookups.Dischargequipment parentVoInstance = voInstance; ims.domain.lookups.LookupInstance parent = instance.getParent(); while (parent != null) { if (parent.getImage() != null) { img = new ims.framework.utils.ImagePath(parent.getImage().getImageId(), parent.getImage().getImagePath()); } else { img = null; } color = parent.getColor(); if (color != null) color.getValue(); parentVoInstance.setParent(new ims.emergency.vo.lookups.Dischargequipment(parent.getId(),parent.getText(), parent.isActive(), null, img, color)); parentVoInstance = parentVoInstance.getParent(); parent = parent.getParent(); } Equipment.add(voInstance); } valueObject.setEquipment( Equipment ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.DischargeServicesAndAdvice extractDischargeServicesAndAdvice(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVo valueObject) { return extractDischargeServicesAndAdvice(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.DischargeServicesAndAdvice extractDischargeServicesAndAdvice(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.DischargeServicesAndAdviceVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_DischargeServicesAndAdvice(); ims.emergency.domain.objects.DischargeServicesAndAdvice domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.DischargeServicesAndAdvice)domMap.get(valueObject); } // ims.emergency.vo.DischargeServicesAndAdviceVo ID_DischargeServicesAndAdvice field is unknown domainObject = new ims.emergency.domain.objects.DischargeServicesAndAdvice(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_DischargeServicesAndAdvice()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.DischargeServicesAndAdvice)domMap.get(key); } domainObject = (ims.emergency.domain.objects.DischargeServicesAndAdvice) domainFactory.getDomainObject(ims.emergency.domain.objects.DischargeServicesAndAdvice.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_DischargeServicesAndAdvice()); ims.core.patient.domain.objects.Patient value1 = null; if ( null != valueObject.getPatient() ) { if (valueObject.getPatient().getBoId() == null) { if (domMap.get(valueObject.getPatient()) != null) { value1 = (ims.core.patient.domain.objects.Patient)domMap.get(valueObject.getPatient()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getPatient(); } else { value1 = (ims.core.patient.domain.objects.Patient)domainFactory.getDomainObject(ims.core.patient.domain.objects.Patient.class, valueObject.getPatient().getBoId()); } } domainObject.setPatient(value1); ims.core.admin.domain.objects.EpisodeOfCare value2 = null; if ( null != valueObject.getEpisode() ) { if (valueObject.getEpisode().getBoId() == null) { if (domMap.get(valueObject.getEpisode()) != null) { value2 = (ims.core.admin.domain.objects.EpisodeOfCare)domMap.get(valueObject.getEpisode()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value2 = domainObject.getEpisode(); } else { value2 = (ims.core.admin.domain.objects.EpisodeOfCare)domainFactory.getDomainObject(ims.core.admin.domain.objects.EpisodeOfCare.class, valueObject.getEpisode().getBoId()); } } domainObject.setEpisode(value2); ims.core.admin.domain.objects.CareContext value3 = null; if ( null != valueObject.getAttendance() ) { if (valueObject.getAttendance().getBoId() == null) { if (domMap.get(valueObject.getAttendance()) != null) { value3 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getAttendance()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value3 = domainObject.getAttendance(); } else { value3 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getAttendance().getBoId()); } } domainObject.setAttendance(value3); ims.core.vo.lookups.PatientMobilityCollection collection4 = valueObject.getPatientMobility(); java.util.List domainPatientMobility = domainObject.getPatientMobility();; int collection4Size=0; if (collection4 == null) { domainPatientMobility = new java.util.ArrayList(0); } else { collection4Size = collection4.size(); } for(int i=0; i<collection4Size; i++) { int instanceId = collection4.get(i).getID(); ims.domain.lookups.LookupInstanceRef dom =new ims.domain.lookups.LookupInstanceRef(domainFactory.getLookupInstance(instanceId)); int domIdx = domainPatientMobility.indexOf(dom); if (domIdx == -1) { domainPatientMobility.add(i, dom); } else if (i != domIdx && i < domainPatientMobility.size()) { Object tmp = domainPatientMobility.get(i); domainPatientMobility.set(i, domainPatientMobility.get(domIdx)); domainPatientMobility.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int j4 = domainPatientMobility.size(); while (j4 > collection4Size) { domainPatientMobility.remove(j4-1); j4 = domainPatientMobility.size(); } domainObject.setPatientMobility(domainPatientMobility); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value5 = null; if ( null != valueObject.getTransportArrangedType() ) { value5 = domainFactory.getLookupInstance(valueObject.getTransportArrangedType().getID()); } domainObject.setTransportArrangedType(value5); ims.framework.utils.DateTime dateTime6 = valueObject.getTransportDateTime(); java.util.Date value6 = null; if ( dateTime6 != null ) { value6 = dateTime6.getJavaDate(); } domainObject.setTransportDateTime(value6); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getComments() != null && valueObject.getComments().equals("")) { valueObject.setComments(null); } domainObject.setComments(valueObject.getComments()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getBookingNo() != null && valueObject.getBookingNo().equals("")) { valueObject.setBookingNo(null); } domainObject.setBookingNo(valueObject.getBookingNo()); domainObject.setSupportNetworkFamily(ims.core.vo.domain.SupportNetworkFamilyAssembler.extractSupportNetworkFamilyList(domainFactory, valueObject.getSupportNetworkFamily(), domainObject.getSupportNetworkFamily(), domMap)); domainObject.setSupportNetworkProfessionals(ims.core.vo.domain.SupportNetworkProfessionalVoAssembler.extractSupportNetworkProfessionalList(domainFactory, valueObject.getSupportNetworkProfessionals(), domainObject.getSupportNetworkProfessionals(), domMap)); domainObject.setSupportNetworkServices(ims.core.vo.domain.SupportNetworkServicesVoAssembler.extractSupportNetworkServicesList(domainFactory, valueObject.getSupportNetworkServices(), domainObject.getSupportNetworkServices(), domMap)); ims.emergency.vo.lookups.DischargequipmentCollection collection12 = valueObject.getEquipment(); java.util.List domainEquipment = domainObject.getEquipment();; int collection12Size=0; if (collection12 == null) { domainEquipment = new java.util.ArrayList(0); } else { collection12Size = collection12.size(); } for(int i=0; i<collection12Size; i++) { int instanceId = collection12.get(i).getID(); ims.domain.lookups.LookupInstanceRef dom =new ims.domain.lookups.LookupInstanceRef(domainFactory.getLookupInstance(instanceId)); int domIdx = domainEquipment.indexOf(dom); if (domIdx == -1) { domainEquipment.add(i, dom); } else if (i != domIdx && i < domainEquipment.size()) { Object tmp = domainEquipment.get(i); domainEquipment.set(i, domainEquipment.get(domIdx)); domainEquipment.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int j12 = domainEquipment.size(); while (j12 > collection12Size) { domainEquipment.remove(j12-1); j12 = domainEquipment.size(); } domainObject.setEquipment(domainEquipment); return domainObject; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/DischargeServicesAndAdviceVoAssembler.java
Java
agpl-3.0
33,423
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ /* ScriptData SDName: boss_kri, boss_yauj, boss_vem : The Bug Trio SD%Complete: 100 SDComment: SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" enum Spells { SPELL_CLEAVE = 26350, SPELL_TOXIC_VOLLEY = 25812, SPELL_POISON_CLOUD = 38718, //Only Spell with right dmg. SPELL_ENRAGE = 34624, //Changed cause 25790 is cast on gamers too. Same prob with old explosion of twin emperors. SPELL_CHARGE = 26561, SPELL_KNOCKBACK = 26027, SPELL_HEAL = 25807, SPELL_FEAR = 19408 }; class boss_kri : public CreatureScript { public: boss_kri() : CreatureScript("boss_kri") { } CreatureAI* GetAI(Creature* creature) const { return GetInstanceAI<boss_kriAI>(creature); } struct boss_kriAI : public ScriptedAI { boss_kriAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 Cleave_Timer; uint32 ToxicVolley_Timer; uint32 Check_Timer; bool VemDead; bool Death; void Reset() { Cleave_Timer = urand(4000, 8000); ToxicVolley_Timer = urand(6000, 12000); Check_Timer = 2000; VemDead = false; Death = false; } void EnterCombat(Unit* /*who*/) { } void JustDied(Unit* /*killer*/) { if (instance->GetData(DATA_BUG_TRIO_DEATH) < 2)// Unlootable if death me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); instance->SetData(DATA_BUG_TRIO_DEATH, 1); } void UpdateAI(uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //Cleave_Timer if (Cleave_Timer <= diff) { DoCastVictim(SPELL_CLEAVE); Cleave_Timer = urand(5000, 12000); } else Cleave_Timer -= diff; //ToxicVolley_Timer if (ToxicVolley_Timer <= diff) { DoCastVictim(SPELL_TOXIC_VOLLEY); ToxicVolley_Timer = urand(10000, 15000); } else ToxicVolley_Timer -= diff; if (!HealthAbovePct(5) && !Death) { DoCastVictim(SPELL_POISON_CLOUD); Death = true; } if (!VemDead) { //Checking if Vem is dead. If yes we will enrage. if (Check_Timer <= diff) { if (instance->GetData(DATA_VEMISDEAD)) { DoCast(me, SPELL_ENRAGE); VemDead = true; } Check_Timer = 2000; } else Check_Timer -=diff; } DoMeleeAttackIfReady(); } }; }; class boss_vem : public CreatureScript { public: boss_vem() : CreatureScript("boss_vem") { } CreatureAI* GetAI(Creature* creature) const { return GetInstanceAI<boss_vemAI>(creature); } struct boss_vemAI : public ScriptedAI { boss_vemAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 Charge_Timer; uint32 KnockBack_Timer; uint32 Enrage_Timer; bool Enraged; void Reset() { Charge_Timer = urand(15000, 27000); KnockBack_Timer = urand(8000, 20000); Enrage_Timer = 120000; Enraged = false; } void JustDied(Unit* /*killer*/) { instance->SetData(DATA_VEM_DEATH, 0); if (instance->GetData(DATA_BUG_TRIO_DEATH) < 2)// Unlootable if death me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); instance->SetData(DATA_BUG_TRIO_DEATH, 1); } void EnterCombat(Unit* /*who*/) { } void UpdateAI(uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //Charge_Timer if (Charge_Timer <= diff) { Unit* target = NULL; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) { DoCast(target, SPELL_CHARGE); //me->SendMonsterMove(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, true, 1); AttackStart(target); } Charge_Timer = urand(8000, 16000); } else Charge_Timer -= diff; //KnockBack_Timer if (KnockBack_Timer <= diff) { DoCastVictim(SPELL_KNOCKBACK); if (DoGetThreat(me->GetVictim())) DoModifyThreatPercent(me->GetVictim(), -80); KnockBack_Timer = urand(15000, 25000); } else KnockBack_Timer -= diff; //Enrage_Timer if (!Enraged && Enrage_Timer <= diff) { DoCast(me, SPELL_ENRAGE); Enraged = true; } else Charge_Timer -= diff; DoMeleeAttackIfReady(); } }; }; class boss_yauj : public CreatureScript { public: boss_yauj() : CreatureScript("boss_yauj") { } CreatureAI* GetAI(Creature* creature) const { return GetInstanceAI<boss_yaujAI>(creature); } struct boss_yaujAI : public ScriptedAI { boss_yaujAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; uint32 Heal_Timer; uint32 Fear_Timer; uint32 Check_Timer; bool VemDead; void Reset() { Heal_Timer = urand(25000, 40000); Fear_Timer = urand(12000, 24000); Check_Timer = 2000; VemDead = false; } void JustDied(Unit* /*killer*/) { if (instance->GetData(DATA_BUG_TRIO_DEATH) < 2)// Unlootable if death me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); instance->SetData(DATA_BUG_TRIO_DEATH, 1); for (uint8 i = 0; i < 10; ++i) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { if (Creature* Summoned = me->SummonCreature(15621, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 90000)) Summoned->AI()->AttackStart(target); } } } void EnterCombat(Unit* /*who*/) { } void UpdateAI(uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //Fear_Timer if (Fear_Timer <= diff) { DoCastVictim(SPELL_FEAR); DoResetThreat(); Fear_Timer = 20000; } else Fear_Timer -= diff; //Casting Heal to other twins or herself. if (Heal_Timer <= diff) { switch (urand(0, 2)) { case 0: if (Creature* kri = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_KRI))) DoCast(kri, SPELL_HEAL); break; case 1: if (Creature* vem = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VEM))) DoCast(vem, SPELL_HEAL); break; case 2: DoCast(me, SPELL_HEAL); break; } Heal_Timer = 15000+rand()%15000; } else Heal_Timer -= diff; //Checking if Vem is dead. If yes we will enrage. if (Check_Timer <= diff) { if (!VemDead) { if (instance->GetData(DATA_VEMISDEAD)) { DoCast(me, SPELL_ENRAGE); VemDead = true; } } Check_Timer = 2000; } else Check_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_bug_trio() { new boss_kri(); new boss_vem(); new boss_yauj(); }
DantestyleXD/azerothcore-wotlk
src/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp
C++
agpl-3.0
9,053
using System; using System.Collections; using DatabaseAPI; using UnityEngine; using UnityEngine.UI; using Mirror; using Firebase.Auth; using IgnoranceTransport; namespace Lobby { public class GUI_LobbyDialogue : MonoBehaviour { private const string DefaultServerAddress = "127.0.0.1"; private const ushort DefaultServerPort = 7777; private const string UserNamePlayerPref = "PlayerName"; public GameObject accountLoginPanel; public GameObject createAccountPanel; public GameObject pendingCreationPanel; public GameObject informationPanel; public GameObject wrongVersionPanel; public GameObject controlInformationPanel; public GameObject loggingInPanel; public GameObject connectionPanel; //Account Creation screen: public InputField chosenUsernameInput; public InputField chosenPasswordInput; public InputField emailAddressInput; public GameObject goBackCreationButton; public GameObject nextCreationButton; //Account login: public GameObject loginNextButton; public GameObject loginGoBackButton; public Button resendEmailButton; public InputField serverAddressInput; public InputField serverPortInput; public Text serverConnectionFailedText; public Text dialogueTitle; public Text pleaseWaitCreationText; public Text loggingInText; public Toggle hostServerToggle; public Toggle autoLoginToggle; #region Lifecycle private void Start() { OnHostToggle(); // Init Lobby UI InitPlayerName(); } private void OnEnable() { UpdateManager.Add(CallbackType.UPDATE, UpdateMe); } private void OnDisable() { UpdateManager.Remove(CallbackType.UPDATE, UpdateMe); } private void UpdateMe() { //login skip only allowed (and only works properly) in offline mode if (Input.GetKeyDown(KeyCode.F6) && GameData.Instance.OfflineMode) { //skip login HideAllPanels(); connectionPanel.SetActive(true); dialogueTitle.text = "Connection Panel"; //if there aren't char settings, default if (PlayerManager.CurrentCharacterSettings == null) { PlayerManager.CurrentCharacterSettings = new CharacterSettings(); } } } #endregion public void OnClientDisconnect() { LoadingScreenManager.Instance.CloseLoadingScreen(); gameObject.SetActive(true); ShowConnectionPanel(); StartCoroutine(FlashConnectionFailedText()); } private IEnumerator FlashConnectionFailedText() { serverConnectionFailedText.gameObject.SetActive(true); yield return WaitFor.Seconds(5); serverConnectionFailedText.gameObject.SetActive(false); } public void ShowLoginScreen() { HideAllPanels(); accountLoginPanel.SetActive(true); dialogueTitle.text = "Account Login"; } public void ShowCreationPanel() { _ = SoundManager.Play(CommonSounds.Instance.Click01); HideAllPanels(); createAccountPanel.SetActive(true); dialogueTitle.text = "Create an Account"; } public void ShowCharacterEditor(Action onCloseAction = null) { _ = SoundManager.Play(CommonSounds.Instance.Click01); HideAllPanels(); LobbyManager.Instance.characterCustomization.gameObject.SetActive(true); if (onCloseAction != null) { LobbyManager.Instance.characterCustomization.onCloseAction = onCloseAction; } } public void ShowConnectionPanel() { HideAllPanels(); if (ServerData.Auth.CurrentUser != null) { connectionPanel.SetActive(true); dialogueTitle.text = "Connection Panel"; StartCoroutine(WaitForReloadProfile()); } else { loggingInPanel.SetActive(true); dialogueTitle.text = "Please Wait.."; } } //Make sure we have the latest DisplayName from Auth private IEnumerator WaitForReloadProfile() { ServerData.ReloadProfile(); float timeOutLimit = 60f; float timeOutCount = 0f; while (string.IsNullOrEmpty(ServerData.Auth.CurrentUser.DisplayName)) { timeOutCount += Time.deltaTime; if (timeOutCount >= timeOutLimit) { Logger.LogError("Failed to load users profile data", Category.DatabaseAPI); break; } yield return WaitFor.EndOfFrame; } if (!string.IsNullOrEmpty(ServerData.Auth.CurrentUser.DisplayName)) { dialogueTitle.text = "Logged in: " + ServerData.Auth.CurrentUser.DisplayName; } } public void CreationNextButton() { _ = SoundManager.Play(CommonSounds.Instance.Click01); HideAllPanels(); pendingCreationPanel.SetActive(true); nextCreationButton.SetActive(false); goBackCreationButton.SetActive(false); pleaseWaitCreationText.text = "Please wait.."; ServerData.TryCreateAccount(chosenUsernameInput.text, chosenPasswordInput.text, emailAddressInput.text, AccountCreationSuccess, AccountCreationError); } private void AccountCreationSuccess(CharacterSettings charSettings) { pleaseWaitCreationText.text = $"Success! An email has been sent to {emailAddressInput.text}. " + $"Please click the link in the email to verify " + $"your account before signing in."; PlayerManager.CurrentCharacterSettings = charSettings; GameData.LoggedInUsername = chosenUsernameInput.text; chosenPasswordInput.text = ""; chosenUsernameInput.text = ""; goBackCreationButton.SetActive(true); PlayerPrefs.SetString("lastLogin", emailAddressInput.text); PlayerPrefs.Save(); LobbyManager.Instance.accountLogin.userNameInput.text = emailAddressInput.text; emailAddressInput.text = ""; } private void AccountCreationError(string errorText) { pleaseWaitCreationText.text = errorText; goBackCreationButton.SetActive(true); } public void OnLogin() { _ = SoundManager.Play(CommonSounds.Instance.Click01); PerformLogin(); } public void PerformLogin() { if (!LobbyManager.Instance.accountLogin.ValidLogin()) { return; } ShowLoggingInStatus("Logging in.."); LobbyManager.Instance.accountLogin.TryLogin(LoginSuccess, LoginError); } public void ShowLoggingInStatus(string status) { HideAllPanels(); if (loggingInPanel == null) return; loggingInPanel.SetActive(true); loggingInText.text = status; loginNextButton.SetActive(false); loginGoBackButton.SetActive(false); } public void OnLogout() { _ = SoundManager.Play(CommonSounds.Instance.Click01); HideAllPanels(); ServerData.Auth.SignOut(); NetworkClient.Disconnect(); PlayerPrefs.SetString("username", ""); PlayerPrefs.SetString("cookie", ""); PlayerPrefs.SetInt("autoLogin", 0); PlayerPrefs.Save(); ShowLoginScreen(); } public void OnExit() { _ = SoundManager.Play(CommonSounds.Instance.Click01); Application.Quit(); } public void LoginSuccess(string msg) { loggingInText.text = "Login Success.."; ShowConnectionPanel(); } public void LoginError(string msg) { loggingInText.text = "Login failed: " + msg; if (msg.Contains("Email Not Verified")) { resendEmailButton.gameObject.SetActive(true); resendEmailButton.interactable = true; } else { resendEmailButton.gameObject.SetActive(false); ServerData.Auth.SignOut(); } loginGoBackButton.SetActive(true); } public void OnEmailResend() { resendEmailButton.interactable = false; loggingInText.text = $"A new verification email has been sent to {FirebaseAuth.DefaultInstance.CurrentUser.Email}."; _ = SoundManager.Play(CommonSounds.Instance.Click01); FirebaseAuth.DefaultInstance.CurrentUser.SendEmailVerificationAsync(); FirebaseAuth.DefaultInstance.SignOut(); } public void OnHostToggle() { serverAddressInput.interactable = !hostServerToggle.isOn; serverPortInput.interactable = !hostServerToggle.isOn; } // Button handlers public void OnStartGame() { _ = SoundManager.Play(CommonSounds.Instance.Click01); // Return if no network address is specified if (string.IsNullOrEmpty(serverAddressInput.text)) { return; } // Set and cache player name PlayerPrefs.SetString(UserNamePlayerPref, PlayerManager.CurrentCharacterSettings.Name); // Start game dialogueTitle.text = "Starting Game..."; if (!hostServerToggle.isOn) { ConnectToServer(); } else { LoadingScreenManager.LoadFromLobby(CustomNetworkManager.Instance.StartHost); } // Hide dialogue and show status text gameObject.SetActive(false); // UIManager.Chat.CurrentChannelText.text = "<color=green>Loading game please wait..</color>\r\n"; } public void OnStartGameFromHub() { PlayerPrefs.SetString(UserNamePlayerPref, PlayerManager.CurrentCharacterSettings.Name); ConnectToServer(); gameObject.SetActive(false); } public void OnShowInformationPanel() { _ = SoundManager.Play(CommonSounds.Instance.Click01); ShowInformationPanel(); } public void OnShowControlInformationPanel() { _ = SoundManager.Play(CommonSounds.Instance.Click01); ShowControlInformationPanel(); } public void OnCharacterButton() { ShowCharacterEditor(OnCharacterExit); } private void OnCharacterExit() { gameObject.SetActive(true); if (ServerData.Auth.CurrentUser != null) { ShowConnectionPanel(); } else { Logger.LogWarning("User is not logged in! Returning to login screen.", Category.Connections); ShowLoginScreen(); } } // Game handlers public void ConnectToServer() { LoadingScreenManager.LoadFromLobby(DoServerConnect); } private void DoServerConnect() { // Set network address string serverAddress = serverAddressInput.text; if (string.IsNullOrEmpty(serverAddress)) { serverAddress = DefaultServerAddress; } // Set network port ushort serverPort = DefaultServerPort; if (serverPortInput.text.Length >= 4) { ushort.TryParse(serverPortInput.text, out serverPort); } // Init network client Logger.LogFormat("Client trying to connect to {0}:{1}", Category.Connections, serverAddress, serverPort); CustomNetworkManager.Instance.networkAddress = serverAddress; var telepathy = CustomNetworkManager.Instance.GetComponent<TelepathyTransport>(); if (telepathy != null) { telepathy.port = serverPort; } var ignorance = CustomNetworkManager.Instance.GetComponent<Ignorance>(); if (ignorance != null) { ignorance.port = serverPort; } // var booster = CustomNetworkManager.Instance.GetComponent<BoosterTransport>(); // if (booster != null) // { // booster.port = serverPort; // } CustomNetworkManager.Instance.StartClient(); } private void InitPlayerName() { string steamName = ""; string prefsName; if (!string.IsNullOrEmpty(steamName)) { prefsName = steamName; } else { prefsName = PlayerPrefs.GetString(UserNamePlayerPref); } if (!string.IsNullOrEmpty(prefsName)) { //FIXME // playerNameInput.text = prefsName; } } private void ShowInformationPanel() { HideAllPanels(); informationPanel.SetActive(true); } private void ShowControlInformationPanel() { HideAllPanels(); controlInformationPanel.SetActive(true); } private void ShowWrongVersionPanel() { HideAllPanels(); wrongVersionPanel.SetActive(true); } public void HideAllPanels() { // TODO: FIXME // startGamePanel.SetActive(false); if (accountLoginPanel != null) { accountLoginPanel.SetActive(false); } if (createAccountPanel != null) { createAccountPanel.SetActive(false); } if (pendingCreationPanel != null) { pendingCreationPanel.SetActive(false); } if (informationPanel != null) { informationPanel.SetActive(false); } if (controlInformationPanel != null) { controlInformationPanel.SetActive(false); } if (loggingInPanel != null) { loggingInPanel.SetActive(false); } if (connectionPanel != null) { connectionPanel.SetActive(false); } } } }
unitystation/unitystation
UnityProject/Assets/Scripts/UI/Systems/Lobby/GUI_LobbyDialogue.cs
C#
agpl-3.0
11,881
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default)
CLVsol/odoo_addons
clv_insured/seq/clv_insured_seq.py
Python
agpl-3.0
3,732
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ /* ScriptData SDName: Instance_Molten_Core SD%Complete: 0 SDComment: Place Holder SDCategory: Molten Core EndScriptData */ #include "ObjectMgr.h" #include "ScriptMgr.h" #include "InstanceScript.h" #include "CreatureAI.h" #include "molten_core.h" #include "TemporarySummon.h" Position const SummonPositions[10] = { {737.850f, -1145.35f, -120.288f, 4.71368f}, {744.162f, -1151.63f, -119.726f, 4.58204f}, {751.247f, -1152.82f, -119.744f, 4.49673f}, {759.206f, -1155.09f, -120.051f, 4.30104f}, {755.973f, -1152.33f, -120.029f, 4.25588f}, {731.712f, -1147.56f, -120.195f, 4.95955f}, {726.499f, -1149.80f, -120.156f, 5.24055f}, {722.408f, -1152.41f, -120.029f, 5.33087f}, {718.994f, -1156.36f, -119.805f, 5.75738f}, {838.510f, -829.840f, -232.000f, 2.00000f}, }; class instance_molten_core : public InstanceMapScript { public: instance_molten_core() : InstanceMapScript("instance_molten_core", 409) { } struct instance_molten_core_InstanceMapScript : public InstanceScript { instance_molten_core_InstanceMapScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTER); _golemaggTheIncineratorGUID = 0; _majordomoExecutusGUID = 0; _cacheOfTheFirelordGUID = 0; _executusSchedule = NULL; _deadBossCount = 0; _ragnarosAddDeaths = 0; _isLoading = false; _summonedExecutus = false; } ~instance_molten_core_InstanceMapScript() { delete _executusSchedule; } void OnPlayerEnter(Player* /*player*/) { if (_executusSchedule) { SummonMajordomoExecutus(*_executusSchedule); delete _executusSchedule; _executusSchedule = NULL; } } void OnCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { case NPC_GOLEMAGG_THE_INCINERATOR: _golemaggTheIncineratorGUID = creature->GetGUID(); break; case NPC_MAJORDOMO_EXECUTUS: _majordomoExecutusGUID = creature->GetGUID(); break; default: break; } } void OnGameObjectCreate(GameObject* go) { switch (go->GetEntry()) { case GO_CACHE_OF_THE_FIRELORD: _cacheOfTheFirelordGUID = go->GetGUID(); break; default: break; } } void SetData(uint32 type, uint32 data) { if (type == DATA_RAGNAROS_ADDS) { if (data == 1) ++_ragnarosAddDeaths; else if (data == 0) _ragnarosAddDeaths = 0; } } uint32 GetData(uint32 type) const { switch (type) { case DATA_RAGNAROS_ADDS: return _ragnarosAddDeaths; } return 0; } uint64 GetData64(uint32 type) const { switch (type) { case BOSS_GOLEMAGG_THE_INCINERATOR: return _golemaggTheIncineratorGUID; case BOSS_MAJORDOMO_EXECUTUS: return _majordomoExecutusGUID; } return 0; } bool SetBossState(uint32 bossId, EncounterState state) { if (!InstanceScript::SetBossState(bossId, state)) return false; if (state == DONE && bossId < BOSS_MAJORDOMO_EXECUTUS) ++_deadBossCount; if (_isLoading) return true; if (_deadBossCount == 8) SummonMajordomoExecutus(false); if (bossId == BOSS_MAJORDOMO_EXECUTUS && state == DONE) DoRespawnGameObject(_cacheOfTheFirelordGUID, 7 * DAY); return true; } void SummonMajordomoExecutus(bool done) { if (_summonedExecutus) return; _summonedExecutus = true; if (!done) { instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, SummonPositions[0]); instance->SummonCreature(NPC_FLAMEWAKER_HEALER, SummonPositions[1]); instance->SummonCreature(NPC_FLAMEWAKER_HEALER, SummonPositions[2]); instance->SummonCreature(NPC_FLAMEWAKER_HEALER, SummonPositions[3]); instance->SummonCreature(NPC_FLAMEWAKER_HEALER, SummonPositions[4]); instance->SummonCreature(NPC_FLAMEWAKER_ELITE, SummonPositions[5]); instance->SummonCreature(NPC_FLAMEWAKER_ELITE, SummonPositions[6]); instance->SummonCreature(NPC_FLAMEWAKER_ELITE, SummonPositions[7]); instance->SummonCreature(NPC_FLAMEWAKER_ELITE, SummonPositions[8]); } else if (TempSummon* summon = instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, RagnarosTelePos)) summon->AI()->DoAction(ACTION_START_RAGNAROS_ALT); } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "M C " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(char const* data) { if (!data) { OUT_LOAD_INST_DATA_FAIL; return; } _isLoading = true; OUT_LOAD_INST_DATA(data); char dataHead1, dataHead2; std::istringstream loadStream(data); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'M' && dataHead2 == 'C') { EncounterState states[MAX_ENCOUNTER]; uint8 executusCounter = 0; // need 2 loops to check spawning executus/ragnaros for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > TO_BE_DECIDED) tmpState = NOT_STARTED; states[i] = EncounterState(tmpState); if (tmpState == DONE && i < BOSS_MAJORDOMO_EXECUTUS) ++executusCounter; } if (executusCounter >= 8 && states[BOSS_RAGNAROS] != DONE) _executusSchedule = new bool(states[BOSS_MAJORDOMO_EXECUTUS] == DONE); for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) SetBossState(i, states[i]); } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; _isLoading = false; } private: uint64 _golemaggTheIncineratorGUID; uint64 _majordomoExecutusGUID; uint64 _cacheOfTheFirelordGUID; bool* _executusSchedule; uint8 _deadBossCount; uint8 _ragnarosAddDeaths; bool _isLoading; bool _summonedExecutus; }; InstanceScript* GetInstanceScript(InstanceMap* map) const { return new instance_molten_core_InstanceMapScript(map); } }; void AddSC_instance_molten_core() { new instance_molten_core(); }
DantestyleXD/azerothcore-wotlk
src/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp
C++
agpl-3.0
8,560
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "cesdkhandler.h" #include <utils/environment.h> #include <QtCore/QFile> #include <QtCore/QDebug> #include <QtCore/QXmlStreamReader> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; using Utils::Environment; CeSdkInfo::CeSdkInfo() : m_major(0), m_minor(0) { } void CeSdkInfo::addToEnvironment(Environment &env) { qDebug() << "adding " << name() << "to Environment"; env.set("INCLUDE", m_include); env.set("LIB", m_lib); env.prependOrSetPath(m_bin); } CeSdkHandler::CeSdkHandler() { } bool CeSdkHandler::parse(const QString &vsdir) { // look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config // and scan through all installed sdks... m_list.clear(); VCInstallDir = vsdir; QDir vStudioDir(VCInstallDir); if (!vStudioDir.cd("vcpackages")) return false; QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config"))); qDebug()<<"##"; if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly)) return false; qDebug()<<"parsing"; QString currentElement; CeSdkInfo currentItem; QXmlStreamReader xml(&configFile); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentElement = xml.name().toString(); if (currentElement == QLatin1String("Platform")) currentItem = CeSdkInfo(); else if (currentElement == QLatin1String("Directories")) { QXmlStreamAttributes attr = xml.attributes(); currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString()); currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString()); currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString()); } } else if (xml.isEndElement()) { if (xml.name().toString() == QLatin1String("Platform")) m_list.append(currentItem); } else if (xml.isCharacters() && !xml.isWhitespace()) { if (currentElement == QLatin1String("PlatformName")) currentItem.m_name = xml.text().toString(); else if (currentElement == QLatin1String("OSMajorVersion")) currentItem.m_major = xml.text().toString().toInt(); else if (currentElement == QLatin1String("OSMinorVersion")) currentItem.m_minor = xml.text().toString().toInt(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning("CeSdkHandler::parse(): XML ERROR: %d : %s", int(xml.lineNumber()), qPrintable(xml.errorString())); return false; } return m_list.size() > 0 ? true : false; } CeSdkInfo CeSdkHandler::find(const QString &name) { qDebug() << "looking for platform " << name; for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) { qDebug() << "...." << it->name(); if (it->name() == name) return *it; } return CeSdkInfo(); }
yinyunqiao/qtcreator
src/plugins/projectexplorer/cesdkhandler.cpp
C++
lgpl-2.1
4,476
package org.herac.tuxguitar.ui.jfx.resource; import java.util.HashMap; import java.util.Map; import javafx.scene.Cursor; import org.herac.tuxguitar.ui.resource.UICursor; public class JFXCursor { private static final Map<UICursor, Cursor> CURSOR_MAP = JFXCursor.createCursorMap(); private JFXCursor() { super(); } private static Map<UICursor, Cursor> createCursorMap() { Map<UICursor, Cursor> cursorMap = new HashMap<UICursor, Cursor>(); cursorMap.put(UICursor.NORMAL, Cursor.DEFAULT); cursorMap.put(UICursor.WAIT, Cursor.WAIT); cursorMap.put(UICursor.HAND, Cursor.HAND); cursorMap.put(UICursor.SIZEWE, Cursor.H_RESIZE); cursorMap.put(UICursor.SIZENS, Cursor.V_RESIZE); return cursorMap; } public static Cursor getCursor(UICursor cursor) { return CURSOR_MAP.get(cursor); } }
halfspiral/tuxguitar
TuxGuitar-ui-toolkit-jfx/src/org/herac/tuxguitar/ui/jfx/resource/JFXCursor.java
Java
lgpl-2.1
811
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "tennisserver.h" #include "tennis.h" #include <qbluetoothserver.h> #include <qbluetoothsocket.h> #include <QDebug> TennisServer::TennisServer(QObject *parent) : QObject(parent), l2capServer(0), clientSocket(0), stream(0), lagReplyTimeout(0) { elapsed.start(); ballElapsed.start(); lagTimer.setInterval(1000); connect(&lagTimer, SIGNAL(timeout()), this, SLOT(sendEcho())); } TennisServer::~TennisServer() { if (stream){ QByteArray b; QDataStream s(&b, QIODevice::WriteOnly); s << QString("D"); clientSocket->write(b); } stopServer(); } void TennisServer::startServer() { if (l2capServer) return; //! [Create the server] l2capServer = new QBluetoothServer(QBluetoothServiceInfo::L2capProtocol, this); connect(l2capServer, SIGNAL(newConnection()), this, SLOT(clientConnected())); l2capServer->listen(); //! [Create the server] serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010); //! [Class ServiceClass must contain at least 1 entry] QBluetoothServiceInfo::Sequence classId; // classId << QVariant::fromValue(QBluetoothUuid(serviceUuid)); classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort)); serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId); //! [Class ServiceClass must contain at least 1 entry] //! [Service name, description and provider] serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Example Tennis Server")); serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription, tr("Example bluetooth tennis server")); serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("Nokia, QtDF")); //! [Service name, description and provider] //! [Service UUID set] serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid)); //! [Service UUID set] //! [Service Discoverability] serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList, QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup)); //! [Service Discoverability] //! [Protocol descriptor list] QBluetoothServiceInfo::Sequence protocolDescriptorList; QBluetoothServiceInfo::Sequence protocol; protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap)) << QVariant::fromValue(quint16(l2capServer->serverPort())); protocolDescriptorList.append(QVariant::fromValue(protocol)); serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, protocolDescriptorList); //! [Protocol descriptor list] //! [Register service] serviceInfo.registerService(); //! [Register service] } //! [stopServer] void TennisServer::stopServer() { qDebug() <<Q_FUNC_INFO; // Unregister service serviceInfo.unregisterService(); delete stream; stream = 0; // Close sockets delete clientSocket; clientSocket = 0; // Close server delete l2capServer; l2capServer = 0; } //! [stopServer] quint16 TennisServer::serverPort() const { return l2capServer->serverPort(); } //! [moveBall] void TennisServer::moveBall(int x, int y) { int msec = ballElapsed.elapsed(); if (stream && msec > 30){ QByteArray b; QDataStream s(&b, QIODevice::WriteOnly); s << QString("m %1 %2").arg(x).arg(y); //s << QLatin1String("m") << x << y; clientSocket->write(b); ballElapsed.restart(); } } //! [moveBall] void TennisServer::score(int left, int right) { if (stream){ QByteArray b; QDataStream s(&b, QIODevice::WriteOnly); s << QString("s %1 %2").arg(left).arg(right); // s << QChar('s') << left << right; clientSocket->write(b); } } void TennisServer::moveLeftPaddle(int y) { int msec = elapsed.elapsed(); if (stream && msec > 50) { QByteArray b; QDataStream s(&b, QIODevice::WriteOnly); s << QString("l %1").arg(y); // s << QChar('l') << y; clientSocket->write(b); elapsed.restart(); } } void TennisServer::readSocket() { if (!clientSocket) return; while (clientSocket->bytesAvailable()) { QString str; *stream >> str; QStringList args = str.split(QChar(' ')); QString s = args.takeFirst(); if (s == "r" && args.count() == 1){ emit moveRightPaddle(args.at(0).toInt()); } else if (s == "e" && args.count() == 1){ lagReplyTimeout = 0; QTime then = QTime::fromString(args.at(0), "hh:mm:ss.zzz"); if (then.isValid()) { emit lag(then.msecsTo(QTime::currentTime())); // qDebug() << "RTT: " << then.msecsTo(QTime::currentTime()) << "ms"; } } else if (s == "E"){ QByteArray b; QDataStream st(&b, QIODevice::WriteOnly); st << str; clientSocket->write(b); } else if (s == "D"){ qDebug() << Q_FUNC_INFO << "closing!"; clientSocket->deleteLater(); clientSocket = 0; } else { qDebug() << Q_FUNC_INFO << "Unknown command" << str; } } } //! [clientConnected] void TennisServer::clientConnected() { qDebug() << Q_FUNC_INFO << "connect"; QBluetoothSocket *socket = l2capServer->nextPendingConnection(); if (!socket) return; if (clientSocket){ qDebug() << Q_FUNC_INFO << "Closing socket!"; delete socket; return; } connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(socketError(QBluetoothSocket::SocketError))); stream = new QDataStream(socket); clientSocket = socket; qDebug() << Q_FUNC_INFO << "started"; emit clientConnected(clientSocket->peerName()); lagTimer.start(); } //! [clientConnected] void TennisServer::socketError(QBluetoothSocket::SocketError err) { qDebug() << Q_FUNC_INFO << err; } //! [sendEcho] void TennisServer::sendEcho() { if (lagReplyTimeout) { lagReplyTimeout--; return; } if (stream) { QByteArray b; QDataStream s(&b, QIODevice::WriteOnly); s << QString("e %1").arg(QTime::currentTime().toString("hh:mm:ss.zzz")); clientSocket->write(b); lagReplyTimeout = 10; } } //! [sendEcho] //! [clientDisconnected] void TennisServer::clientDisconnected() { qDebug() << Q_FUNC_INFO << "client closing!"; lagTimer.stop(); lagReplyTimeout = 0; QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender()); if (!socket) return; emit clientDisconnected(socket->peerName()); clientSocket->deleteLater(); clientSocket = 0; delete stream; stream = 0; // socket->deleteLater(); } //! [clientDisconnected]
CodeDJ/qt5-hidpi
qt/qtconnectivity/examples/bluetooth/bttennis/tennisserver.cpp
C++
lgpl-2.1
9,054
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: tiki-view_tracker.php 48122 2013-10-20 22:07:01Z nkoth $ $section = 'trackers'; require_once ('tiki-setup.php'); $access->check_feature('feature_trackers'); global $trklib; include_once ('lib/trackers/trackerlib.php'); if ($prefs['feature_groupalert'] == 'y') { include_once ('lib/groupalert/groupalertlib.php'); } include_once ('lib/notifications/notificationlib.php'); if ($prefs['feature_categories'] == 'y') { include_once ('lib/categories/categlib.php'); } $auto_query_args = array( 'offset', 'trackerId', 'reloff', 'itemId', 'maxRecords', 'status', 'sort_mode', 'initial', 'filterfield', 'filtervalue' ); if (!empty($_REQUEST['itemId'])) $ratedItemId = $_REQUEST['itemId']; $_REQUEST["itemId"] = 0; $smarty->assign('itemId', $_REQUEST["itemId"]); if (!isset($_REQUEST["trackerId"])) { $smarty->assign('msg', tra("No tracker indicated")); $smarty->display("error.tpl"); die; } $trackerDefinition = Tracker_Definition::get($_REQUEST['trackerId']); if (! $trackerDefinition) { $smarty->assign('msg', tra("No tracker indicated")); $smarty->display("error.tpl"); die; } $tracker_info = $trackerDefinition->getInformation(); $tikilib->get_perm_object($_REQUEST['trackerId'], 'tracker', $tracker_info); if (!empty($_REQUEST['show']) && $_REQUEST['show'] == 'view') { $cookietab = '1'; } elseif (!empty($_REQUEST['show']) && $_REQUEST['show'] == 'mod') { $cookietab = '2'; } elseif (empty($_REQUEST['cookietab'])) { if (isset($tracker_info['writerCanModify']) && $tracker_info['writerCanModify'] == 'y' && $user) $cookietab = '1'; elseif (!($tiki_p_view_trackers == 'y' || $tiki_p_admin == 'y' || $tiki_p_admin_trackers == 'y') && $tiki_p_create_tracker_items == 'y') $cookietab = "2"; else if (!isset($cookietab)) { $cookietab = '1'; } } else { $cookietab = $_REQUEST['cookietab']; } $defaultvalues = array(); if (isset($_REQUEST['vals']) and is_array($_REQUEST['vals'])) { $defaultvalues = $_REQUEST['vals']; $cookietab = "2"; } elseif (isset($_REQUEST['new'])) { $cookietab = "2"; } $smarty->assign('defaultvalues', $defaultvalues); $my = ''; $ours = ''; if (isset($_REQUEST['my'])) { if ($tiki_p_admin_trackers == 'y') { $my = $_REQUEST['my']; } elseif ($user) { $my = $user; } } elseif (isset($_REQUEST['ours'])) { if ($tiki_p_admin_trackers == 'y') { $ours = $_REQUEST['ours']; } elseif ($group) { $ours = $group; } } if ($tiki_p_create_tracker_items == 'y' && !empty($t['start'])) { if ($tikilib->now < $t['start']) { $tiki_p_create_tracker_items = 'n'; $smarty->assign('tiki_p_create_tracker_items', 'n'); } } if ($tiki_p_create_tracker_items == 'y' && !empty($t['end'])) { if ($tikilib->now > $t['end']) { $tiki_p_create_tracker_items = 'n'; $smarty->assign('tiki_p_create_tracker_items', 'n'); } } $access->check_permission_either(array('tiki_p_view_trackers', 'tiki_p_create_tracker_items')); if ($tracker_info['adminOnlyViewEditItem'] === 'y') { $access->check_permission('tiki_p_admin_trackers', tra('Admin this tracker'), 'tracker', $tracker_info['trackerId']); } if ($tiki_p_view_trackers != 'y') { $userCreatorFieldId = $writerfield; $groupCreatorFieldId = $writergroupfield; if ($user && !$my and isset($tracker_info['writerCanModify']) and $tracker_info['writerCanModify'] == 'y' and !empty($userCreatorFieldId)) { $my = $user; } elseif ($user && !$ours and isset($tracker_info['writerGroupCanModify']) and $tracker_info['writerGroupCanModify'] == 'y' and !empty($groupCreatorFieldId)) { $ours = $group; } } $smarty->assign('my', $my); $smarty->assign('ours', $ours); if ($prefs['feature_groupalert'] == 'y') { $groupforalert = $groupalertlib->GetGroup('tracker', $_REQUEST['trackerId']); if ($groupforalert != '') { $showeachuser = $groupalertlib->GetShowEachUser('tracker', $_REQUEST["trackerId"], $groupforalert); $listusertoalert = $userlib->get_users(0, -1, 'login_asc', '', '', false, $groupforalert, ''); $smarty->assign_by_ref('listusertoalert', $listusertoalert['data']); } $smarty->assign_by_ref('groupforalert', $groupforalert); $smarty->assign_by_ref('showeachuser', $showeachuser); } $status_types = array(); $status_raw = $trklib->status_types(); if (isset($_REQUEST['status'])) { $sts = preg_split('//', $_REQUEST['status'], -1, PREG_SPLIT_NO_EMPTY); } elseif (isset($tracker_info["defaultStatus"])) { $sts = preg_split('//', $tracker_info["defaultStatus"], -1, PREG_SPLIT_NO_EMPTY); $_REQUEST['status'] = $tracker_info["defaultStatus"]; } else { $sts = array( 'o' ); $_REQUEST['status'] = 'o'; } foreach ($status_raw as $let => $sta) { if ((isset($$sta['perm']) and $$sta['perm'] == 'y') or ($my or $ours)) { if (in_array($let, $sts)) { $sta['class'] = 'statuson'; $sta['statuslink'] = str_replace($let, '', implode('', $sts)); } else { $sta['class'] = 'statusoff'; $sta['statuslink'] = implode('', $sts) . $let; } $status_types["$let"] = $sta; } } $smarty->assign('status_types', $status_types); if (count($status_types) == 0) { $tracker_info["showStatus"] = 'n'; } $filterFields = array('isSearchable'=>'y', 'isTblVisible'=>'y', 'type'=>array('q','u','g','I','C','n','j','f')); $sort_field = 0; if (!isset($_REQUEST["sort_mode"])) { if (isset($tracker_info['defaultOrderKey'])) { if ($tracker_info['defaultOrderKey'] == - 1) $sort_mode = 'lastModif'; elseif ($tracker_info['defaultOrderKey'] == - 2) $sort_mode = 'created'; elseif ($tracker_info['defaultOrderKey'] == - 3) $sort_mode = 'itemId'; else { $sort_field = $tracker_info['defaultOrderKey']; $sort_mode = 'f_' . $tracker_info['defaultOrderKey']; $filterFields['fieldId'] = $tracker_info['defaultOrderKey']; } if (isset($tracker_info['defaultOrderDir'])) { $sort_mode.= "_" . $tracker_info['defaultOrderDir']; } else { $sort_mode.= "_asc"; } } else { $sort_mode = ''; } } else { $sort_mode = $_REQUEST["sort_mode"]; if (preg_match('/f_([0-9]+)_/', $sort_mode, $matches)) { $sort_field = $matches[1]; $filterFields['fieldId'] = $matches[1]; } } $smarty->assign_by_ref('sort_mode', $sort_mode); //get field settings (no values) $xfields = array('data' => $trackerDefinition->getFields()); $popupFields = $trackerDefinition->getPopupFields(); $smarty->assign_by_ref('popupFields', $popupFields); $smarty->assign('tracker_sync', $trackerDefinition->getSyncInformation()); $orderkey = false; $listfields = array(); $usecategs = false; $textarea_options = false; $all_descends = false; $fieldFactory = $trackerDefinition->getFieldFactory(); $itemObject = Tracker_Item::newItem($_REQUEST['trackerId']); foreach ($xfields['data'] as $i => $current_field) { $current_field_ins = null; $fid = $current_field["fieldId"]; $ins_id = 'ins_' . $fid; $current_field["ins_id"] = $ins_id; $current_field["id"] = $fid; $filter_id = 'filter_' . $fid; $current_field["filter_id"] = $filter_id; if (!empty($sort_field) and $sort_field == $fid) { $orderkey = true; } $fieldIsVisible = $itemObject->canViewField($fid); $fieldIsEditable = $itemObject->canModifyField($fid); if ($fieldIsVisible || $fieldIsEditable) { $handler = $fieldFactory->getHandler($current_field); if ($handler) { $field_values = $insert_values = $handler->getFieldData($_REQUEST); $current_field_ins = array_merge($current_field, $insert_values); } } //exclude fields that should not be listed if ($fieldIsVisible && ($current_field_ins['isTblVisible'] == 'y' or in_array($fid, $popupFields))) { $listfields[$fid] = $current_field_ins; } if (! empty($current_field_ins)) { if ($fieldIsEditable) { $ins_fields['data'][$i] = $current_field_ins; } if ($fieldIsVisible) { $fields['data'][$i] = $current_field_ins; } } if ($fieldIsEditable) { $listfields[$fid]['editable'] = true; } else { $listfields[$fid]['editable'] = false; } } // Collect information from the provided fields $newItemRateField = null; foreach ($ins_fields['data'] as $current_field) { if ($current_field['type'] == 's' && $current_field['name'] == 'Rating') { $newItemRateField = $current_field; $newItemRate = $current_field['request_rate']; } } if (!$orderkey && $sort_mode == '') { $sort_mode = 'lastModif_asc'; } if (!empty($_REQUEST['remove'])) { $item_info = $trklib->get_item_info($_REQUEST['remove']); $actionObject = Tracker_Item::fromInfo($item_info); if ($actionObject->canRemove()) { //bypass the question to confirm delete or not if (empty($_REQUEST['force'])) { $access->check_authenticity(); $trklib->remove_tracker_item($_REQUEST['remove']); } } } elseif (isset($_REQUEST["batchaction"]) and $_REQUEST["batchaction"] == 'delete') { check_ticket('view-trackers'); $transaction = $tikilib->begin(); foreach ($_REQUEST['action'] as $batchid) { $item_info = $trklib->get_item_info($batchid); $actionObject = Tracker_Item::fromInfo($item_info); if ($actionObject->canRemove()) { $trklib->remove_tracker_item($batchid); } } $transaction->commit(); } elseif (isset($_REQUEST['batchaction']) and ($_REQUEST['batchaction'] == 'o' || $_REQUEST['batchaction'] == 'p' || $_REQUEST['batchaction'] == 'c')) { check_ticket('view-trackers'); $transaction = $tikilib->begin(); foreach ($_REQUEST['action'] as $batchid) { $item_info = $trklib->get_item_info($batchid); $actionObject = Tracker_Item::fromInfo($item_info); if ($actionObject->canModify()) { $trklib->replace_item($_REQUEST['trackerId'], $batchid, array('data' => ''), $_REQUEST['batchaction']); } } $transaction->commit(); } $smarty->assign('mail_msg', ''); $smarty->assign('email_mon', ''); if ($prefs['feature_user_watches'] == 'y' and $tiki_p_watch_trackers == 'y') { if ($user and isset($_REQUEST['watch'])) { check_ticket('view-trackers'); if ($_REQUEST['watch'] == 'add') { $tikilib->add_user_watch($user, 'tracker_modified', $_REQUEST["trackerId"], 'tracker', $tracker_info['name'], "tiki-view_tracker.php?trackerId=" . $_REQUEST["trackerId"]); } else { $tikilib->remove_user_watch($user, 'tracker_modified', $_REQUEST["trackerId"], 'tracker'); } } $smarty->assign('user_watching_tracker', 'n'); $it = $tikilib->user_watches($user, 'tracker_modified', $_REQUEST['trackerId'], 'tracker'); if ($user and $tikilib->user_watches($user, 'tracker_modified', $_REQUEST['trackerId'], 'tracker')) { $smarty->assign('user_watching_tracker', 'y'); } // Check, if the user is watching this tracker by a category. if ($prefs['feature_categories'] == 'y') { $watching_categories_temp = $categlib->get_watching_categories($_REQUEST["trackerId"], 'tracker', $user); $smarty->assign('category_watched', 'n'); if (count($watching_categories_temp) > 0) { $smarty->assign('category_watched', 'y'); $watching_categories = array(); foreach ($watching_categories_temp as $wct) { $watching_categories[] = array( "categId" => $wct, "name" => $categlib->get_category_name($wct) ); } $smarty->assign('watching_categories', $watching_categories); } } } if (isset($_REQUEST["save"])) { if ($itemObject->canModify()) { global $captchalib; include_once 'lib/captcha/captchalib.php'; if (empty($user) && $prefs['feature_antibot'] == 'y' && !$captchalib->validate()) { $smarty->assign('msg', $captchalib->getErrors()); $smarty->assign('errortype', 'no_redirect_login'); $smarty->display("error.tpl"); die; } // Check field values for each type and presence of mandatory ones $mandatory_missing = array(); $err_fields = array(); $categorized_fields = $trackerDefinition->getCategorizedFields(); $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields, $_REQUEST['trackerId'], empty($_REQUEST['itemId'])?'':$_REQUEST['itemId']); $smarty->assign('err_mandatory', $field_errors['err_mandatory']); $smarty->assign('err_value', $field_errors['err_value']); // values are OK, then lets add a new item if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0) { $smarty->assign('input_err', '0'); // no warning to display check_ticket('view-trackers'); if (!isset($_REQUEST["status"]) or ($tracker_info["showStatus"] != 'y' and $tiki_p_admin_trackers != 'y')) { $_REQUEST["status"] = ''; } if (empty($_REQUEST["itemId"]) && $tracker_info['oneUserItem'] == 'y') { // test if one item per user $_REQUEST['itemId'] = $trklib->get_user_item($_REQUEST['trackerId'], $tracker_info); } $itemid = $trklib->replace_item($_REQUEST["trackerId"], $_REQUEST["itemId"], $ins_fields, $_REQUEST['status']); if (isset($_REQUEST['listtoalert']) && $prefs['feature_groupalert'] == 'y') { $groupalertlib->Notify($_REQUEST['listtoalert'], "tiki-view_tracker_item.php?itemId=$itemid"); } $cookietab = "1"; $smarty->assign('itemId', ''); if (isset($newItemRate)) { $trackerId = $_REQUEST["trackerId"]; $trklib->replace_rating($trackerId, $itemid, $newItemRateField, $user, $newItemRate); } if (isset($_REQUEST["viewitem"]) && $_REQUEST["viewitem"] == 'view') { header('location: ' . preg_replace('#[\r\n]+#', '', "tiki-view_tracker_item.php?trackerId=" . $_REQUEST["trackerId"] . "&itemId=" . $itemid)); die; } elseif (isset($_REQUEST["viewitem"]) && $_REQUEST["viewitem"] == 'new') { header('location: ' . preg_replace('#[\r\n]+#', '', "tiki-view_tracker.php?trackerId=" . $_REQUEST["trackerId"] . "&cookietab=2")); die; } if (isset($tracker_info["defaultStatus"])) { $_REQUEST['status'] = $tracker_info["defaultStatus"]; } } else { $cookietab = "2"; $smarty->assign('input_err', '1'); // warning to display } if (isset($newItemRate)) { $trackerId = $_REQUEST["trackerId"]; $trklib->replace_rating($trackerId, $itemid, $newItemRateField, $user, $newItemRate); } } } if (!isset($_REQUEST["offset"])) { $offset = 0; } else { $offset = $_REQUEST["offset"]; } $smarty->assign_by_ref('offset', $offset); if (!empty($_REQUEST["maxRecords"])) { $maxRecords = $_REQUEST['maxRecords']; } if (isset($_REQUEST["initial"])) { $initial = $_REQUEST["initial"]; } else { $initial = ''; } $smarty->assign('initial', $initial); $writerfield = $trackerDefinition->getWriterField(); $writergroupfield = $trackerDefinition->getWriterGroupField(); if ($my and $writerfield) { $filterfield = $writerfield; } elseif ($ours and $writergroupfield) { $filterfield = $writergroupfield; } else { if (isset($_REQUEST["filterfield"])) { $filterfield = $_REQUEST["filterfield"]; } else { $filterfield = ''; } } $smarty->assign('filterfield', $filterfield); if ($my and $writerfield) { $exactvalue = $my; $filtervalue = ''; $_REQUEST['status'] = 'opc'; } elseif ($ours and $writergroupfield) { $exactvalue = $userlib->get_user_groups($user); $filtervalue = ''; $_REQUEST['status'] = 'opc'; } else { if (isset($_REQUEST["filtervalue"]) and is_array($_REQUEST["filtervalue"]) and isset($_REQUEST["filtervalue"]["$filterfield"])) { $filtervalue = $_REQUEST["filtervalue"]["$filterfield"]; } else if (isset($_REQUEST["filtervalue"])) { $filtervalue = $_REQUEST["filtervalue"]; } else { $filtervalue = ''; } if (!empty($_REQUEST['filtervalue_other'])) { $filtervalue = $_REQUEST['filtervalue_other']; } $exactvalue = ''; } $smarty->assign('filtervalue', $filtervalue); if (is_array($filtervalue)) { foreach ($filtervalue as $fil) { $filtervalueencoded = "&amp;filtervalue[" . rawurlencode($filterfield) . "][]=" . rawurlencode($fil); } $smarty->assign('filtervalueencoded', $filtervalueencoded); } $smarty->assign('status', $_REQUEST["status"]); if (isset($_REQUEST["trackerId"])) { $trackerId = $_REQUEST["trackerId"]; } if (isset($tracker_info['useRatings']) and $tracker_info['useRatings'] == 'y' and $user and $tiki_p_tracker_vote_ratings == 'y' and !empty($_REQUEST['trackerId']) and !empty($ratedItemId) and isset($newItemRate) and ($newItemRate == 'NULL' || in_array($newItemRate, explode(',', $tracker_info['ratingOptions'])))) { $trklib->replace_rating($_REQUEST['trackerId'], $ratedItemId, $newItemRateField, $user, $newItemRate); } $items = $trklib->list_items($_REQUEST["trackerId"], $offset, $maxRecords, $sort_mode, $listfields, $filterfield, $filtervalue, $_REQUEST["status"], $initial, $exactvalue, '', $xfields); $urlquery['status'] = $_REQUEST['status']; $urlquery['initial'] = $initial; $urlquery['trackerId'] = $_REQUEST["trackerId"]; $urlquery['sort_mode'] = $sort_mode; $urlquery['exactvalue'] = $exactvalue; $urlquery['filterfield'] = $filterfield; if (is_array($filtervalue)) { foreach ($filtervalue as $fil) { $urlquery["filtervalue[" . $filterfield . "][]"] = $fil; } } else { $urlquery["filtervalue[" . $filterfield . "]"] = $filtervalue; } $smarty->assign_by_ref('urlquery', $urlquery); if ($tracker_info['useComments'] == 'y' && ($tracker_info['showComments'] == 'y' || isset($tracker_info['showLastComment']) && $tracker_info['showLastComment'] == 'y')) { foreach ($items['data'] as $itkey => $oneitem) { if ($tracker_info['showComments'] == 'y') { $items['data'][$itkey]['comments'] = $trklib->get_item_nb_comments($items['data'][$itkey]['itemId']); } if (isset($tracker_info['showLastComment']) && $tracker_info['showLastComment'] == 'y') { $l = $trklib->list_last_comments($items['data'][$itkey]['trackerId'], $items['data'][$itkey]['itemId'], 0, 1); $items['data'][$itkey]['lastComment'] = !empty($l['cant']) ? $l['data'][0] : ''; } } } if ($tracker_info['useAttachments'] == 'y' && $tracker_info['showAttachments'] == 'y') { foreach ($items["data"] as $itkey => $oneitem) { $res = $trklib->get_item_nb_attachments($items["data"][$itkey]['itemId']); $items["data"][$itkey]['attachments'] = $res['attachments']; $items["data"][$itkey]['hits'] = $res['hits']; } } foreach ($fields['data'] as $fd) { // add field info for searchable fields not shown in the list $fid = $fd["fieldId"]; if ($fd['isSearchable'] == 'y' and !isset($listfields[$fid]) and $itemObject->canViewField($fid)) { $listfields[$fid] = $fd; } } $smarty->assign('trackerId', $_REQUEST["trackerId"]); $smarty->assign('tracker_info', $tracker_info); $smarty->assign('fields', $fields['data']); $smarty->assign('ins_fields', $ins_fields['data']); $smarty->assign_by_ref('items', $items["data"]); $smarty->assign_by_ref('item_count', $items['cant']); $smarty->assign_by_ref('listfields', $listfields); $users = $userlib->list_all_users(); $smarty->assign_by_ref('users', $users); if ($tiki_p_export_tracker == 'y') { $trackers = $trklib->list_trackers(); $smarty->assign_by_ref('trackers', $trackers['data']); include_once ('lib/wiki-plugins/wikiplugin_trackerfilter.php'); $formats = ''; $filters = wikiplugin_trackerFilter_get_filters($_REQUEST['trackerId'], '', $formats); $smarty->assign_by_ref('filters', $filters); if (!empty($_REQUEST['displayedFields'])) { if (is_string($_REQUEST['displayedFields'])) { $smarty->assign('displayedFields', preg_split('/[:,]/', $_REQUEST['displayedFields'])); } else { $smarty->assign_by_ref('displayedFields', $_REQUEST['displayedFields']); } } $smarty->assign('recordsMax', $items['cant']); $smarty->assign('recordsOffset', 1); } include_once ('tiki-section_options.php'); $smarty->assign('uses_tabs', 'y'); $smarty->assign('show_filters', 'n'); if (count($fields['data']) > 0) { foreach ($fields['data'] as $it) { if ($it['isSearchable'] == 'y') { $smarty->assign('show_filters', 'y'); break; } } } if (isset($tracker_info['useRatings']) && $tracker_info['useRatings'] == 'y' && $items['data']) { foreach ($items['data'] as $f => $v) { $items['data'][$f]['my_rate'] = $tikilib->get_user_vote("tracker." . $_REQUEST["trackerId"] . '.' . $items['data'][$f]['itemId'], $user); } } setcookie('tab', $cookietab); $smarty->assign('cookietab', $cookietab); ask_ticket('view-trackers'); // Generate validation js if ($prefs['feature_jquery'] == 'y' && $prefs['feature_jquery_validation'] == 'y') { global $validatorslib; include_once('lib/validatorslib.php'); $validationjs = $validatorslib->generateTrackerValidateJS($fields['data']); $smarty->assign('validationjs', $validationjs); } //Use 12- or 24-hour clock for $publishDate time selector based on admin and user preferences include_once ('lib/userprefs/userprefslib.php'); $smarty->assign('use_24hr_clock', $userprefslib->get_user_clock_pref($user)); // Display the template $smarty->assign('mid', 'tiki-view_tracker.tpl'); $smarty->display("tiki.tpl");
reneejustrenee/tikiwikitest
tiki-view_tracker.php
PHP
lgpl-2.1
20,702
using System.Collections.Generic; using System.Web.Mvc; using SmartStore.Services.Payments; namespace SmartStore.Web.Framework.Controllers { public abstract class PaymentControllerBase : SmartController { public abstract IList<string> ValidatePaymentForm(FormCollection form); public abstract ProcessPaymentRequest GetPaymentInfo(FormCollection form); } }
ilovejs/SmartStoreNET
src/Presentation/SmartStore.Web.Framework/Controllers/PaymentControllerBase.cs
C#
lgpl-2.1
389
/* * AbstractLikelihoodCore.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.evomodel.treelikelihood; /** * AbstractLikelihoodCore - An abstract base class for LikelihoodCores * * @author Andrew Rambaut * @version $Id: AbstractLikelihoodCore.java,v 1.11 2006/08/30 16:02:42 rambaut Exp $ */ public abstract class AbstractLikelihoodCore implements LikelihoodCore { protected int stateCount; protected int nodeCount; protected int patternCount; protected int partialsSize; protected int matrixSize; protected int matrixCount; protected boolean integrateCategories; protected double[][][] partials; protected int[][] states; protected double[][][] matrices; protected int[] currentMatricesIndices; protected int[] storedMatricesIndices; protected int[] currentPartialsIndices; protected int[] storedPartialsIndices; protected boolean useScaling = false; protected double[][][] scalingFactors; private double scalingThreshold = 1.0E-100; /** * Constructor * * @param stateCount number of states */ public AbstractLikelihoodCore(int stateCount) { this.stateCount = stateCount; } /** * initializes partial likelihood arrays. * * @param nodeCount the number of nodes in the tree * @param patternCount the number of patterns * @param matrixCount the number of matrices (i.e., number of categories) * @param integrateCategories whether sites are being integrated over all matrices */ public void initialize(int nodeCount, int patternCount, int matrixCount, boolean integrateCategories) { this.nodeCount = nodeCount; this.patternCount = patternCount; this.matrixCount = matrixCount; this.integrateCategories = integrateCategories; if (integrateCategories) { partialsSize = patternCount * stateCount * matrixCount; } else { partialsSize = patternCount * stateCount; } partials = new double[2][nodeCount][]; currentMatricesIndices = new int[nodeCount]; storedMatricesIndices = new int[nodeCount]; currentPartialsIndices = new int[nodeCount]; storedPartialsIndices = new int[nodeCount]; states = new int[nodeCount][]; for (int i = 0; i < nodeCount; i++) { partials[0][i] = null; partials[1][i] = null; states[i] = null; } matrixSize = stateCount * stateCount; matrices = new double[2][nodeCount][matrixCount * matrixSize]; } /** * cleans up and deallocates arrays. */ public void finalize() throws java.lang.Throwable { super.finalize(); nodeCount = 0; patternCount = 0; matrixCount = 0; partials = null; currentPartialsIndices = null; storedPartialsIndices = null; states = null; matrices = null; currentMatricesIndices = null; storedMatricesIndices = null; scalingFactors = null; } public void setUseScaling(boolean useScaling) { this.useScaling = useScaling; if (useScaling) { scalingFactors = new double[2][nodeCount][patternCount]; } } /** * Allocates partials for a node */ public void createNodePartials(int nodeIndex) { this.partials[0][nodeIndex] = new double[partialsSize]; this.partials[1][nodeIndex] = new double[partialsSize]; } /** * Sets partials for a node */ public void setNodePartials(int nodeIndex, double[] partials) { if (this.partials[0][nodeIndex] == null) { createNodePartials(nodeIndex); } if (partials.length < partialsSize) { int k = 0; for (int i = 0; i < matrixCount; i++) { System.arraycopy(partials, 0, this.partials[0][nodeIndex], k, partials.length); k += partials.length; } } else { System.arraycopy(partials, 0, this.partials[0][nodeIndex], 0, partials.length); } } /** * Allocates states for a node */ public void createNodeStates(int nodeIndex) { this.states[nodeIndex] = new int[patternCount]; } /** * Sets states for a node */ public void setNodeStates(int nodeIndex, int[] states) { if (this.states[nodeIndex] == null) { createNodeStates(nodeIndex); } System.arraycopy(states, 0, this.states[nodeIndex], 0, patternCount); } /** * Gets states for a node */ public void getNodeStates(int nodeIndex, int[] states) { System.arraycopy(this.states[nodeIndex], 0, states, 0, patternCount); } public void setNodeMatrixForUpdate(int nodeIndex) { currentMatricesIndices[nodeIndex] = 1 - currentMatricesIndices[nodeIndex]; } /** * Sets probability matrix for a node */ public void setNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { System.arraycopy(matrix, 0, matrices[currentMatricesIndices[nodeIndex]][nodeIndex], matrixIndex * matrixSize, matrixSize); } /** * Gets probability matrix for a node */ public void getNodeMatrix(int nodeIndex, int matrixIndex, double[] matrix) { System.arraycopy(matrices[currentMatricesIndices[nodeIndex]][nodeIndex], matrixIndex * matrixSize, matrix, 0, matrixSize); } public void setNodePartialsForUpdate(int nodeIndex) { currentPartialsIndices[nodeIndex] = 1 - currentPartialsIndices[nodeIndex]; } /** * Sets the currently updating node partials for node nodeIndex. This may * need to repeatedly copy the partials for the different category partitions */ public void setCurrentNodePartials(int nodeIndex, double[] partials) { if (partials.length < partialsSize) { int k = 0; for (int i = 0; i < matrixCount; i++) { System.arraycopy(partials, 0, this.partials[currentPartialsIndices[nodeIndex]][nodeIndex], k, partials.length); k += partials.length; } } else { System.arraycopy(partials, 0, this.partials[currentPartialsIndices[nodeIndex]][nodeIndex], 0, partials.length); } } /** * Calculates partial likelihoods at a node. * * @param nodeIndex1 the 'child 1' node * @param nodeIndex2 the 'child 2' node * @param nodeIndex3 the 'parent' node */ public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3) { if (states[nodeIndex1] != null) { if (states[nodeIndex2] != null) { calculateStatesStatesPruning( states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); } else { calculateStatesPartialsPruning(states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); } } else { if (states[nodeIndex2] != null) { calculateStatesPartialsPruning(states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); } else { calculatePartialsPartialsPruning(partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3]); } } if (useScaling) { scalePartials(nodeIndex3); } // // int k =0; // for (int i = 0; i < patternCount; i++) { // double f = 0.0; // // for (int j = 0; j < stateCount; j++) { // f += partials[currentPartialsIndices[nodeIndex3]][nodeIndex3][k]; // k++; // } // if (f == 0.0) { // Logger.getLogger("error").severe("A partial likelihood (node index = " + nodeIndex3 + ", pattern = "+ i +") is zero for all states."); // } // } } /** * Calculates partial likelihoods at a node when both children have states. */ protected abstract void calculateStatesStatesPruning(int[] states1, double[] matrices1, int[] states2, double[] matrices2, double[] partials3); /** * Calculates partial likelihoods at a node when one child has states and one has partials. */ protected abstract void calculateStatesPartialsPruning(int[] states1, double[] matrices1, double[] partials2, double[] matrices2, double[] partials3); /** * Calculates partial likelihoods at a node when both children have partials. */ protected abstract void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, double[] partials2, double[] matrices2, double[] partials3); /** * Calculates partial likelihoods at a node. * * @param nodeIndex1 the 'child 1' node * @param nodeIndex2 the 'child 2' node * @param nodeIndex3 the 'parent' node * @param matrixMap a map of which matrix to use for each pattern (can be null if integrating over categories) */ public void calculatePartials(int nodeIndex1, int nodeIndex2, int nodeIndex3, int[] matrixMap) { if (states[nodeIndex1] != null) { if (states[nodeIndex2] != null) { calculateStatesStatesPruning( states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); } else { calculateStatesPartialsPruning( states[nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); } } else { if (states[nodeIndex2] != null) { calculateStatesPartialsPruning( states[nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); } else { calculatePartialsPartialsPruning( partials[currentPartialsIndices[nodeIndex1]][nodeIndex1], matrices[currentMatricesIndices[nodeIndex1]][nodeIndex1], partials[currentPartialsIndices[nodeIndex2]][nodeIndex2], matrices[currentMatricesIndices[nodeIndex2]][nodeIndex2], partials[currentPartialsIndices[nodeIndex3]][nodeIndex3], matrixMap); } } if (useScaling) { scalePartials(nodeIndex3); } } /** * Calculates partial likelihoods at a node when both children have states. */ protected abstract void calculateStatesStatesPruning(int[] states1, double[] matrices1, int[] states2, double[] matrices2, double[] partials3, int[] matrixMap); /** * Calculates partial likelihoods at a node when one child has states and one has partials. */ protected abstract void calculateStatesPartialsPruning(int[] states1, double[] matrices1, double[] partials2, double[] matrices2, double[] partials3, int[] matrixMap); /** * Calculates partial likelihoods at a node when both children have partials. */ protected abstract void calculatePartialsPartialsPruning(double[] partials1, double[] matrices1, double[] partials2, double[] matrices2, double[] partials3, int[] matrixMap); public void integratePartials(int nodeIndex, double[] proportions, double[] outPartials) { calculateIntegratePartials(partials[currentPartialsIndices[nodeIndex]][nodeIndex], proportions, outPartials); } /** * Integrates partials across categories. * * @param inPartials the partials at the node to be integrated * @param proportions the proportions of sites in each category * @param outPartials an array into which the integrated partials will go */ protected abstract void calculateIntegratePartials(double[] inPartials, double[] proportions, double[] outPartials); /** * Scale the partials at a given node. This uses a scaling suggested by Ziheng Yang in * Yang (2000) J. Mol. Evol. 51: 423-432 * <p/> * This function looks over the partial likelihoods for each state at each pattern * and finds the largest. If this is less than the scalingThreshold (currently set * to 1E-40) then it rescales the partials for that pattern by dividing by this number * (i.e., normalizing to between 0, 1). It then stores the log of this scaling. * This is called for every internal node after the partials are calculated so provides * most of the performance hit. Ziheng suggests only doing this on a proportion of nodes * but this sounded like a headache to organize (and he doesn't use the threshold idea * which improves the performance quite a bit). * * @param nodeIndex */ protected void scalePartials(int nodeIndex) { int u = 0; for (int i = 0; i < patternCount; i++) { double scaleFactor = 0.0; int v = u; for (int k = 0; k < matrixCount; k++) { for (int j = 0; j < stateCount; j++) { if (partials[currentPartialsIndices[nodeIndex]][nodeIndex][v] > scaleFactor) { scaleFactor = partials[currentPartialsIndices[nodeIndex]][nodeIndex][v]; } v++; } v += (patternCount - 1) * stateCount; } if (scaleFactor < scalingThreshold) { v = u; for (int k = 0; k < matrixCount; k++) { for (int j = 0; j < stateCount; j++) { partials[currentPartialsIndices[nodeIndex]][nodeIndex][v] /= scaleFactor; v++; } v += (patternCount - 1) * stateCount; } scalingFactors[currentPartialsIndices[nodeIndex]][nodeIndex][i] = Math.log(scaleFactor); } else { scalingFactors[currentPartialsIndices[nodeIndex]][nodeIndex][i] = 0.0; } u += stateCount; } } /** * This function returns the scaling factor for that pattern by summing over * the log scalings used at each node. If scaling is off then this just returns * a 0. * * @return the log scaling factor */ public double getLogScalingFactor(int pattern) { double logScalingFactor = 0.0; if (useScaling) { for (int i = 0; i < nodeCount; i++) { logScalingFactor += scalingFactors[currentPartialsIndices[i]][i][pattern]; } } return logScalingFactor; } /** * Gets the partials for a particular node. * * @param nodeIndex the node * @param outPartials an array into which the partials will go */ public void getPartials(int nodeIndex, double[] outPartials) { double[] partials1 = partials[currentPartialsIndices[nodeIndex]][nodeIndex]; System.arraycopy(partials1, 0, outPartials, 0, partialsSize); } /** * Store current state */ public void storeState() { System.arraycopy(currentMatricesIndices, 0, storedMatricesIndices, 0, nodeCount); System.arraycopy(currentPartialsIndices, 0, storedPartialsIndices, 0, nodeCount); } /** * Restore the stored state */ public void restoreState() { // Rather than copying the stored stuff back, just swap the pointers... int[] tmp1 = currentMatricesIndices; currentMatricesIndices = storedMatricesIndices; storedMatricesIndices = tmp1; int[] tmp2 = currentPartialsIndices; currentPartialsIndices = storedPartialsIndices; storedPartialsIndices = tmp2; } }
whdc/ieo-beast
src/dr/evomodel/treelikelihood/AbstractLikelihoodCore.java
Java
lgpl-2.1
18,890
/*************************************************************************** * Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "rezkonvimporter.h" #include <kapplication.h> #include <klocale.h> #include <kdebug.h> #include <QFile> #include <QRegExp> #include <QTextStream> #include "datablocks/mixednumber.h" RezkonvImporter::RezkonvImporter() : BaseImporter() {} RezkonvImporter::~RezkonvImporter() {} void RezkonvImporter::parseFile( const QString &filename ) { QFile input( filename ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); QString line; while ( !stream.atEnd() ) { line = stream.readLine(); if ( line.contains( QRegExp( "^=====.*REZKONV.*", Qt::CaseInsensitive ) ) ) { QStringList raw_recipe; while ( !( line = stream.readLine() ).contains( QRegExp( "^=====\\s*$" ) ) && !stream.atEnd() ) raw_recipe << line; readRecipe( raw_recipe ); } } if ( fileRecipeCount() == 0 ) setErrorMsg( i18n( "No recipes found in this file." ) ); } else setErrorMsg( i18n( "Unable to open file." ) ); } void RezkonvImporter::readRecipe( const QStringList &raw_recipe ) { kapp->processEvents(); //don't want the user to think its frozen... especially for files with thousands of recipes Recipe recipe; QStringList::const_iterator text_it = raw_recipe.begin(); m_end_it = raw_recipe.end(); //title (Titel) text_it++; recipe.title = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).trimmed(); kDebug() << "Found title: " << recipe.title ; //categories (Kategorien): text_it++; QStringList categories; if ( ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).isEmpty() ) categories = QStringList(); else categories = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).split( ',', QString::SkipEmptyParts ); for ( QStringList::const_iterator it = categories.constBegin(); it != categories.constEnd(); ++it ) { Element new_cat; new_cat.name = QString( *it ).trimmed(); kDebug() << "Found category: " << new_cat.name ; recipe.categoryList.append( new_cat ); } //yield (Menge) text_it++; //get the number between the ":" and the next space after it QString yield_str = ( *text_it ).trimmed(); yield_str.remove( QRegExp( "^Menge:\\s*" ) ); int sep_index = yield_str.indexOf( ' ' ); if ( sep_index != -1 ) recipe.yield.setType(yield_str.mid( sep_index+1 )); double amount = 0.0, amountOffset = 0.0; readRange( yield_str.mid( 0, sep_index ), amount, amountOffset ); recipe.yield.setAmount(amount); recipe.yield.setAmountOffset(amountOffset); kDebug() << "Found yield: " << recipe.yield.amount(); bool is_sub = false; bool last_line_empty = false; text_it++; while ( text_it != raw_recipe.end() ) { if ( ( *text_it ).isEmpty() ) { last_line_empty = true; text_it++; continue; } if ( ( *text_it ).contains( QRegExp( "^=====.*=$" ) ) ) //is a header { if ( ( *text_it ).contains( "quelle", Qt::CaseInsensitive ) ) { loadReferences( text_it, recipe ); break; //reference lines are the last before the instructions } else loadIngredientHeader( *text_it, recipe ); } //if it has no more than two spaces followed by a non-digit //then we'll assume it is a direction line else if ( last_line_empty && ( *text_it ).contains( QRegExp( "^\\s{0,2}[^\\d\\s=]" ) ) ) break; else loadIngredient( *text_it, recipe, is_sub ); last_line_empty = false; text_it++; } loadInstructions( text_it, recipe ); add ( recipe ); current_header.clear(); } void RezkonvImporter::loadIngredient( const QString &string, Recipe &recipe, bool &is_sub ) { Ingredient new_ingredient; new_ingredient.amount = 0; //amount not required, so give default of 0 QRegExp cont_test( "^-{1,2}" ); if ( string.trimmed().contains( cont_test ) ) { QString name = string.trimmed(); name.remove( cont_test ); kDebug() << "Appending to last ingredient: " << name ; if ( !recipe.ingList.isEmpty() ) //so it doesn't crash when the first ingredient appears to be a continuation of another recipe.ingList.last().name += ' ' + name; return ; } //amount if ( !string.mid( 0, 7 ).trimmed().isEmpty() ) readRange( string.mid( 0, 7 ), new_ingredient.amount, new_ingredient.amount_offset ); //unit QString unit_str = string.mid( 8, 9 ).trimmed(); new_ingredient.units = Unit( unit_str, new_ingredient.amount ); //name and preparation method new_ingredient.name = string.mid( 18, string.length() - 18 ).trimmed(); //separate out the preparation method QString name_and_prep = new_ingredient.name; int separator_index = name_and_prep.indexOf( "," ); if ( separator_index != -1 ) { new_ingredient.name = name_and_prep.mid( 0, separator_index ).trimmed(); new_ingredient.prepMethodList = ElementList::split(",",name_and_prep.mid( separator_index + 1, name_and_prep.length() ).trimmed() ); } //header (if present) new_ingredient.group = current_header; bool last_is_sub = is_sub; if ( !new_ingredient.prepMethodList.isEmpty() && new_ingredient.prepMethodList.last().name == "or" ) { new_ingredient.prepMethodList.pop_back(); is_sub = true; } else is_sub = false; if ( last_is_sub ) recipe.ingList.last().substitutes.append(new_ingredient); else recipe.ingList.append( new_ingredient ); } void RezkonvImporter::loadIngredientHeader( const QString &string, Recipe &/*recipe*/ ) { QString header = string; header.remove( QRegExp( "^=*" ) ).remove( QRegExp( "=*$" ) ); header = header.trimmed(); kDebug() << "found ingredient header: " << header ; current_header = header; } void RezkonvImporter::loadInstructions( QStringList::const_iterator &text_it, Recipe &recipe ) { QString instr; QRegExp rx_title( "^:{0,1}\\s*O-Titel\\s*:" ); QString line; text_it++; while ( text_it != m_end_it ) { line = *text_it; //titles longer than the line width are rewritten here if ( line.contains( rx_title ) ) { line.remove( rx_title ); recipe.title = line.trimmed(); QRegExp rx_line_cont( ":\\s*>{0,1}\\s*:" ); while ( ( line = *text_it ).contains( rx_line_cont ) ) { line.remove( rx_line_cont ); recipe.title += line; text_it++; } kDebug() << "Found long title: " << recipe.title ; } else { if ( line.trimmed().isEmpty() && ( (text_it+1) != m_end_it ) ) instr += "\n\n"; instr += line.trimmed(); } text_it++; } recipe.instructions = instr; } void RezkonvImporter::loadReferences( QStringList::const_iterator &text_it, Recipe &recipe ) { kDebug() << "Found source header" ; text_it++; while ( text_it != m_end_it && !text_it->trimmed().isEmpty() ) { QRegExp rx_line_begin( "^\\s*-{0,2}\\s*" ); QRegExp rx_creation_date = QRegExp( "^\\s*-{0,2}\\s*Erfasst \\*RK\\*", Qt::CaseInsensitive ); if ( ( *text_it ).contains( rx_creation_date ) ) // date followed by typist { QString date = *text_it; date.remove( rx_creation_date ).remove( QRegExp( " von\\s*$" ) ); // Date is given as DD.MM.YY QString s = date.section( '.', 0, 0 ); int day = s.toInt(); s = date.section( '.', 1, 1 ); int month = s.toInt(); s = date.section( '.', 2, 2 ); int year = s.toInt(); year += 1900; if ( year < 1970 ) year += 100; //we'll assume nothing has been created before 1970 (y2k issues :p) recipe.ctime = QDateTime(QDate(year,month,day)); #if 0 //typist text_it++; QString typist = = *text_it; typist.remove( rx_line_begin ); #endif } else //everything else is an author { if ( ( *text_it ).contains( rx_line_begin ) ) { QString author = *text_it; author.remove( rx_line_begin ); recipe.authorList.append( Element( author ) ); } else break; } text_it++; } } void RezkonvImporter::readRange( const QString &range_str, double &amount, double &amount_offset ) { QString from = range_str.section( '-', 0, 0 ); QString to = range_str.section( '-', 1, 1 ); MixedNumber number; MixedNumber::fromString( from, number, false); amount = number.toDouble(); if ( !to.trimmed().isEmpty() ) { MixedNumber::fromString( to, number, false ); amount_offset = number.toDouble() - amount; } }
eliovir/krecipes
src/importers/rezkonvimporter.cpp
C++
lgpl-2.1
8,724
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pt-BR" sourcelanguage="en"> <context> <name>CmdSketcherBSplineComb</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="162"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="163"/> <source>Show/hide B-spline curvature comb</source> <translation>Mostrar/ocultar o pente de curvatura de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="164"/> <source>Switches between showing and hiding the curvature comb for all B-splines</source> <translation>Alterna entre mostrar e ocultar o pente de curvatura para todas as B-splines</translation> </message> </context> <context> <name>CmdSketcherBSplineDegree</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="100"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="101"/> <source>Show/hide B-spline degree</source> <translation>Mostrar/ocultar grau de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="102"/> <source>Switches between showing and hiding the degree for all B-splines</source> <translation>Alterna entre mostrar e ocultar o grau para todas os B-splines</translation> </message> </context> <context> <name>CmdSketcherBSplineKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="193"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="194"/> <source>Show/hide B-spline knot multiplicity</source> <translation>Mostrar/ocultar multiplicidade de nós de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="195"/> <source>Switches between showing and hiding the knot multiplicity for all B-splines</source> <translation>Alterna entre mostrar e ocultar a multiplicidade de nós para todas as B-splines</translation> </message> </context> <context> <name>CmdSketcherBSplinePoleWeight</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="224"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="225"/> <source>Show/hide B-spline control point weight</source> <translation>Mostrar/ocultar o peso dos pontos de controle da B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="226"/> <source>Switches between showing and hiding the control point weight for all B-splines</source> <translation>Alterna entre mostrar e ocultar o peso dos pontos de controle para todas as B-splines</translation> </message> </context> <context> <name>CmdSketcherBSplinePolygon</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="131"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="132"/> <source>Show/hide B-spline control polygon</source> <translation>Mostrar/ocultar polígono de controle de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="133"/> <source>Switches between showing and hiding the control polygons for all B-splines</source> <translation>Alterna entre mostrar e ocultar os polígonos de controle para todas as B-splines</translation> </message> </context> <context> <name>CmdSketcherCarbonCopy</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6204"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6205"/> <source>Carbon copy</source> <translation>Com cópia</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6206"/> <source>Copies the geometry of another sketch</source> <translation>Copia a geometria de outro esboço</translation> </message> </context> <context> <name>CmdSketcherClone</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1558"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1559"/> <source>Clone</source> <translation>Clonar</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1560"/> <source>Creates a clone of the geometry taking as reference the last selected point</source> <translation>Cria um clone da geometria tomando como referência o último ponto selecionado</translation> </message> </context> <context> <name>CmdSketcherCloseShape</name> <message> <location filename="../../CommandSketcherTools.cpp" line="100"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="101"/> <source>Close shape</source> <translation>Fechar forma</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="102"/> <source>Produce a closed shape by tying the end point of one element with the next element's starting point</source> <translation>Produzir uma forma fechada ligando o ponto de extremidade de um elemento com o ponto de partida do próximo elemento</translation> </message> </context> <context> <name>CmdSketcherCompBSplineShowHideGeometryInformation</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="255"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="256"/> <source>Show/hide B-spline information layer</source> <translation>Mostrar/ocultar a camada de informações da B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="331"/> <source>Show/hide B-spline degree</source> <translation>Mostrar/ocultar grau de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="338"/> <source>Show/hide B-spline control polygon</source> <translation>Mostrar/ocultar polígono de controle de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="345"/> <source>Show/hide B-spline curvature comb</source> <translation>Mostrar/ocultar o pente de curvatura de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="352"/> <source>Show/hide B-spline knot multiplicity</source> <translation>Mostrar/ocultar multiplicidade de nós de B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="360"/> <source>Show/hide B-spline control point weight</source> <translation>Mostrar/ocultar o peso dos pontos de controle da B-spline</translation> </message> </context> <context> <name>CmdSketcherCompConstrainRadDia</name> <message> <location filename="../../CommandConstraints.cpp" line="5730"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5731"/> <source>Constrain arc or circle</source> <translation>Restringir arco ou círculo</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5732"/> <source>Constrain an arc or a circle</source> <translation>Restringir um arco ou um círculo</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5815"/> <source>Constrain radius</source> <translation>Restrição de raio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5819"/> <source>Constrain diameter</source> <translation>Restringir o diâmetro</translation> </message> </context> <context> <name>CmdSketcherCompCopy</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1633"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1634"/> <source>Copy</source> <translation>Copiar</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1635"/> <source>Creates a clone of the geometry taking as reference the last selected point</source> <translation>Cria um clone da geometria tomando como referência o último ponto selecionado</translation> </message> </context> <context> <name>CmdSketcherCompCreateArc</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1809"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1810"/> <source>Create arc</source> <translation>Criar arco</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1811"/> <source>Create an arc in the sketcher</source> <translation>Criar um arco na bancada de esboços</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1888"/> <source>Center and end points</source> <translation>Pontos de centro e extremidades</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1892"/> <source>End points and rim point</source> <translation>Pontos de extremidade e ponto de borda</translation> </message> </context> <context> <name>CmdSketcherCompCreateBSpline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4445"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4446"/> <source>Create a B-spline</source> <translation>Criar uma B-spline</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4447"/> <source>Create a B-spline in the sketch</source> <translation>Criar uma B-spline no esboço</translation> </message> </context> <context> <name>CmdSketcherCompCreateCircle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4763"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4764"/> <source>Create circle</source> <translation>Criar círculo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4765"/> <source>Create a circle in the sketcher</source> <translation>Criar um círculo no esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4842"/> <source>Center and rim point</source> <translation>Ponto de centro e borda</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4846"/> <source>3 rim points</source> <translation>3 pontos de borda</translation> </message> </context> <context> <name>CmdSketcherCompCreateConic</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3868"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3869"/> <source>Create a conic</source> <translation>Criar uma cônica</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3870"/> <source>Create a conic in the sketch</source> <translation>Criar uma cônica no esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3975"/> <source>Ellipse by center, major radius, point</source> <translation>Elipse pelo centro, raio maior, ponto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3979"/> <source>Ellipse by periapsis, apoapsis, minor radius</source> <translation>Elipse pelo periélio, apoapsis, menor raio</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3983"/> <source>Arc of ellipse by center, major radius, endpoints</source> <translation>Arco de elipse pelo centro, raio principal, pontos de extremidade</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3987"/> <source>Arc of hyperbola by center, major radius, endpoints</source> <translation>Arco de hipérbole pelo centro, raio maior, pontos de extremidade</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3991"/> <source>Arc of parabola by focus, vertex, endpoints</source> <translation>Arco da parábola por foco, vértice, pontos de extremidade</translation> </message> </context> <context> <name>CmdSketcherCompCreateFillets</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5340"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5341"/> <source>Fillets</source> <translation>Filetes</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5342"/> <source>Create a fillet between two lines</source> <translation>Crie um filete entre duas linhas</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5417"/> <source>Sketch fillet</source> <translation>Filete de esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5421"/> <source>Constraint-preserving sketch fillet</source> <translation>Filete de esboço com preservação de restrições</translation> </message> </context> <context> <name>CmdSketcherCompCreateRegularPolygon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6833"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6834"/> <source>Create regular polygon</source> <translation>Criar polígono regular</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6835"/> <source>Create a regular polygon in the sketcher</source> <translation>Criar um polígono regular no esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6950"/> <source>Triangle</source> <translation>Triângulo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6954"/> <source>Square</source> <translation>Quadrado</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6958"/> <source>Pentagon</source> <translation>Pentágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6962"/> <source>Hexagon</source> <translation>Hexágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6966"/> <source>Heptagon</source> <translation>Heptágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6970"/> <source>Octagon</source> <translation>Octógono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6974"/> <source>Regular Polygon</source> <translation>Polígono regular</translation> </message> </context> <context> <name>CmdSketcherCompModifyKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="898"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="899"/> <source>Modify knot multiplicity</source> <translation>Modificar a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="900"/> <source>Modifies the multiplicity of the selected knot of a B-spline</source> <translation>Modifica a multiplicidade do nós selecionados de uma B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="961"/> <source>Increase knot multiplicity</source> <translation>Aumentar a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="968"/> <source>Decrease knot multiplicity</source> <translation>Diminuir a multiplicidade de nós</translation> </message> </context> <context> <name>CmdSketcherConnect</name> <message> <location filename="../../CommandSketcherTools.cpp" line="211"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="212"/> <source>Connect edges</source> <translation>Conectar nós</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="213"/> <source>Tie the end point of the element with next element's starting point</source> <translation>Amarrar o ponto final do elemento com o ponto de partida do próximo elemento</translation> </message> </context> <context> <name>CmdSketcherConstrainAngle</name> <message> <location filename="../../CommandConstraints.cpp" line="5848"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5849"/> <source>Constrain angle</source> <translation>Ângulo de restrição</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5850"/> <source>Fix the angle of a line or the angle between two lines</source> <translation>Fixar o ângulo de uma linha ou o ângulo entre duas linhas</translation> </message> </context> <context> <name>CmdSketcherConstrainBlock</name> <message> <location filename="../../CommandConstraints.cpp" line="1753"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1754"/> <source>Constrain block</source> <translation>Restrição de bloqueio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1755"/> <source>Block constraint: block the selected edge from moving</source> <translation>Restrição de bloqueio: impede o deslocamento da aresta selecionada</translation> </message> </context> <context> <name>CmdSketcherConstrainCoincident</name> <message> <location filename="../../CommandConstraints.cpp" line="2063"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2064"/> <source>Constrain coincident</source> <translation>Restrição de coincidência</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2065"/> <source>Create a coincident constraint on the selected item</source> <translation>Criar uma restrição de coincidência sobre o item selecionado</translation> </message> </context> <context> <name>CmdSketcherConstrainDiameter</name> <message> <location filename="../../CommandConstraints.cpp" line="5275"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5276"/> <source>Constrain diameter</source> <translation>Restringir o diâmetro</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5277"/> <source>Fix the diameter of a circle or an arc</source> <translation>Corrigir o diâmetro de um círculo ou arco</translation> </message> </context> <context> <name>CmdSketcherConstrainDistance</name> <message> <location filename="../../CommandConstraints.cpp" line="2251"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2252"/> <source>Constrain distance</source> <translation>Restrição de distância</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2253"/> <source>Fix a length of a line or the distance between a line and a vertex</source> <translation>Trancar o comprimento de uma linha ou a distância entre uma linha e um vértice</translation> </message> </context> <context> <name>CmdSketcherConstrainDistanceX</name> <message> <location filename="../../CommandConstraints.cpp" line="2806"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2807"/> <source>Constrain horizontal distance</source> <translation>Restrição de distância horizontal</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2808"/> <source>Fix the horizontal distance between two points or line ends</source> <translation>Fixar a distância horizontal entre dois pontos ou extremidades de linha</translation> </message> </context> <context> <name>CmdSketcherConstrainDistanceY</name> <message> <location filename="../../CommandConstraints.cpp" line="3060"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3061"/> <source>Constrain vertical distance</source> <translation>Restringir a distância vertical</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3062"/> <source>Fix the vertical distance between two points or line ends</source> <translation>Fixar a distância vertical entre dois pontos ou extremidades de linha</translation> </message> </context> <context> <name>CmdSketcherConstrainEqual</name> <message> <location filename="../../CommandConstraints.cpp" line="6375"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6376"/> <source>Constrain equal</source> <translation>Restrição igual</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6377"/> <source>Create an equality constraint between two lines or between circles and arcs</source> <translation>Criar uma restrição de igualdade entre duas linhas ou círculos e arcos</translation> </message> </context> <context> <name>CmdSketcherConstrainHorizontal</name> <message> <location filename="../../CommandConstraints.cpp" line="1056"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1057"/> <source>Constrain horizontally</source> <translation>Restringir horizontalmente</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1058"/> <source>Create a horizontal constraint on the selected item</source> <translation>Criar uma restrição horizontal sobre o item selecionado</translation> </message> </context> <context> <name>CmdSketcherConstrainInternalAlignment</name> <message> <location filename="../../CommandConstraints.cpp" line="7056"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7057"/> <source>Constrain internal alignment</source> <translation>Restrição de alinhamento interno</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7058"/> <source>Constrains an element to be aligned with the internal geometry of another element</source> <translation>Restringe um elemento para ser alinhado com a geometria interna de um outro elemento</translation> </message> </context> <context> <name>CmdSketcherConstrainLock</name> <message> <location filename="../../CommandConstraints.cpp" line="1528"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1529"/> <source>Constrain lock</source> <translation>Restrição de bloqueio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1530"/> <source>Lock constraint: create both a horizontal and a vertical distance constraint on the selected vertex</source> <translation>Restrição de bloqueio: adiciona uma restrição de distância horizontal e vertical ao vértice selecionado</translation> </message> </context> <context> <name>CmdSketcherConstrainParallel</name> <message> <location filename="../../CommandConstraints.cpp" line="3306"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3307"/> <source>Constrain parallel</source> <translation>Restrição paralela</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3308"/> <source>Create a parallel constraint between two lines</source> <translation>Criar uma restrição paralela entre duas linhas</translation> </message> </context> <context> <name>CmdSketcherConstrainPerpendicular</name> <message> <location filename="../../CommandConstraints.cpp" line="3456"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3457"/> <source>Constrain perpendicular</source> <translation>Restrição perpendicular</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3458"/> <source>Create a perpendicular constraint between two lines</source> <translation>Criar uma restrição perpendicular entre duas linhas</translation> </message> </context> <context> <name>CmdSketcherConstrainPointOnObject</name> <message> <location filename="../../CommandConstraints.cpp" line="2599"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2600"/> <source>Constrain point onto object</source> <translation>Restringir um ponto sobre um objeto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2601"/> <source>Fix a point onto an object</source> <translation>Fixar um ponto sobre um objeto</translation> </message> </context> <context> <name>CmdSketcherConstrainRadius</name> <message> <location filename="../../CommandConstraints.cpp" line="4764"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4765"/> <source>Constrain radius or weight</source> <translation>Restrição de raio ou peso</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4766"/> <source>Fix the radius of a circle or an arc or fix the weight of a pole of a B-Spline</source> <translation>Bloquea o raio de um círculo ou arco ou o peso de um polo de um B-Spline</translation> </message> </context> <context> <name>CmdSketcherConstrainSnellsLaw</name> <message> <location filename="../../CommandConstraints.cpp" line="6892"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6893"/> <source>Constrain refraction (Snell's law')</source> <translation>Restrição de refração (lei de Snell)</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6894"/> <source>Create a refraction law (Snell's law) constraint between two endpoints of rays and an edge as an interface.</source> <translation>Cria uma restrição de refração (lei de Snell) entre dois pontos de extremidade de raios e uma aresta usada como interface.</translation> </message> </context> <context> <name>CmdSketcherConstrainSymmetric</name> <message> <location filename="../../CommandConstraints.cpp" line="6592"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6593"/> <source>Constrain symmetrical</source> <translation>Restrição simétrica</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6594"/> <source>Create a symmetry constraint between two points with respect to a line or a third point</source> <translation>Criar uma restrição de simetria entre dois pontos em relação a uma linha ou um terceiro ponto</translation> </message> </context> <context> <name>CmdSketcherConstrainTangent</name> <message> <location filename="../../CommandConstraints.cpp" line="4092"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4093"/> <source>Constrain tangent</source> <translation>Restrição tangente</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4094"/> <source>Create a tangent constraint between two entities</source> <translation>Criar uma restrição tangente entre duas entidades</translation> </message> </context> <context> <name>CmdSketcherConstrainVertical</name> <message> <location filename="../../CommandConstraints.cpp" line="1294"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1295"/> <source>Constrain vertically</source> <translation>Restringir verticalmente</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1296"/> <source>Create a vertical constraint on the selected item</source> <translation>Criar uma restrição vertical sobre o item selecionado</translation> </message> </context> <context> <name>CmdSketcherConvertToNURB</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="384"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="385"/> <source>Convert geometry to B-spline</source> <translation>Converter geometria para B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="386"/> <source>Converts the selected geometry to a B-spline</source> <translation>Converte a geometria selecionada em uma B-spline</translation> </message> </context> <context> <name>CmdSketcherCopy</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1514"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1515"/> <source>Copy</source> <translation>Copiar</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1516"/> <source>Creates a simple copy of the geometry taking as reference the last selected point</source> <translation>Cria uma cópia simples da geometria tomando como referência o último ponto selecionado</translation> </message> </context> <context> <name>CmdSketcherCreate3PointArc</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1782"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1783"/> <source>Create arc by three points</source> <translation>Criar um arco a partir de três pontos</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1784"/> <source>Create an arc by its end points and a point along the arc</source> <translation>Criar um arco a partir de seus pontos de extremidade e um ponto ao longo do arco</translation> </message> </context> <context> <name>CmdSketcherCreate3PointCircle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4736"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4737"/> <source>Create circle by three points</source> <translation>Criar um círculo a partir de três pontos</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4738"/> <source>Create a circle by 3 perimeter points</source> <translation>Criar um círculo a partir de 3 pontos do perímetro</translation> </message> </context> <context> <name>CmdSketcherCreateArc</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1513"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1514"/> <source>Create arc by center</source> <translation>Criar um arco pelo centro</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1515"/> <source>Create an arc by its center and by its end points</source> <translation>Criar um arco a partir do seu centro e por seus pontos de extremidade</translation> </message> </context> <context> <name>CmdSketcherCreateArcOfEllipse</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3195"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3196"/> <source>Create an arc of ellipse</source> <translation>Criar um arco de elipse</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3197"/> <source>Create an arc of ellipse in the sketch</source> <translation>Criar um arco de elipse no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateArcOfHyperbola</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3538"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3539"/> <source>Create an arc of hyperbola</source> <translation>Cria um arco de hipérbole</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3540"/> <source>Create an arc of hyperbola in the sketch</source> <translation>Cria um arco de hipérbole no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateArcOfParabola</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3836"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3837"/> <source>Create an arc of parabola</source> <translation>Criar um arco de parábola</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3838"/> <source>Create an arc of parabola in the sketch</source> <translation>Criar um arco de parábola no Esboço</translation> </message> </context> <context> <name>CmdSketcherCreateBSpline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4370"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4371"/> <source>Create B-spline</source> <translation>Criar B-spline</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4372"/> <source>Create a B-spline via control points in the sketch.</source> <translation>Criar uma B-spline através de pontos de controle no esboço.</translation> </message> </context> <context> <name>CmdSketcherCreateCircle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="2043"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2044"/> <source>Create circle</source> <translation>Criar círculo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2045"/> <source>Create a circle in the sketch</source> <translation>Criar um círculo no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateDraftLine</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5000"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5001"/> <source>Create draft line</source> <translation>Criar linha de rascunho</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5002"/> <source>Create a draft line in the sketch</source> <translation>Criar uma linha de rascunho no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateEllipseBy3Points</name> <message> <location filename="../../CommandCreateGeo.cpp" line="2868"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2869"/> <source>Create ellipse by 3 points</source> <translation>Criar elipse por 3 pontos</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2870"/> <source>Create an ellipse by 3 points in the sketch</source> <translation>Criar uma elipse por 3 pontos no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateEllipseByCenter</name> <message> <location filename="../../CommandCreateGeo.cpp" line="2838"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2839"/> <source>Create ellipse by center</source> <translation>Criar elipse pelo centro</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2840"/> <source>Create an ellipse by center in the sketch</source> <translation>Criar uma elipse pelo centro no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateFillet</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5280"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5281"/> <source>Create fillet</source> <translation>Criar filete</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5282"/> <source>Create a fillet between two lines or at a coincident point</source> <translation>Criar um arredondamento entre duas linhas ou em um ponto de coincidência</translation> </message> </context> <context> <name>CmdSketcherCreateHeptagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6748"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6749"/> <source>Create heptagon</source> <translation>Criar heptágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6750"/> <source>Create a heptagon in the sketch</source> <translation>Criar um heptágono no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateHexagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6721"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6722"/> <source>Create hexagon</source> <translation>Criar hexágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6723"/> <source>Create a hexagon in the sketch</source> <translation>Criar um hexágono no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateLine</name> <message> <location filename="../../CommandCreateGeo.cpp" line="383"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="384"/> <source>Create line</source> <translation>Criar linha</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="385"/> <source>Create a line in the sketch</source> <translation>Criar uma linha no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateOctagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6775"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6776"/> <source>Create octagon</source> <translation>Criar octógono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6777"/> <source>Create an octagon in the sketch</source> <translation>Criar um octógono no esboço</translation> </message> </context> <context> <name>CmdSketcherCreatePentagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6693"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6694"/> <source>Create pentagon</source> <translation>Criar pentágono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6695"/> <source>Create a pentagon in the sketch</source> <translation>Criar um pentágono no esboço</translation> </message> </context> <context> <name>CmdSketcherCreatePeriodicBSpline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4414"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4415"/> <source>Create periodic B-spline</source> <translation>Criar B-spline periódica</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4416"/> <source>Create a periodic B-spline via control points in the sketch.</source> <translation>Crie uma B-spline periódica através de pontos de controle no esboço.</translation> </message> </context> <context> <name>CmdSketcherCreatePoint</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4943"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4944"/> <source>Create point</source> <translation>Criar ponto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4945"/> <source>Create a point in the sketch</source> <translation>Criar um ponto no esboço</translation> </message> </context> <context> <name>CmdSketcherCreatePointFillet</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5309"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5310"/> <source>Create corner-preserving fillet</source> <translation>Criar filete de preservação de canto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5311"/> <source>Fillet that preserves intersection point and most constraints</source> <translation>Filete que preserva o ponto de interseção e a maioria das restrições</translation> </message> </context> <context> <name>CmdSketcherCreatePolyline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1270"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1271"/> <source>Create polyline</source> <translation>Criar polígono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1272"/> <source>Create a polyline in the sketch. 'M' Key cycles behaviour</source> <translation>Criar um polígono no esboço. A tecla 'M' alterna os modos de desenho</translation> </message> </context> <context> <name>CmdSketcherCreateRectangle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="582"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="583"/> <source>Create rectangle</source> <translation>Criar retângulo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="584"/> <source>Create a rectangle in the sketch</source> <translation>Criar um retângulo no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateRegularPolygon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6802"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6803"/> <source>Create regular polygon</source> <translation>Criar polígono regular</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6804"/> <source>Create a regular polygon in the sketch</source> <translation>Criar um polígono regular no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateSlot</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6445"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6446"/> <source>Create slot</source> <translation>Criar uma fresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6447"/> <source>Create a slot in the sketch</source> <translation>Criar uma fresta no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateSquare</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6666"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6667"/> <source>Create square</source> <translation>Criar quadrado</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6668"/> <source>Create a square in the sketch</source> <translation>Criar um quadrado no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateText</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4972"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4973"/> <source>Create text</source> <translation>Criar texto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4974"/> <source>Create text in the sketch</source> <translation>Criar um texto no esboço</translation> </message> </context> <context> <name>CmdSketcherCreateTriangle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6639"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6640"/> <source>Create equilateral triangle</source> <translation>Criar triângulo equilátero</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6641"/> <source>Create an equilateral triangle in the sketch</source> <translation>Criar um triângulo equilátero no esboço</translation> </message> </context> <context> <name>CmdSketcherDecreaseDegree</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="525"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="526"/> <source>Decrease B-spline degree</source> <translation>Diminuir grau B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="527"/> <source>Decreases the degree of the B-spline</source> <translation>Diminui o grau de uma B-spline</translation> </message> </context> <context> <name>CmdSketcherDecreaseKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="756"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="757"/> <source>Decrease knot multiplicity</source> <translation>Diminuir a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="758"/> <source>Decreases the multiplicity of the selected knot of a B-spline</source> <translation>Diminui a multiplicidade do nó selecionado de uma B-spline</translation> </message> </context> <context> <name>CmdSketcherDeleteAllConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="2094"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2095"/> <source>Delete all constraints</source> <translation>Excluir todas as restrições</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2096"/> <source>Delete all constraints in the sketch</source> <translation>Excluir todas as restrições do esboço</translation> </message> </context> <context> <name>CmdSketcherDeleteAllGeometry</name> <message> <location filename="../../CommandSketcherTools.cpp" line="2033"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2034"/> <source>Delete all geometry</source> <translation>Excluir toda a geometria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2035"/> <source>Delete all geometry and constraints in the current sketch, with the exception of external geometry</source> <translation>Excluir todas as restrições e geometria do esboço atual, com exceção da geometria externa</translation> </message> </context> <context> <name>CmdSketcherEditSketch</name> <message> <location filename="../../Command.cpp" line="265"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="266"/> <source>Edit sketch</source> <translation>Editar esboço</translation> </message> <message> <location filename="../../Command.cpp" line="267"/> <source>Edit the selected sketch.</source> <translation>Editar o esboço selecionado.</translation> </message> </context> <context> <name>CmdSketcherExtend</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5844"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5845"/> <source>Extend edge</source> <translation>Prolongar aresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5846"/> <source>Extend an edge with respect to the picked position</source> <translation>Estende uma aresta em relação à posição escolhida</translation> </message> </context> <context> <name>CmdSketcherExternal</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6028"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6029"/> <source>External geometry</source> <translation>Geometria externa</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6030"/> <source>Create an edge linked to an external geometry</source> <translation>Criar uma aresta ligada a uma geometria externa</translation> </message> </context> <context> <name>CmdSketcherIncreaseDegree</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="452"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="453"/> <source>Increase B-spline degree</source> <translation>Aumentar grau B-spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="454"/> <source>Increases the degree of the B-spline</source> <translation>Aumenta o grau da B-spline</translation> </message> </context> <context> <name>CmdSketcherIncreaseKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="602"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="603"/> <source>Increase knot multiplicity</source> <translation>Aumentar a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="604"/> <source>Increases the multiplicity of the selected knot of a B-spline</source> <translation>Aumenta a multiplicidade do nó selecionado de uma B-spline</translation> </message> </context> <context> <name>CmdSketcherLeaveSketch</name> <message> <location filename="../../Command.cpp" line="295"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="296"/> <source>Leave sketch</source> <translation>Sair do esboço</translation> </message> <message> <location filename="../../Command.cpp" line="297"/> <source>Finish editing the active sketch.</source> <translation>Finaliza a edição do esboço ativo.</translation> </message> </context> <context> <name>CmdSketcherMapSketch</name> <message> <location filename="../../Command.cpp" line="507"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="508"/> <source>Map sketch to face...</source> <translation>Esboço para face...</translation> </message> <message> <location filename="../../Command.cpp" line="509"/> <source>Set the 'Support' of a sketch. First select the supporting geometry, for example, a face or an edge of a solid object, then call this command, then choose the desired sketch.</source> <translation>Defina o suporte de um esboço. Selecione primeiro a geometria de suporte, por exemplo uma face ou uma aresta de um objeto sólido, em seguida, execute este comando e escolha o esboço desejado.</translation> </message> <message> <location filename="../../Command.cpp" line="561"/> <source>Some of the selected objects depend on the sketch to be mapped. Circular dependencies are not allowed.</source> <translation>Alguns dos objetos selecionados dependem do esboço a ser mapeado. Dependências circulares não são permitidas.</translation> </message> </context> <context> <name>CmdSketcherMergeSketches</name> <message> <location filename="../../Command.cpp" line="863"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="864"/> <source>Merge sketches</source> <translation>Mesclar esboços</translation> </message> <message> <location filename="../../Command.cpp" line="865"/> <source>Create a new sketch from merging two or more selected sketches.</source> <translation>Criar um novo esboço ao mesclar dois ou mais esboços selecionados.</translation> </message> <message> <location filename="../../Command.cpp" line="878"/> <source>Wrong selection</source> <translation>Seleção errada</translation> </message> <message> <location filename="../../Command.cpp" line="879"/> <source>Select at least two sketches.</source> <translation>Selecione pelo menos dois esboços.</translation> </message> </context> <context> <name>CmdSketcherMirrorSketch</name> <message> <location filename="../../Command.cpp" line="756"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="757"/> <source>Mirror sketch</source> <translation>Espelhar o esboço</translation> </message> <message> <location filename="../../Command.cpp" line="758"/> <source>Create a new mirrored sketch for each selected sketch by using the X or Y axes, or the origin point, as mirroring reference.</source> <translation>Criar um novo esboço espelhado para cada esboço selecionado usando os eixos X ou Y ou o ponto de origem como referência espelhada.</translation> </message> <message> <location filename="../../Command.cpp" line="773"/> <source>Wrong selection</source> <translation>Seleção errada</translation> </message> <message> <location filename="../../Command.cpp" line="774"/> <source>Select one or more sketches.</source> <translation>Selecione um ou mais esboços.</translation> </message> </context> <context> <name>CmdSketcherMove</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1601"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1602"/> <source>Move</source> <translation>Mover</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1603"/> <source>Moves the geometry taking as reference the last selected point</source> <translation>Move a geometria usando como referência o último ponto selecionado</translation> </message> </context> <context> <name>CmdSketcherNewSketch</name> <message> <location filename="../../Command.cpp" line="142"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="143"/> <source>Create sketch</source> <translation>Criar um esboço</translation> </message> <message> <location filename="../../Command.cpp" line="144"/> <source>Create a new sketch.</source> <translation>Criar um novo esboço.</translation> </message> </context> <context> <name>CmdSketcherRectangularArray</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1895"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1896"/> <source>Rectangular array</source> <translation>Rede retangular</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1897"/> <source>Creates a rectangular array pattern of the geometry taking as reference the last selected point</source> <translation>Cria um padrão retangular da geometria com referência ao último ponto selecionado</translation> </message> </context> <context> <name>CmdSketcherReorientSketch</name> <message> <location filename="../../Command.cpp" line="380"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="381"/> <source>Reorient sketch...</source> <translation>Reorientar um esboço...</translation> </message> <message> <location filename="../../Command.cpp" line="382"/> <source>Place the selected sketch on one of the global coordinate planes. This will clear the 'Support' property, if any.</source> <translation>Coloque o esboço selecionado em um dos planos de coordenadas globais. Isto irá limpar a propriedade 'Suporte', se houver.</translation> </message> </context> <context> <name>CmdSketcherRestoreInternalAlignmentGeometry</name> <message> <location filename="../../CommandSketcherTools.cpp" line="906"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="907"/> <source>Show/hide internal geometry</source> <translation>Mostrar/ocultar geometria interna</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="908"/> <source>Show all internal geometry or hide unused internal geometry</source> <translation>Mostrar toda a geometria interna ou ocultar a geometria interna não utilizada</translation> </message> </context> <context> <name>CmdSketcherSelectConflictingConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="652"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="653"/> <location filename="../../CommandSketcherTools.cpp" line="654"/> <source>Select conflicting constraints</source> <translation>Selecionar restrições conflitantes</translation> </message> </context> <context> <name>CmdSketcherSelectConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="296"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="297"/> <source>Select associated constraints</source> <translation>Selecionar restrições associadas</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="298"/> <source>Select the constraints associated with the selected geometrical elements</source> <translation>Selecionar as restrições associadas aos elementos geométricos selecionados</translation> </message> </context> <context> <name>CmdSketcherSelectElementsAssociatedWithConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="703"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="704"/> <source>Select associated geometry</source> <translation>Selecionar geometria associada</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="705"/> <source>Select the geometrical elements associated with the selected constraints</source> <translation>Selecionar os elementos geométricos associados às restrições selecionadas</translation> </message> </context> <context> <name>CmdSketcherSelectElementsWithDoFs</name> <message> <location filename="../../CommandSketcherTools.cpp" line="823"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="824"/> <source>Select unconstrained DoF</source> <translation>Selecionar grau de liberdade não restrito</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="825"/> <source>Select geometrical elements where the solver still detects unconstrained degrees of freedom.</source> <translation>Selecionar os elementos geométricos onde o calculador ainda detecta graus de liberdade sem restrições.</translation> </message> </context> <context> <name>CmdSketcherSelectHorizontalAxis</name> <message> <location filename="../../CommandSketcherTools.cpp" line="454"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="455"/> <source>Select horizontal axis</source> <translation>Selecionar eixo horizontal</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="456"/> <source>Select the local horizontal axis of the sketch</source> <translation>Selecionar o eixo horizontal local do esboço</translation> </message> </context> <context> <name>CmdSketcherSelectMalformedConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="547"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="548"/> <location filename="../../CommandSketcherTools.cpp" line="549"/> <source>Select malformed constraints</source> <translation>Selecione restrições malformadas</translation> </message> </context> <context> <name>CmdSketcherSelectOrigin</name> <message> <location filename="../../CommandSketcherTools.cpp" line="368"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="369"/> <source>Select origin</source> <translation>Selecionar a origem</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="370"/> <source>Select the local origin point of the sketch</source> <translation>Selecionar o ponto de origem local do esboço</translation> </message> </context> <context> <name>CmdSketcherSelectPartiallyRedundantConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="599"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="600"/> <location filename="../../CommandSketcherTools.cpp" line="601"/> <source>Select partially redundant constraints</source> <translation>Selecionar restrições parcialmente redundantes</translation> </message> </context> <context> <name>CmdSketcherSelectRedundantConstraints</name> <message> <location filename="../../CommandSketcherTools.cpp" line="495"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="496"/> <location filename="../../CommandSketcherTools.cpp" line="497"/> <source>Select redundant constraints</source> <translation>Selecionar restrições redundantes</translation> </message> </context> <context> <name>CmdSketcherSelectVerticalAxis</name> <message> <location filename="../../CommandSketcherTools.cpp" line="412"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="413"/> <source>Select vertical axis</source> <translation>Selecionar o eixo vertical</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="414"/> <source>Select the local vertical axis of the sketch</source> <translation>Selecionar o eixo vertical local do esboço</translation> </message> </context> <context> <name>CmdSketcherStopOperation</name> <message> <location filename="../../Command.cpp" line="339"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="340"/> <source>Stop operation</source> <translation>Parar a operação</translation> </message> <message> <location filename="../../Command.cpp" line="341"/> <source>When in edit mode, stop the active operation (drawing, constraining, etc.).</source> <translation>Quando estiver no modo de edição, para a operação ativa (desenho, restrição, etc.).</translation> </message> </context> <context> <name>CmdSketcherSwitchVirtualSpace</name> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="92"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="93"/> <source>Switch virtual space</source> <translation>Alternar espaço virtual</translation> </message> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="94"/> <source>Switches the selected constraints or the view to the other virtual space</source> <translation>Alterna as restrições selecionadas para um outro espaço virtual</translation> </message> </context> <context> <name>CmdSketcherSymmetry</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1000"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1001"/> <source>Symmetry</source> <translation>Simetria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1002"/> <source>Creates symmetric geometry with respect to the last selected line or point</source> <translation>Cria uma geometria simétrica em relação ao último ponto ou linha selecionada</translation> </message> </context> <context> <name>CmdSketcherToggleActiveConstraint</name> <message> <location filename="../../CommandConstraints.cpp" line="7643"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7644"/> <source>Activate/deactivate constraint</source> <translation>Ativar/desativar restrição</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7645"/> <source>Activates or deactivates the selected constraints</source> <translation>Ativa ou desativa as restrições selecionadas</translation> </message> </context> <context> <name>CmdSketcherToggleConstruction</name> <message> <location filename="../../CommandAlterGeometry.cpp" line="73"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandAlterGeometry.cpp" line="74"/> <source>Toggle construction geometry</source> <translation>Ativa/desativa a geometria de construção</translation> </message> <message> <location filename="../../CommandAlterGeometry.cpp" line="75"/> <source>Toggles the toolbar or selected geometry to/from construction mode</source> <translation>Ativa/desativa a barra de ferramentas ou geometria selecionada de/para o modo de construção</translation> </message> </context> <context> <name>CmdSketcherToggleDrivingConstraint</name> <message> <location filename="../../CommandConstraints.cpp" line="7517"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7518"/> <source>Toggle driving/reference constraint</source> <translation>Ativar/desativar restrição atuante ou de referência</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7519"/> <source>Set the toolbar, or the selected constraints, into driving or reference mode</source> <translation>Colocar a barra de ferramentas, ou as restrições selecionadas, no modo atuante ou de referência</translation> </message> </context> <context> <name>CmdSketcherTrimming</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5530"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5531"/> <source>Trim edge</source> <translation>Recortar aresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5532"/> <source>Trim an edge with respect to the picked position</source> <translation>Aparar uma aresta em relação a posição escolhida</translation> </message> </context> <context> <name>CmdSketcherValidateSketch</name> <message> <location filename="../../Command.cpp" line="718"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="719"/> <source>Validate sketch...</source> <translation>Validar um esboço...</translation> </message> <message> <location filename="../../Command.cpp" line="720"/> <source>Validate a sketch by looking at missing coincidences, invalid constraints, degenerated geometry, etc.</source> <translation>Validar um esboço olhando para coincidências faltando, restrições inválidas, geometria corrompida, etc.</translation> </message> <message> <location filename="../../Command.cpp" line="735"/> <source>Select only one sketch.</source> <translation>Selecione apenas um esboço.</translation> </message> <message> <location filename="../../Command.cpp" line="734"/> <source>Wrong selection</source> <translation>Seleção errada</translation> </message> </context> <context> <name>CmdSketcherViewSection</name> <message> <location filename="../../Command.cpp" line="947"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="948"/> <source>View section</source> <translation>Ver seção</translation> </message> <message> <location filename="../../Command.cpp" line="949"/> <source>When in edit mode, switch between section view and full view.</source> <translation>Quando em modo de edição, alterna entre vista da seção e vista completa.</translation> </message> </context> <context> <name>CmdSketcherViewSketch</name> <message> <location filename="../../Command.cpp" line="679"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="680"/> <source>View sketch</source> <translation>Ver esboço</translation> </message> <message> <location filename="../../Command.cpp" line="681"/> <source>When in edit mode, set the camera orientation perpendicular to the sketch plane.</source> <translation>Quando estiver em modo de edição, coloca a orientação da câmera perpendicular ao plano do esboço.</translation> </message> </context> <context> <name>Command</name> <message> <location filename="../../CommandConstraints.cpp" line="1158"/> <location filename="../../CommandConstraints.cpp" line="1233"/> <source>Add horizontal constraint</source> <translation>Adicionar restrição horizontal</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1167"/> <location filename="../../CommandConstraints.cpp" line="1259"/> <location filename="../../CommandConstraints.cpp" line="1494"/> <source>Add horizontal alignment</source> <translation>Adicionar alinhamento horizontal</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1395"/> <location filename="../../CommandConstraints.cpp" line="1469"/> <source>Add vertical constraint</source> <translation>Adicionar restrição vertical</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1403"/> <source>Add vertical alignment</source> <translation>Adicionar alinhamento vertical</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1608"/> <source>Add 'Lock' constraint</source> <translation>Adicionar restrição 'Travar'</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1649"/> <source>Add relative 'Lock' constraint</source> <translation>Adicionar restrição 'Travar' relativa</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1694"/> <source>Add fixed constraint</source> <translation>Adicionar restrição fixa</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1836"/> <source>Add 'Block' constraint</source> <translation>Adicionar restrição 'Bloquear'</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1880"/> <source>Add block constraint</source> <translation>Adicionar restrição 'Bloquear'</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2026"/> <location filename="../../CommandConstraints.cpp" line="2126"/> <location filename="../../CommandConstraints.cpp" line="2215"/> <location filename="../../CommandSketcherTools.cpp" line="144"/> <location filename="../../CommandSketcherTools.cpp" line="250"/> <source>Add coincident constraint</source> <translation>Adicionar restrição coincidente</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2150"/> <source>Swap edge tangency with ptp tangency</source> <translation>Trocar tangência de aresta por tangência ponto-a-ponto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2321"/> <location filename="../../CommandConstraints.cpp" line="2453"/> <source>Add distance from horizontal axis constraint</source> <translation>Adiciona restrição na distância ao eixo horizontal</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2329"/> <location filename="../../CommandConstraints.cpp" line="2460"/> <source>Add distance from vertical axis constraint</source> <translation>Adiciona restrição na distância ao eixo vertical</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2337"/> <location filename="../../CommandConstraints.cpp" line="2467"/> <source>Add point to point distance constraint</source> <translation>Adiciona restrição na distância ponto a ponto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2372"/> <location filename="../../CommandConstraints.cpp" line="2542"/> <source>Add point to line Distance constraint</source> <translation>Adicionar restrição na distância entre ponto e linha</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2406"/> <location filename="../../CommandConstraints.cpp" line="2499"/> <source>Add length constraint</source> <translation>Adiciona restrição de comprimento</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2657"/> <location filename="../../CommandConstraints.cpp" line="2740"/> <source>Add point on object constraint</source> <translation>Adiciona restrição tipo 'ponto-no-objeto'</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2908"/> <location filename="../../CommandConstraints.cpp" line="3010"/> <source>Add point to point horizontal distance constraint</source> <translation>Adicionar restrição de distância horizontal ponto a ponto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2939"/> <source>Add fixed x-coordinate constraint</source> <translation>Adiciona restrição de coordenada x fixa</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3157"/> <location filename="../../CommandConstraints.cpp" line="3259"/> <source>Add point to point vertical distance constraint</source> <translation>Adiciona restrição de distância vertical ponto a ponto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3187"/> <source>Add fixed y-coordinate constraint</source> <translation>Adiciona restrição de coordenada y fixa</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3388"/> <location filename="../../CommandConstraints.cpp" line="3429"/> <source>Add parallel constraint</source> <translation>Adiciona restrição paralela</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3553"/> <location filename="../../CommandConstraints.cpp" line="3621"/> <location filename="../../CommandConstraints.cpp" line="3775"/> <location filename="../../CommandConstraints.cpp" line="3811"/> <location filename="../../CommandConstraints.cpp" line="3956"/> <location filename="../../CommandConstraints.cpp" line="3990"/> <location filename="../../CommandConstraints.cpp" line="4032"/> <source>Add perpendicular constraint</source> <translation>Adiciona restrição perpendicular</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3658"/> <source>Add perpendicularity constraint</source> <translation>Adicionar restrição de perpendicularidade</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4187"/> <location filename="../../CommandConstraints.cpp" line="4239"/> <location filename="../../CommandConstraints.cpp" line="4275"/> <location filename="../../CommandConstraints.cpp" line="4468"/> <location filename="../../CommandConstraints.cpp" line="4625"/> <location filename="../../CommandConstraints.cpp" line="4683"/> <location filename="../../CommandConstraints.cpp" line="4704"/> <source>Add tangent constraint</source> <translation>Adiciona restrição tangente</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4317"/> <source>Swap coincident+tangency with ptp tangency</source> <translation>Trocar coincidência+tangência por tangência ponto-a-ponto</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4354"/> <location filename="../../CommandConstraints.cpp" line="4361"/> <location filename="../../CommandConstraints.cpp" line="4368"/> <location filename="../../CommandConstraints.cpp" line="4392"/> <location filename="../../CommandConstraints.cpp" line="4400"/> <location filename="../../CommandConstraints.cpp" line="4425"/> <location filename="../../CommandConstraints.cpp" line="4433"/> <location filename="../../CommandConstraints.cpp" line="4460"/> <location filename="../../CommandConstraints.cpp" line="4546"/> <location filename="../../CommandConstraints.cpp" line="4553"/> <location filename="../../CommandConstraints.cpp" line="4560"/> <location filename="../../CommandConstraints.cpp" line="4584"/> <location filename="../../CommandConstraints.cpp" line="4591"/> <location filename="../../CommandConstraints.cpp" line="4617"/> <source>Add tangent constraint point</source> <translation>Adiciona ponto de tangência</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4881"/> <location filename="../../CommandConstraints.cpp" line="4946"/> <location filename="../../CommandConstraints.cpp" line="4965"/> <location filename="../../CommandConstraints.cpp" line="5123"/> <source>Add radius constraint</source> <translation>Adicionar restrição de raio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5382"/> <location filename="../../CommandConstraints.cpp" line="5441"/> <location filename="../../CommandConstraints.cpp" line="5453"/> <location filename="../../CommandConstraints.cpp" line="5608"/> <source>Add diameter constraint</source> <translation>Adicionar restrição de diâmetro</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5940"/> <location filename="../../CommandConstraints.cpp" line="6073"/> <location filename="../../CommandConstraints.cpp" line="6103"/> <location filename="../../CommandConstraints.cpp" line="6127"/> <location filename="../../CommandConstraints.cpp" line="6240"/> <location filename="../../CommandConstraints.cpp" line="6294"/> <source>Add angle constraint</source> <translation>Adicionar restrição de ângulo</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6508"/> <location filename="../../CommandConstraints.cpp" line="6560"/> <source>Add equality constraint</source> <translation>Adicionar restrição de igualdade</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6681"/> <location filename="../../CommandConstraints.cpp" line="6733"/> <location filename="../../CommandConstraints.cpp" line="6749"/> <location filename="../../CommandConstraints.cpp" line="6835"/> <location filename="../../CommandConstraints.cpp" line="6870"/> <source>Add symmetric constraint</source> <translation>Adicionar restrição simétrica</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7009"/> <source>Add Snell's law constraint</source> <translation>Adicionar restrição lei de Snell</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7218"/> <location filename="../../CommandConstraints.cpp" line="7396"/> <source>Add internal alignment constraint</source> <translation>Adicionar restrição de alinhamento interno</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7602"/> <source>Toggle constraint to driving/reference</source> <translation>Alternar o tipo da restrição entre motriz ou referência</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7686"/> <source>Activate/Deactivate constraint</source> <translation>Ativar/desativar restrição</translation> </message> <message> <location filename="../../Command.cpp" line="207"/> <source>Create a new sketch on a face</source> <translation>Criar um novo esboço em uma face</translation> </message> <message> <location filename="../../Command.cpp" line="239"/> <source>Create a new sketch</source> <translation>Criar um novo esboço</translation> </message> <message> <location filename="../../Command.cpp" line="489"/> <source>Reorient sketch</source> <translation>Reorientar um esboço</translation> </message> <message> <location filename="../../Command.cpp" line="644"/> <source>Attach sketch</source> <translation>Anexar esboço</translation> </message> <message> <location filename="../../Command.cpp" line="649"/> <source>Detach sketch</source> <translation>Desanexar esboço</translation> </message> <message> <location filename="../../Command.cpp" line="789"/> <source>Create a mirrored sketch for each selected sketch</source> <translation>Criar um esboço espelhado para cada esboço selecionado</translation> </message> <message> <location filename="../../Command.cpp" line="888"/> <source>Merge sketches</source> <translation>Mesclar esboços</translation> </message> <message> <location filename="../../CommandAlterGeometry.cpp" line="137"/> <source>Toggle draft from/to draft</source> <translation>Alternar modo rascunho</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="319"/> <source>Add sketch line</source> <translation>Adicionar linha do esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="493"/> <source>Add sketch box</source> <translation>Adicionar caixa de esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="981"/> <source>Add line to sketch wire</source> <translation>Adicionar linha ao arame do esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1001"/> <source>Add arc to sketch wire</source> <translation>Adicionar arco ao arame do esboço</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1444"/> <location filename="../../CommandCreateGeo.cpp" line="1713"/> <source>Add sketch arc</source> <translation>Adicionar esboço de arco</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="1982"/> <location filename="../../CommandCreateGeo.cpp" line="4668"/> <source>Add sketch circle</source> <translation>Adicionar esboço de círculo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="2741"/> <source>Add sketch ellipse</source> <translation>Adicionar esboço de elipse</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3110"/> <source>Add sketch arc of ellipse</source> <translation>Adicionar esboço de arco de elipse</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3448"/> <source>Add sketch arc of hyperbola</source> <translation>Adicionar esboço de arco de hipérbole</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="3750"/> <source>Add sketch arc of Parabola</source> <translation>Adicionar arco de parábola</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4073"/> <source>Add Pole circle</source> <translation>Adicionar círculo de polo</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4895"/> <source>Add sketch point</source> <translation>Adicionar ponto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5144"/> <location filename="../../CommandCreateGeo.cpp" line="5222"/> <source>Create fillet</source> <translation>Criar filete</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5505"/> <source>Trim edge</source> <translation>Recortar aresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5776"/> <source>Extend edge</source> <translation>Prolongar aresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5992"/> <source>Add external geometry</source> <translation>Adicionar geometria externa</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6173"/> <source>Add carbon copy</source> <translation>Adicionar cópia de carbono</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6354"/> <source>Add slot</source> <translation>Adicionar fresta</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6567"/> <source>Add hexagon</source> <translation>Adicionar hexágono</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="413"/> <source>Convert to NURBS</source> <translation>Converter para NURBS</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="479"/> <source>Increase spline degree</source> <translation>Aumentar grau de spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="554"/> <source>Decrease spline degree</source> <translation>Diminuir grau de spline</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="647"/> <source>Increase knot multiplicity</source> <translation>Aumentar a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="801"/> <source>Decrease knot multiplicity</source> <translation>Diminuir a multiplicidade de nós</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="964"/> <source>Exposing Internal Geometry</source> <translation>Exposição da geometria interna</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1174"/> <source>Create symmetric geometry</source> <translation>Criar geometria simétrica</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1316"/> <source>Copy/clone/move geometry</source> <translation>Copiar/clonar/mover geometria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1840"/> <source>Create copy of geometry</source> <translation>Criar cópia da geometria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2060"/> <source>Delete all geometry</source> <translation>Excluir toda a geometria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2120"/> <source>Delete All Constraints</source> <translation>Excluir todas as restrições</translation> </message> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="155"/> <source>Toggle constraints to the other virtual space</source> <translation>Enviar restrições para o outro espaço virtual</translation> </message> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="163"/> <location filename="../../TaskSketcherConstrains.cpp" line="862"/> <source>Update constraint's virtual space</source> <translation>Atualizar espaço virtual das restrições</translation> </message> <message> <location filename="../../DrawSketchHandler.cpp" line="601"/> <source>Add auto constraints</source> <translation>Adicionar restrições automáticas</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="625"/> <source>Swap constraint names</source> <translation>Trocar nomes de restrição</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="847"/> <source>Rename sketch constraint</source> <translation>Renomear restrição do esboço</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="840"/> <source>Drag Point</source> <translation>Arrastar Ponto</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="871"/> <source>Drag Curve</source> <translation>Arrastar Curva</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="922"/> <source>Drag Constraint</source> <translation>Restrição de arrasto</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="1099"/> <source>Modify sketch constraints</source> <translation>Modificar restrições do esboço</translation> </message> </context> <context> <name>Exceptions</name> <message> <location filename="../../../App/SketchAnalysis.cpp" line="373"/> <source>Autoconstrain error: Unsolvable sketch while applying coincident constraints.</source> <translation>Erro de restrição automática: esboço insolúvel ao aplicar restrições coincidentes.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="454"/> <source>Autoconstrain error: Unsolvable sketch while applying vertical/horizontal constraints.</source> <translation>Erro de restrição automática: esboço insolúvel ao aplicar restrições verticais/horizontais.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="651"/> <source>Autoconstrain error: Unsolvable sketch while applying equality constraints.</source> <translation>Erro de restrição automática: esboço insolúvel ao aplicar restrições de igualdade.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="705"/> <source>Autoconstrain error: Unsolvable sketch without constraints.</source> <translation>Erro de restrição automática: esboço insolúvel sem restrições.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="742"/> <source>Autoconstrain error: Unsolvable sketch after applying horizontal and vertical constraints.</source> <translation>Erro de restrição automática: esboço irresolvível após a aplicação de restrições horizontais e verticais.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="764"/> <source>Autoconstrain error: Unsolvable sketch after applying point-on-point constraints.</source> <translation>Erro de restrição automática: esboço insolúvel após a aplicação de restrições de ponto-em-ponto.</translation> </message> <message> <location filename="../../../App/SketchAnalysis.cpp" line="792"/> <source>Autoconstrain error: Unsolvable sketch after applying equality constraints.</source> <translation>Erro de restrição automática: esboço insolúvel após a aplicação de restrições de igualdade.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="1966"/> <source>Unable to guess intersection of curves. Try adding a coincident constraint between the vertices of the curves you are intending to fillet.</source> <translation>Não é possível adivinhar a intersecção das curvas. Tente adicionar uma restrição coincidente entre os vértices das curvas que você pretende filetar.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5606"/> <source>This version of OCE/OCC does not support knot operation. You need 6.9.0 or higher.</source> <translation>Esta versão do OCE / OCC não suporta operação de nó. Você precisa de 6.9.0 ou superior.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5610"/> <source>BSpline Geometry Index (GeoID) is out of bounds.</source> <translation>Índice de geometria BSpline (GeoID) está fora dos limites.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5613"/> <source>You are requesting no change in knot multiplicity.</source> <translation>Você não solicitou nenhuma mudança de multiplicidade em nós.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5618"/> <source>The Geometry Index (GeoId) provided is not a B-spline curve.</source> <translation>O índice de geometria (GeoId) fornecida não é uma curva B-spline.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5625"/> <source>The knot index is out of bounds. Note that in accordance with OCC notation, the first knot has index 1 and not zero.</source> <translation>O índice do nó está fora dos limites. Note que, de acordo com a notação do OCC, o primeiro nó tem índice 1 e não zero.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5632"/> <source>The multiplicity cannot be increased beyond the degree of the B-spline.</source> <translation>A multiplicidade não pode ser aumentada além do grau de B-spline.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5635"/> <source>The multiplicity cannot be decreased beyond zero.</source> <translation>A multiplicidade não pode ser diminuída abaixo de zero.</translation> </message> <message> <location filename="../../../App/SketchObject.cpp" line="5647"/> <source>OCC is unable to decrease the multiplicity within the maximum tolerance.</source> <translation>O OCC não consegue diminuir a multiplicidade dentro de tolerância máxima.</translation> </message> </context> <context> <name>Gui::TaskView::TaskSketcherCreateCommands</name> <message> <location filename="../../TaskSketcherCreateCommands.cpp" line="41"/> <source>Appearance</source> <translation>Aparência</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../../AppSketcherGui.cpp" line="135"/> <location filename="../../AppSketcherGui.cpp" line="136"/> <location filename="../../AppSketcherGui.cpp" line="137"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Command.cpp" line="111"/> <source>There are no modes that accept the selected set of subelements</source> <translation>Não existem modos que aceitem o conjunto de sub-elementos selecionado</translation> </message> <message> <location filename="../../Command.cpp" line="114"/> <source>Broken link to support subelements</source> <translation>Ligação perdida aos sub-elementos de suporte</translation> </message> <message> <location filename="../../Command.cpp" line="117"/> <location filename="../../Command.cpp" line="126"/> <source>Unexpected error</source> <translation>Erro inesperado</translation> </message> <message> <location filename="../../Command.cpp" line="121"/> <source>Face is non-planar</source> <translation>A face não é plana</translation> </message> <message> <location filename="../../Command.cpp" line="123"/> <source>Selected shapes are of wrong form (e.g., a curved edge where a straight one is needed)</source> <translation>As formas selecionadas são do tipo errado (por exemplo, uma aresta curva onde uma reta é necessária)</translation> </message> <message> <location filename="../../Command.cpp" line="164"/> <source>Sketch mapping</source> <translation>Mapeamento de esboço</translation> </message> <message> <location filename="../../Command.cpp" line="165"/> <source>Can't map the sketch to selected object. %1.</source> <translation>Não é possível mapear o esboço no objeto selecionado. %1.</translation> </message> <message> <location filename="../../Command.cpp" line="172"/> <location filename="../../Command.cpp" line="590"/> <source>Don't attach</source> <translation>Não anexar</translation> </message> <message> <location filename="../../CommandAlterGeometry.cpp" line="123"/> <location filename="../../CommandAlterGeometry.cpp" line="131"/> <location filename="../../CommandConstraints.cpp" line="127"/> <location filename="../../CommandConstraints.cpp" line="133"/> <location filename="../../CommandConstraints.cpp" line="1085"/> <location filename="../../CommandConstraints.cpp" line="1323"/> <location filename="../../CommandConstraints.cpp" line="1559"/> <location filename="../../CommandConstraints.cpp" line="1582"/> <location filename="../../CommandConstraints.cpp" line="1586"/> <location filename="../../CommandConstraints.cpp" line="1782"/> <location filename="../../CommandConstraints.cpp" line="1812"/> <location filename="../../CommandConstraints.cpp" line="1816"/> <location filename="../../CommandConstraints.cpp" line="2093"/> <location filename="../../CommandConstraints.cpp" line="2104"/> <location filename="../../CommandConstraints.cpp" line="2114"/> <location filename="../../CommandConstraints.cpp" line="2284"/> <location filename="../../CommandConstraints.cpp" line="2295"/> <location filename="../../CommandConstraints.cpp" line="2393"/> <location filename="../../CommandConstraints.cpp" line="2426"/> <location filename="../../CommandConstraints.cpp" line="2518"/> <location filename="../../CommandConstraints.cpp" line="2632"/> <location filename="../../CommandConstraints.cpp" line="2672"/> <location filename="../../CommandConstraints.cpp" line="2678"/> <location filename="../../CommandConstraints.cpp" line="2695"/> <location filename="../../CommandConstraints.cpp" line="2706"/> <location filename="../../CommandConstraints.cpp" line="2754"/> <location filename="../../CommandConstraints.cpp" line="2762"/> <location filename="../../CommandConstraints.cpp" line="2778"/> <location filename="../../CommandConstraints.cpp" line="2839"/> <location filename="../../CommandConstraints.cpp" line="2850"/> <location filename="../../CommandConstraints.cpp" line="2879"/> <location filename="../../CommandConstraints.cpp" line="2929"/> <location filename="../../CommandConstraints.cpp" line="2958"/> <location filename="../../CommandConstraints.cpp" line="2987"/> <location filename="../../CommandConstraints.cpp" line="3091"/> <location filename="../../CommandConstraints.cpp" line="3102"/> <location filename="../../CommandConstraints.cpp" line="3127"/> <location filename="../../CommandConstraints.cpp" line="3177"/> <location filename="../../CommandConstraints.cpp" line="3207"/> <location filename="../../CommandConstraints.cpp" line="3236"/> <location filename="../../CommandConstraints.cpp" line="3337"/> <location filename="../../CommandConstraints.cpp" line="3350"/> <location filename="../../CommandConstraints.cpp" line="3364"/> <location filename="../../CommandConstraints.cpp" line="3380"/> <location filename="../../CommandConstraints.cpp" line="3418"/> <location filename="../../CommandConstraints.cpp" line="3505"/> <location filename="../../CommandConstraints.cpp" line="3518"/> <location filename="../../CommandConstraints.cpp" line="3548"/> <location filename="../../CommandConstraints.cpp" line="3601"/> <location filename="../../CommandConstraints.cpp" line="3638"/> <location filename="../../CommandConstraints.cpp" line="3647"/> <location filename="../../CommandConstraints.cpp" line="3653"/> <location filename="../../CommandConstraints.cpp" line="3677"/> <location filename="../../CommandConstraints.cpp" line="3686"/> <location filename="../../CommandConstraints.cpp" line="3695"/> <location filename="../../CommandConstraints.cpp" line="3823"/> <location filename="../../CommandConstraints.cpp" line="3858"/> <location filename="../../CommandConstraints.cpp" line="3867"/> <location filename="../../CommandConstraints.cpp" line="3876"/> <location filename="../../CommandConstraints.cpp" line="4027"/> <location filename="../../CommandConstraints.cpp" line="4139"/> <location filename="../../CommandConstraints.cpp" line="4152"/> <location filename="../../CommandConstraints.cpp" line="4182"/> <location filename="../../CommandConstraints.cpp" line="4234"/> <location filename="../../CommandConstraints.cpp" line="4255"/> <location filename="../../CommandConstraints.cpp" line="4264"/> <location filename="../../CommandConstraints.cpp" line="4270"/> <location filename="../../CommandConstraints.cpp" line="4294"/> <location filename="../../CommandConstraints.cpp" line="4300"/> <location filename="../../CommandConstraints.cpp" line="4482"/> <location filename="../../CommandConstraints.cpp" line="4518"/> <location filename="../../CommandConstraints.cpp" line="4524"/> <location filename="../../CommandConstraints.cpp" line="4663"/> <location filename="../../CommandConstraints.cpp" line="4699"/> <location filename="../../CommandConstraints.cpp" line="4793"/> <location filename="../../CommandConstraints.cpp" line="4804"/> <location filename="../../CommandConstraints.cpp" line="4865"/> <location filename="../../CommandConstraints.cpp" line="4870"/> <location filename="../../CommandConstraints.cpp" line="5117"/> <location filename="../../CommandConstraints.cpp" line="5304"/> <location filename="../../CommandConstraints.cpp" line="5315"/> <location filename="../../CommandConstraints.cpp" line="5357"/> <location filename="../../CommandConstraints.cpp" line="5372"/> <location filename="../../CommandConstraints.cpp" line="5596"/> <location filename="../../CommandConstraints.cpp" line="5602"/> <location filename="../../CommandConstraints.cpp" line="5890"/> <location filename="../../CommandConstraints.cpp" line="5902"/> <location filename="../../CommandConstraints.cpp" line="5933"/> <location filename="../../CommandConstraints.cpp" line="5995"/> <location filename="../../CommandConstraints.cpp" line="6091"/> <location filename="../../CommandConstraints.cpp" line="6147"/> <location filename="../../CommandConstraints.cpp" line="6287"/> <location filename="../../CommandConstraints.cpp" line="6404"/> <location filename="../../CommandConstraints.cpp" line="6417"/> <location filename="../../CommandConstraints.cpp" line="6433"/> <location filename="../../CommandConstraints.cpp" line="6438"/> <location filename="../../CommandConstraints.cpp" line="6457"/> <location filename="../../CommandConstraints.cpp" line="6487"/> <location filename="../../CommandConstraints.cpp" line="6502"/> <location filename="../../CommandConstraints.cpp" line="6554"/> <location filename="../../CommandConstraints.cpp" line="6636"/> <location filename="../../CommandConstraints.cpp" line="6649"/> <location filename="../../CommandConstraints.cpp" line="6674"/> <location filename="../../CommandConstraints.cpp" line="6696"/> <location filename="../../CommandConstraints.cpp" line="6726"/> <location filename="../../CommandConstraints.cpp" line="6763"/> <location filename="../../CommandConstraints.cpp" line="6786"/> <location filename="../../CommandConstraints.cpp" line="6828"/> <location filename="../../CommandConstraints.cpp" line="6844"/> <location filename="../../CommandConstraints.cpp" line="6971"/> <location filename="../../CommandConstraints.cpp" line="6977"/> <location filename="../../CommandConstraints.cpp" line="7076"/> <location filename="../../CommandConstraints.cpp" line="7089"/> <location filename="../../CommandConstraints.cpp" line="7110"/> <location filename="../../CommandConstraints.cpp" line="7133"/> <location filename="../../CommandConstraints.cpp" line="7155"/> <location filename="../../CommandConstraints.cpp" line="7163"/> <location filename="../../CommandConstraints.cpp" line="7169"/> <location filename="../../CommandConstraints.cpp" line="7325"/> <location filename="../../CommandConstraints.cpp" line="7333"/> <location filename="../../CommandConstraints.cpp" line="7341"/> <location filename="../../CommandConstraints.cpp" line="7347"/> <location filename="../../CommandConstraints.cpp" line="7496"/> <location filename="../../CommandConstraints.cpp" line="7556"/> <location filename="../../CommandConstraints.cpp" line="7564"/> <location filename="../../CommandConstraints.cpp" line="7596"/> <location filename="../../CommandConstraints.cpp" line="7669"/> <location filename="../../CommandConstraints.cpp" line="7680"/> <location filename="../../CommandSketcherBSpline.cpp" line="431"/> <location filename="../../CommandSketcherBSpline.cpp" line="502"/> <location filename="../../CommandSketcherBSpline.cpp" line="580"/> <location filename="../../CommandSketcherBSpline.cpp" line="640"/> <location filename="../../CommandSketcherBSpline.cpp" line="703"/> <location filename="../../CommandSketcherBSpline.cpp" line="794"/> <location filename="../../CommandSketcherBSpline.cpp" line="843"/> <location filename="../../CommandSketcherTools.cpp" line="125"/> <location filename="../../CommandSketcherTools.cpp" line="133"/> <location filename="../../CommandSketcherTools.cpp" line="175"/> <location filename="../../CommandSketcherTools.cpp" line="235"/> <location filename="../../CommandSketcherTools.cpp" line="243"/> <location filename="../../CommandSketcherTools.cpp" line="320"/> <location filename="../../CommandSketcherTools.cpp" line="931"/> <location filename="../../CommandSketcherTools.cpp" line="1024"/> <location filename="../../CommandSketcherTools.cpp" line="1032"/> <location filename="../../CommandSketcherTools.cpp" line="1137"/> <location filename="../../CommandSketcherTools.cpp" line="1146"/> <location filename="../../CommandSketcherTools.cpp" line="1384"/> <location filename="../../CommandSketcherTools.cpp" line="1393"/> <location filename="../../CommandSketcherTools.cpp" line="1452"/> <location filename="../../CommandSketcherTools.cpp" line="1915"/> <location filename="../../CommandSketcherTools.cpp" line="1924"/> <location filename="../../CommandSketcherTools.cpp" line="1986"/> <location filename="../../CommandSketcherVirtualSpace.cpp" line="115"/> <location filename="../../CommandSketcherVirtualSpace.cpp" line="123"/> <location filename="../../CommandSketcherVirtualSpace.cpp" line="146"/> <source>Wrong selection</source> <translation>Seleção errada</translation> </message> <message> <location filename="../../CommandAlterGeometry.cpp" line="124"/> <location filename="../../CommandAlterGeometry.cpp" line="132"/> <source>Select edge(s) from the sketch.</source> <translation>Selecione aresta(s) no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5062"/> <location filename="../../CommandConstraints.cpp" line="5211"/> <location filename="../../CommandConstraints.cpp" line="5541"/> <location filename="../../CommandConstraints.cpp" line="5677"/> <location filename="../../EditDatumDialog.cpp" line="206"/> <source>Dimensional constraint</source> <translation>Restrição de dimensão</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="704"/> <location filename="../../CommandConstraints.cpp" line="715"/> <location filename="../../CommandConstraints.cpp" line="727"/> <source>Only sketch and its support is allowed to select</source> <translation>É permitido selecionar somente um esboço e seu suporte</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="736"/> <source>One of the selected has to be on the sketch</source> <translation>Um dos selecionados tem que ser no esboço</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1086"/> <location filename="../../CommandConstraints.cpp" line="1324"/> <source>Select an edge from the sketch.</source> <translation>Selecione uma aresta do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1111"/> <location filename="../../CommandConstraints.cpp" line="1125"/> <location filename="../../CommandConstraints.cpp" line="1131"/> <location filename="../../CommandConstraints.cpp" line="1150"/> <location filename="../../CommandConstraints.cpp" line="1178"/> <location filename="../../CommandConstraints.cpp" line="1206"/> <location filename="../../CommandConstraints.cpp" line="1220"/> <location filename="../../CommandConstraints.cpp" line="1226"/> <location filename="../../CommandConstraints.cpp" line="1349"/> <location filename="../../CommandConstraints.cpp" line="1363"/> <location filename="../../CommandConstraints.cpp" line="1369"/> <location filename="../../CommandConstraints.cpp" line="1387"/> <location filename="../../CommandConstraints.cpp" line="1413"/> <location filename="../../CommandConstraints.cpp" line="1442"/> <location filename="../../CommandConstraints.cpp" line="1451"/> <location filename="../../CommandConstraints.cpp" line="1462"/> <location filename="../../CommandSketcherTools.cpp" line="165"/> <location filename="../../CommandSketcherTools.cpp" line="267"/> <source>Impossible constraint</source> <translation>Restrição impossível</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1112"/> <location filename="../../CommandConstraints.cpp" line="1207"/> <location filename="../../CommandConstraints.cpp" line="1350"/> <location filename="../../CommandConstraints.cpp" line="1443"/> <source>The selected edge is not a line segment</source> <translation>A aresta selecionada não é um segmento de linha</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1120"/> <location filename="../../CommandConstraints.cpp" line="1215"/> <location filename="../../CommandConstraints.cpp" line="1358"/> <location filename="../../CommandConstraints.cpp" line="1456"/> <location filename="../../CommandConstraints.cpp" line="1826"/> <location filename="../../CommandConstraints.cpp" line="1874"/> <source>Double constraint</source> <translation>Restrição dupla</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1121"/> <location filename="../../CommandConstraints.cpp" line="1216"/> <location filename="../../CommandConstraints.cpp" line="1364"/> <location filename="../../CommandConstraints.cpp" line="1452"/> <source>The selected edge already has a horizontal constraint!</source> <translation>A aresta selecionada já tem uma restrição horizontal!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1126"/> <location filename="../../CommandConstraints.cpp" line="1221"/> <location filename="../../CommandConstraints.cpp" line="1359"/> <location filename="../../CommandConstraints.cpp" line="1457"/> <source>The selected edge already has a vertical constraint!</source> <translation>A aresta selecionada já tem uma restrição vertical!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1132"/> <location filename="../../CommandConstraints.cpp" line="1227"/> <location filename="../../CommandConstraints.cpp" line="1370"/> <location filename="../../CommandConstraints.cpp" line="1463"/> <location filename="../../CommandConstraints.cpp" line="1827"/> <location filename="../../CommandConstraints.cpp" line="1875"/> <source>The selected edge already has a Block constraint!</source> <translation>A aresta selecionada já possui uma restrição de Bloqueio!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1151"/> <source>The selected item(s) can't accept a horizontal constraint!</source> <translation>Os itens selecionados não podem aceitar uma restrição horizontal!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1179"/> <source>There are more than one fixed point selected. Select a maximum of one fixed point!</source> <translation>Mais de um ponto fixo selecionado. Selecione um único ponto fixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1388"/> <source>The selected item(s) can't accept a vertical constraint!</source> <translation>Os itens selecionados não podem aceitar uma restrição vertical!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1414"/> <source>There are more than one fixed points selected. Select a maximum of one fixed point!</source> <translation>Há mais de um ponto fixo selecionado. Selecione no máximo um ponto fixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1560"/> <location filename="../../CommandConstraints.cpp" line="1783"/> <source>Select vertices from the sketch.</source> <translation>Selecione vértices do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1583"/> <source>Select one vertex from the sketch other than the origin.</source> <translation>Selecione um vértice do esboço que não seja a origem.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1587"/> <source>Select only vertices from the sketch. The last selected vertex may be the origin.</source> <translation>Selecione somente os vértices do esboço. O último vértice selecionado pode ser a origem.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1794"/> <source>Wrong solver status</source> <translation>Erro no status do calculador</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="128"/> <source>Cannot add a constraint between two external geometries.</source> <translation>Não é possível adicionar uma restrição entre duas geometrias externas.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="134"/> <source>Cannot add a constraint between two fixed geometries. Fixed geometries involve external geometry, blocked geometry or special points as B-spline knot points.</source> <translation>Não é possível adicionar uma restrição entre duas geometrias fixas. Geometrias fixas podem ser geometria externa, geometria bloqueada, ou pontos especiais como nós de B-spline.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1795"/> <source>A Block constraint cannot be added if the sketch is unsolved or there are redundant and conflicting constraints.</source> <translation>Uma restrição de bloqueio não pode ser adicionada se o esboço não estiver resolvido ou se existirem restrições redundantes e/ou conflitantes.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1813"/> <source>Select one edge from the sketch.</source> <translation>Selecione uma aresta do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1817"/> <source>Select only edges from the sketch.</source> <translation>Selecione somente arestas do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="1845"/> <location filename="../../CommandConstraints.cpp" line="1890"/> <location filename="../../CommandConstraints.cpp" line="3577"/> <location filename="../../CommandConstraints.cpp" line="4056"/> <location filename="../../CommandConstraints.cpp" line="4211"/> <location filename="../../CommandConstraints.cpp" line="4728"/> <location filename="../../CommandConstraints.cpp" line="7039"/> <location filename="../../CommandSketcherBSpline.cpp" line="833"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2094"/> <source>Select two or more points from the sketch.</source> <translation>Selecione dois ou mais pontos no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2105"/> <location filename="../../CommandConstraints.cpp" line="2115"/> <source>Select two or more vertexes from the sketch.</source> <translation>Selecione dois ou mais vértices do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2168"/> <location filename="../../CommandConstraints.cpp" line="4330"/> <source>Constraint Substitution</source> <translation>Substituição de restrição</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2169"/> <source>Endpoint to endpoint tangency was applied instead.</source> <translation>Uma tangência de ponto a ponto de extremidade foi aplicado em vez disso.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2285"/> <source>Select vertexes from the sketch.</source> <translation>Selecione vértices do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2296"/> <location filename="../../CommandConstraints.cpp" line="2427"/> <source>Select exactly one line or one point and one line or two points from the sketch.</source> <translation>Selecione exatamente uma linha ou um ponto e uma linha ou dois pontos no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2394"/> <source>Cannot add a length constraint on an axis!</source> <translation>Não é possível adicionar uma restrição de comprimento em um eixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2519"/> <source>This constraint does not make sense for non-linear curves</source> <translation>Essa restrição não faz sentido para curvas não-lineares</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2633"/> <location filename="../../CommandConstraints.cpp" line="2840"/> <location filename="../../CommandConstraints.cpp" line="3092"/> <location filename="../../CommandConstraints.cpp" line="4794"/> <location filename="../../CommandConstraints.cpp" line="5305"/> <location filename="../../CommandConstraints.cpp" line="5891"/> <source>Select the right things from the sketch.</source> <translation>Selecione as coisas corretas no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2673"/> <location filename="../../CommandConstraints.cpp" line="2755"/> <source>Point on B-spline edge currently unsupported.</source> <translation>Ponto em aresta de Bspline ainda não está suportado.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2779"/> <source>None of the selected points were constrained onto the respective curves, either because they are parts of the same element, or because they are both external geometry.</source> <translation>Nenhum dos pontos selecionados foi restringido para as respectivas curvas, eles são partes do mesmo elemento, ou ambos são geometria externa.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2707"/> <source>Select either one point and several curves, or one curve and several points. You have selected %1 curves and %2 points.</source> <translation>Selecione um ponto e várias curvas, ou uma curva e vários pontos. Você selecionou %1 curvas e %2 pontos.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2679"/> <location filename="../../CommandConstraints.cpp" line="2763"/> <location filename="../../CommandConstraints.cpp" line="3549"/> <location filename="../../CommandConstraints.cpp" line="3654"/> <location filename="../../CommandConstraints.cpp" line="3696"/> <location filename="../../CommandConstraints.cpp" line="3877"/> <location filename="../../CommandConstraints.cpp" line="4028"/> <location filename="../../CommandConstraints.cpp" line="4183"/> <location filename="../../CommandConstraints.cpp" line="4271"/> <location filename="../../CommandConstraints.cpp" line="4301"/> <location filename="../../CommandConstraints.cpp" line="4525"/> <location filename="../../CommandConstraints.cpp" line="4700"/> <location filename="../../CommandConstraints.cpp" line="5358"/> <location filename="../../CommandConstraints.cpp" line="5603"/> <location filename="../../CommandConstraints.cpp" line="5934"/> <location filename="../../CommandConstraints.cpp" line="5996"/> <location filename="../../CommandConstraints.cpp" line="6288"/> <location filename="../../CommandConstraints.cpp" line="6978"/> <source>Select an edge that is not a B-spline weight</source> <translation>Selecione uma aresta que não seja uma peso de B-spline</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2696"/> <source>None of the selected points were constrained onto the respective curves, because they are parts of the same element, because they are both external geometry, or because the edge is not eligible.</source> <translation>Nenhum dos pontos selecionados foi restrito sobre as respectivas curvas, porque elas são partes do mesmo elemento, porque são ambos geometria externa, ou porque a aresta não é elegível.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2851"/> <location filename="../../CommandConstraints.cpp" line="2959"/> <location filename="../../CommandConstraints.cpp" line="3103"/> <location filename="../../CommandConstraints.cpp" line="3208"/> <source>Select exactly one line or up to two points from the sketch.</source> <translation>Selecione exatamente uma linha ou até dois pontos no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2880"/> <source>Cannot add a horizontal length constraint on an axis!</source> <translation>Não é possível adicionar uma restrição de comprimento horizontal em um eixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2930"/> <source>Cannot add a fixed x-coordinate constraint on the origin point!</source> <translation>Não é possível adicionar uma restrição de coordenada-x fixa no ponto de origem!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="2988"/> <location filename="../../CommandConstraints.cpp" line="3237"/> <source>This constraint only makes sense on a line segment or a pair of points</source> <translation>Esta restrição só faz sentido num segmento reto ou num par de pontos</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3128"/> <source>Cannot add a vertical length constraint on an axis!</source> <translation>Não é possível adicionar uma restrição de comprimento vertical em um eixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3178"/> <source>Cannot add a fixed y-coordinate constraint on the origin point!</source> <translation>Não é possível adicionar uma restrição de coordenada-y fixa no ponto de origem!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3338"/> <source>Select two or more lines from the sketch.</source> <translation>Selecione duas ou mais linhas no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3351"/> <location filename="../../CommandConstraints.cpp" line="6418"/> <source>Select at least two lines from the sketch.</source> <translation>Selecione pelo menos duas linhas no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3365"/> <source>Select a valid line</source> <translation>Selecione uma linha válida</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3381"/> <location filename="../../CommandConstraints.cpp" line="3419"/> <source>The selected edge is not a valid line</source> <translation>A aresta selecionada não é uma linha válida</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3483"/> <source>There is a number of ways this constraint can be applied. Accepted combinations: two curves; an endpoint and a curve; two endpoints; two curves and a point.</source> <comment>perpendicular constraint</comment> <translation>Há um número de maneiras em que essa restrição pode ser aplicada. Combinações possíveis: duas curvas; um ponto de extremidade e uma curva; dois pontos de extremidade; duas curvas e um ponto.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3503"/> <source>Select some geometry from the sketch.</source> <comment>perpendicular constraint</comment> <translation>Selecione alguma geometria do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3516"/> <source>Wrong number of selected objects!</source> <comment>perpendicular constraint</comment> <translation>Número errado de objetos selecionados!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3593"/> <location filename="../../CommandConstraints.cpp" line="4226"/> <source>With 3 objects, there must be 2 curves and 1 point.</source> <comment>tangent constraint</comment> <translation>Com 3 objetos, deve haver 2 curvas e 1 ponto.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3602"/> <location filename="../../CommandConstraints.cpp" line="3639"/> <source>Cannot add a perpendicularity constraint at an unconnected point!</source> <translation>Não é possível adicionar uma restrição de perpendicularidade em um ponto não conectado!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3648"/> <location filename="../../CommandConstraints.cpp" line="3687"/> <location filename="../../CommandConstraints.cpp" line="3868"/> <source>Perpendicular to B-spline edge currently unsupported.</source> <translation>Perpendicular à aresta de Bspline ainda não está suportado.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="3678"/> <location filename="../../CommandConstraints.cpp" line="3859"/> <source>One of the selected edges should be a line.</source> <translation>Uma das arestas selecionadas deve ser uma linha.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4118"/> <source>There are a number of ways this constraint can be applied. Accepted combinations: two curves; an endpoint and a curve; two endpoints; two curves and a point.</source> <comment>tangent constraint</comment> <translation>Há uma quantidade de maneiras de aplicar esta restrição. Combinações possíveis: duas curvas; um ponto de extremidade e uma curva; dois pontos de extremidade; duas curvas e um ponto.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4137"/> <source>Select some geometry from the sketch.</source> <comment>tangent constraint</comment> <translation>Selecione alguma geometria do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4150"/> <source>Wrong number of selected objects!</source> <comment>tangent constraint</comment> <translation>Número errado de objetos selecionados!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4235"/> <location filename="../../CommandConstraints.cpp" line="4256"/> <location filename="../../CommandConstraints.cpp" line="4664"/> <source>Cannot add a tangency constraint at an unconnected point!</source> <translation>Não é possível adicionar uma restrição de tangência em um ponto não conectado!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4265"/> <location filename="../../CommandConstraints.cpp" line="4295"/> <location filename="../../CommandConstraints.cpp" line="4519"/> <source>Tangency to B-spline edge currently unsupported.</source> <translation>Tangência à aresta de Bspline ainda não está suportado.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4331"/> <source>Endpoint to endpoint tangency was applied. The coincident constraint was deleted.</source> <translation>Uma tangência de ponto a ponto foi aplicada. A restrição de coincidência foi excluída.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4805"/> <location filename="../../CommandConstraints.cpp" line="4866"/> <location filename="../../CommandConstraints.cpp" line="5316"/> <location filename="../../CommandConstraints.cpp" line="5373"/> <source>Select one or more arcs or circles from the sketch.</source> <translation>Selecione um ou mais arcos ou círculos no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4871"/> <source>Select either only one or more B-Spline poles or only one or more arcs or circles from the sketch, but not mixed.</source> <translation>Selecione somente um ou mais polos B-Spline ou apenas um ou mais arcos ou círculos do esboço, mas não misturados.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4927"/> <location filename="../../CommandConstraints.cpp" line="5422"/> <source>Constrain equal</source> <translation>Restrição igual</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="4928"/> <source>Do you want to share the same radius for all selected elements?</source> <translation>Deseja compartilhar o mesmo raio para todos os elementos selecionados?</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5118"/> <location filename="../../CommandConstraints.cpp" line="5597"/> <source>Constraint only applies to arcs or circles.</source> <translation>Restrição aplicável somente em arcos ou círculos.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5423"/> <source>Do you want to share the same diameter for all selected elements?</source> <translation>Deseja compartilhar o mesmo diâmetro para todos os elementos selecionados?</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5903"/> <location filename="../../CommandConstraints.cpp" line="6148"/> <source>Select one or two lines from the sketch. Or select two edges and a point.</source> <translation>Selecione uma ou duas linhas no esboço. Ou selecione um ponto e duas arestas.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6059"/> <location filename="../../CommandConstraints.cpp" line="6226"/> <source>Parallel lines</source> <translation>Linhas paralelas</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6060"/> <location filename="../../CommandConstraints.cpp" line="6227"/> <source>An angle constraint cannot be set for two parallel lines.</source> <translation>Uma restrição de ângulo não pode ser aplicada em duas linhas paralelas.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6092"/> <source>Cannot add an angle constraint on an axis!</source> <translation>Não é possível adicionar uma restrição de ângulo em um eixo!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6405"/> <source>Select two edges from the sketch.</source> <translation>Selecione duas arestas no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6434"/> <location filename="../../CommandConstraints.cpp" line="7134"/> <source>Select two or more compatible edges</source> <translation>Selecione duas ou mais arestas compatíveis</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6439"/> <source>Sketch axes cannot be used in equality constraints</source> <translation>Os eixos do esboço não podem ser usados em restrições de igualdade</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6458"/> <source>Equality for B-spline edge currently unsupported.</source> <translation>Igualdade para aresta de Bspline ainda não está suportada.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6488"/> <location filename="../../CommandConstraints.cpp" line="6503"/> <location filename="../../CommandConstraints.cpp" line="6555"/> <source>Select two or more edges of similar type</source> <translation>Selecione duas ou mais arestas do mesmo tipo</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6637"/> <location filename="../../CommandConstraints.cpp" line="6650"/> <location filename="../../CommandConstraints.cpp" line="6697"/> <location filename="../../CommandConstraints.cpp" line="6764"/> <location filename="../../CommandConstraints.cpp" line="6845"/> <source>Select two points and a symmetry line, two points and a symmetry point or a line and a symmetry point from the sketch.</source> <translation>Selecione dois pontos e uma linha de simetria, dois pontos e um ponto de simetria ou uma linha e um ponto de simetria no esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6675"/> <location filename="../../CommandConstraints.cpp" line="6829"/> <source>Cannot add a symmetry constraint between a line and its end points.</source> <translation>Não é possível adicionar uma restrição de simetria entre uma linha e seus pontos finais.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6727"/> <location filename="../../CommandConstraints.cpp" line="6787"/> <source>Cannot add a symmetry constraint between a line and its end points!</source> <translation>Não é possível adicionar uma restrição de simetria entre uma linha e seus pontos finais!</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6907"/> <source>Select two endpoints of lines to act as rays, and an edge representing a boundary. The first selected point corresponds to index n1, second to n2, and datum value sets the ratio n2/n1.</source> <comment>Constraint_SnellsLaw</comment> <translation>Selecione dois pontos finais de linhas para agir como raios e uma aresta que representa um limite. O primeiro ponto selecionado corresponde ao índice n1, o segundo ao n2, e o valor de datum define a proporção n2/n1.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6955"/> <source>Cannot create constraint with external geometry only.</source> <translation>Não é possível criar restrições somente com geometria externa.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6962"/> <source>Incompatible geometry is selected.</source> <translation>Geometria incompatível selecionada.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6972"/> <source>SnellsLaw on B-spline edge is currently unsupported.</source> <translation>Restrições SnellsLaw em arestas de Bspline ainda não são suportadas.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7156"/> <source>You cannot internally constrain an ellipse on another ellipse. Select only one ellipse.</source> <translation>Não é possível restringir internamente uma elipse sobre outra elipse. Selecione apenas uma elipse.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7209"/> <location filename="../../CommandConstraints.cpp" line="7387"/> <source>Currently all internal geometrical elements of the ellipse are already exposed.</source> <translation>Atualmente todos os elementos geométricos internos da elipse já estão expostos.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7557"/> <location filename="../../CommandConstraints.cpp" line="7565"/> <location filename="../../CommandConstraints.cpp" line="7597"/> <location filename="../../CommandConstraints.cpp" line="7670"/> <location filename="../../CommandConstraints.cpp" line="7681"/> <source>Select constraints from the sketch.</source> <translation>Selecione restrições do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6923"/> <source>Selected objects are not just geometry from one sketch.</source> <translation>Objetos selecionados não são apenas geometria de um esboço só.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6933"/> <source>Number of selected objects is not 3 (is %1).</source> <translation>Número de objetos selecionados não é 3 (é %1).</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7077"/> <location filename="../../CommandConstraints.cpp" line="7090"/> <source>Select at least one ellipse and one edge from the sketch.</source> <translation>Selecione pelo menos uma elipse e uma aresta do esboço.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7111"/> <source>Sketch axes cannot be used in internal alignment constraint</source> <translation>Eixos do esboço não podem ser usados para uma restrição de alinhamento interno</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7164"/> <location filename="../../CommandConstraints.cpp" line="7342"/> <source>Maximum 2 points are supported.</source> <translation>Máximo 2 pontos são suportados.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7170"/> <location filename="../../CommandConstraints.cpp" line="7348"/> <source>Maximum 2 lines are supported.</source> <translation>Máximo 2 linhas são suportadas.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7208"/> <location filename="../../CommandConstraints.cpp" line="7386"/> <source>Nothing to constrain</source> <translation>Nada para restringir</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7299"/> <location filename="../../CommandConstraints.cpp" line="7310"/> <location filename="../../CommandConstraints.cpp" line="7477"/> <location filename="../../CommandConstraints.cpp" line="7488"/> <source>Extra elements</source> <translation>Elementos extra</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7300"/> <location filename="../../CommandConstraints.cpp" line="7311"/> <location filename="../../CommandConstraints.cpp" line="7478"/> <source>More elements than possible for the given ellipse were provided. These were ignored.</source> <translation>Foram fornecidos mais elementos do que o possível para a elipse dada. Estes foram ignorados.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7326"/> <source>You cannot internally constrain an arc of ellipse on another arc of ellipse. Select only one arc of ellipse.</source> <translation>Você não pode restringir internamente um arco de elipse em outro arco de elipse. Selecione apenas um arco de elipse.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7334"/> <source>You cannot internally constrain an ellipse on an arc of ellipse. Select only one ellipse or arc of ellipse.</source> <translation>Não é possível restringir internamente uma elipse sobre um arco de elipse. Selecione apenas uma elipse ou um arco de elipse.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7489"/> <source>More elements than possible for the given arc of ellipse were provided. These were ignored.</source> <translation>Foram fornecidos mais elementos do que o possível para o arco de elipse dado. Estes foram ignorados.</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="7497"/> <source>Currently internal geometry is only supported for ellipse or arc of ellipse. The last selected element must be an ellipse or an arc of ellipse.</source> <translation>Atualmente a geometria interna só é suportada para elipses ou arcos de elipse. O último elemento selecionado deve ser uma elipse ou um arco de elipse.</translation> </message> <message> <location filename="../../CommandSketcherVirtualSpace.cpp" line="116"/> <location filename="../../CommandSketcherVirtualSpace.cpp" line="124"/> <location filename="../../CommandSketcherVirtualSpace.cpp" line="147"/> <source>Select constraint(s) from the sketch.</source> <translation>Selecione restrições do desenho.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5233"/> <location filename="../../CommandSketcherBSpline.cpp" line="682"/> <source>CAD Kernel Error</source> <translation>Erro de Kernel CAD</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="432"/> <source>None of the selected elements is an edge.</source> <translation>Nenhum dos elementos selecionados é uma aresta.</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="503"/> <location filename="../../CommandSketcherBSpline.cpp" line="581"/> <source>At least one of the selected objects was not a B-Spline and was ignored.</source> <translation>Pelo menos um dos objetos selecionados não era um B-Spline e foi ignorado.</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="618"/> <location filename="../../CommandSketcherBSpline.cpp" line="772"/> <source>Wrong OCE/OCC version</source> <translation>Versão errada do OCE/OCC</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="619"/> <location filename="../../CommandSketcherBSpline.cpp" line="773"/> <source>This version of OCE/OCC does not support knot operation. You need 6.9.0 or higher</source> <translation>Esta versão do OCE/OCC não suporta operações com nós. Você precisa da versão 6.9.0 ou superior</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="641"/> <location filename="../../CommandSketcherBSpline.cpp" line="795"/> <source>The selection comprises more than one item. Please select just one knot.</source> <translation>A seleção engloba mais de um item. Por favor, selecione apenas um nó.</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="691"/> <source>Input Error</source> <translation>Erro de entrada</translation> </message> <message> <location filename="../../CommandSketcherBSpline.cpp" line="704"/> <location filename="../../CommandSketcherBSpline.cpp" line="844"/> <source>None of the selected elements is a knot of a B-spline</source> <translation>Nenhum dos elementos selecionados é um nó de uma B-spline</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="126"/> <location filename="../../CommandSketcherTools.cpp" line="134"/> <location filename="../../CommandSketcherTools.cpp" line="236"/> <location filename="../../CommandSketcherTools.cpp" line="244"/> <source>Select at least two edges from the sketch.</source> <translation>Selecione pelo menos duas arestas do esboço.</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="166"/> <location filename="../../CommandSketcherTools.cpp" line="268"/> <source>One selected edge is not connectable</source> <translation>Uma aresta selecionada não é conectável</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="176"/> <source>Closing a shape formed by exactly two lines makes no sense.</source> <translation>Fechar uma forma formada por exatamente duas linhas não faz sentido.</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="321"/> <location filename="../../CommandSketcherTools.cpp" line="932"/> <location filename="../../CommandSketcherTools.cpp" line="1025"/> <location filename="../../CommandSketcherTools.cpp" line="1033"/> <location filename="../../CommandSketcherTools.cpp" line="1385"/> <location filename="../../CommandSketcherTools.cpp" line="1394"/> <location filename="../../CommandSketcherTools.cpp" line="1916"/> <location filename="../../CommandSketcherTools.cpp" line="1925"/> <source>Select elements from a single sketch.</source> <translation>Selecione elementos de um esboço único.</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="807"/> <source>No constraint selected</source> <translation>Nenhuma restrição selecionada</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="808"/> <source>At least one constraint must be selected</source> <translation>Pelo menos uma restrição deve ser selecionada</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1138"/> <source>A symmetric construction requires at least two geometric elements, the last geometric element being the reference for the symmetry construction.</source> <translation>Uma construção simétrica requer pelo menos dois elementos geométricos, sendo o último elemento geométrico a referência para a construção da simetria.</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1147"/> <source>The last element must be a point or a line serving as reference for the symmetry construction.</source> <translation>O último elemento deve ser um ponto ou uma linha, servindo como referência para a construção da simetria.</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1453"/> <location filename="../../CommandSketcherTools.cpp" line="1987"/> <source>A copy requires at least one selected non-external geometric element</source> <translation>Uma cópia requer pelo menos um elemento geométrico não-externo selecionado</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2048"/> <source>Delete All Geometry</source> <translation>Excluir toda a geometria</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2049"/> <source>Are you really sure you want to delete all geometry and constraints?</source> <translation>Tem certeza que deseja excluir todas as geometria e restrições?</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2108"/> <source>Delete All Constraints</source> <translation>Excluir todas as restrições</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="2109"/> <source>Are you really sure you want to delete all the constraints?</source> <translation>Tem certeza de que deseja excluir todas as restrições?</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="80"/> <source>Distance constraint</source> <translation>Restrição de distância</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="81"/> <source>Not allowed to edit the datum because the sketch contains conflicting constraints</source> <translation>Não é possível editar o dado porque o esboço contém restrições conflitantes</translation> </message> </context> <context> <name>SketcherGui::CarbonCopySelection</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6075"/> <source>Carbon copy would cause a circular dependency.</source> <translation>Cópia de carbono poderia causar uma dependência circular.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6078"/> <source>This object is in another document.</source> <translation>Este objeto está em um outro documento.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6081"/> <source>This object belongs to another body. Hold Ctrl to allow cross-references.</source> <translation>Este objeto pertence a outro corpo. Pressione a tecla Ctrl para permitir referências cruzadas.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6084"/> <source>This object belongs to another body and it contains external geometry. Cross-reference not allowed.</source> <translation>Este objeto pertence a outro corpo, e contém geometria externa. Referências cruzadas não são permitidas.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6087"/> <source>This object belongs to another part.</source> <translation>Este objeto pertence a outra peça.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6090"/> <source>The selected sketch is not parallel to this sketch. Hold Ctrl+Alt to allow non-parallel sketches.</source> <translation>O esboço selecionado não é paralelo a este esboço. Pressione Ctrl+Alt para permitir esboços não paralelos.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6093"/> <source>The XY axes of the selected sketch do not have the same direction as this sketch. Hold Ctrl+Alt to disregard it.</source> <translation>Os eixos XY do esboço selecionado não tem a mesma direção que este esboço. Pressione Ctrl + Alt para ignorar isto.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6096"/> <source>The origin of the selected sketch is not aligned with the origin of this sketch. Hold Ctrl+Alt to disregard it.</source> <translation>A origem do esboço selecionado não está alinhada com a origem deste esboço. Pressione Ctrl + Alt para ignorar isto.</translation> </message> </context> <context> <name>SketcherGui::ConstraintView</name> <message> <location filename="../../TaskSketcherConstrains.cpp" line="485"/> <source>Change value</source> <translation>Mudar o valor</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="489"/> <source>Toggle to/from reference</source> <translation>Alternar para/de referência</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="492"/> <source>Deactivate</source> <translation>Desativar</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="492"/> <source>Activate</source> <translation>Ativar</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="496"/> <source>Show constraints</source> <translation>Mostrar as restrições</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="498"/> <source>Hide constraints</source> <translation>Ocultar as restrições</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="504"/> <source>Rename</source> <translation>Renomear</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="511"/> <source>Center sketch</source> <translation>Croqui do centro</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="514"/> <source>Delete</source> <translation>Excluir</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="518"/> <source>Swap constraint names</source> <translation>Trocar nomes de restrição</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="616"/> <source>Unnamed constraint</source> <translation>Restrição sem nome</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="617"/> <source>Only the names of named constraints can be swapped.</source> <translation>Apenas os nomes das restrições nomeadas podem ser trocados.</translation> </message> </context> <context> <name>SketcherGui::EditDatumDialog</name> <message> <location filename="../../EditDatumDialog.cpp" line="96"/> <source>Insert angle</source> <translation>Insira o ângulo</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="98"/> <source>Angle:</source> <translation>Ângulo:</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="102"/> <source>Insert radius</source> <translation>Insira o raio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5015"/> <location filename="../../CommandConstraints.cpp" line="5173"/> <location filename="../../EditDatumDialog.cpp" line="104"/> <source>Radius:</source> <translation>Raio:</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="108"/> <source>Insert diameter</source> <translation>Inserir diâmetro</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5494"/> <location filename="../../CommandConstraints.cpp" line="5641"/> <location filename="../../EditDatumDialog.cpp" line="110"/> <source>Diameter:</source> <translation>Diâmetro:</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="114"/> <source>Insert weight</source> <translation>Inserir peso</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="119"/> <source>Refractive index ratio</source> <comment>Constraint_SnellsLaw</comment> <translation>Relação de índice de refração</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="120"/> <source>Ratio n2/n1:</source> <comment>Constraint_SnellsLaw</comment> <translation>Relação n2/n1:</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="125"/> <source>Insert length</source> <translation>Insira o comprimento</translation> </message> <message> <location filename="../../EditDatumDialog.cpp" line="127"/> <source>Length:</source> <translation>Comprimento:</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5009"/> <location filename="../../CommandConstraints.cpp" line="5167"/> <source>Change weight</source> <translation>Alterar peso</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5010"/> <location filename="../../CommandConstraints.cpp" line="5168"/> <location filename="../../EditDatumDialog.cpp" line="115"/> <source>Weight:</source> <translation>Peso:</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5014"/> <location filename="../../CommandConstraints.cpp" line="5172"/> <source>Change radius</source> <translation>Mudar raio</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="5493"/> <location filename="../../CommandConstraints.cpp" line="5640"/> <source>Change diameter</source> <translation>Alterar o diâmetro</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6989"/> <source>Refractive index ratio</source> <translation>Relação de índice de refração</translation> </message> <message> <location filename="../../CommandConstraints.cpp" line="6990"/> <source>Ratio n2/n1:</source> <translation>Relação n2/n1:</translation> </message> </context> <context> <name>SketcherGui::ElementView</name> <message> <location filename="../../TaskSketcherElements.cpp" line="184"/> <source>Delete</source> <translation>Excluir</translation> </message> </context> <context> <name>SketcherGui::ExternalSelection</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5884"/> <source>Linking this will cause circular dependency.</source> <translation>Esta ligação irá causar dependência circular.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5887"/> <source>This object is in another document.</source> <translation>Este objeto está em um outro documento.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5890"/> <source>This object belongs to another body, can't link.</source> <translation>Este objeto pertence a outro corpo, não é possível vincular.</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="5893"/> <source>This object belongs to another part, can't link.</source> <translation>Este objeto pertence a outra parte, não é possível vincular.</translation> </message> </context> <context> <name>SketcherGui::InsertDatum</name> <message> <location filename="../../InsertDatum.ui" line="23"/> <source>Insert datum</source> <translation>Inserir datum</translation> </message> <message> <location filename="../../InsertDatum.ui" line="31"/> <source>datum:</source> <translation>datum:</translation> </message> <message> <location filename="../../InsertDatum.ui" line="48"/> <source>Name (optional)</source> <translation>Nome (opcional)</translation> </message> <message> <location filename="../../InsertDatum.ui" line="61"/> <source>Constraint name (available for expressions)</source> <translation>Nome da restrição (disponível para expressões)</translation> </message> <message> <location filename="../../InsertDatum.ui" line="76"/> <source>Reference (or constraint) dimension</source> <translation>Dimensão de referência (ou restrição)</translation> </message> <message> <location filename="../../InsertDatum.ui" line="79"/> <source>Reference</source> <translation>Referência</translation> </message> </context> <context> <name>SketcherGui::PropertyConstraintListItem</name> <message> <location filename="../../PropertyConstraintListItem.cpp" line="131"/> <location filename="../../PropertyConstraintListItem.cpp" line="184"/> <source>Unnamed</source> <translation>Sem nome</translation> </message> </context> <context> <name>SketcherGui::SketchMirrorDialog</name> <message> <location filename="../../SketchMirrorDialog.ui" line="14"/> <location filename="../../SketchMirrorDialog.ui" line="20"/> <source>Select Mirror Axis/Point</source> <translation>Selecione o eixo/ponto de simetria</translation> </message> <message> <location filename="../../SketchMirrorDialog.ui" line="26"/> <source>X-Axis</source> <translation>Eixo-X</translation> </message> <message> <location filename="../../SketchMirrorDialog.ui" line="36"/> <source>Y-Axis</source> <translation>Eixo-Y</translation> </message> <message> <location filename="../../SketchMirrorDialog.ui" line="43"/> <source>Origin</source> <translation>Origem</translation> </message> </context> <context> <name>SketcherGui::SketchOrientationDialog</name> <message> <location filename="../../SketchOrientationDialog.ui" line="14"/> <source>Choose orientation</source> <translation>Escolher a orientação</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="20"/> <source>Sketch orientation</source> <translation>Orientação do esboço</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="26"/> <source>XY-Plane</source> <translation>Plano XY</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="36"/> <source>XZ-Plane</source> <translation>Plano XZ</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="43"/> <source>YZ-Plane</source> <translation>Plano YZ</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="72"/> <source>Reverse direction</source> <translation>Inverter direção</translation> </message> <message> <location filename="../../SketchOrientationDialog.ui" line="81"/> <source>Offset:</source> <translation>Offset:</translation> </message> </context> <context> <name>SketcherGui::SketchRectangularArrayDialog</name> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="17"/> <source>Create array</source> <translation>Criar matriz</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="25"/> <source>Columns:</source> <translation>Colunas:</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="32"/> <source>Number of columns of the linear array</source> <translation>Número de colunas da matriz linear</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="52"/> <source>Rows:</source> <translation>Linhas:</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="59"/> <source>Number of rows of the linear array</source> <translation>Número de linhas da matriz linear</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="77"/> <source>Makes the inter-row and inter-col spacing the same if clicked</source> <translation>Faz o espaço entre linhas e entre colunas iguais se ativado</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="80"/> <source>Equal vertical/horizontal spacing</source> <translation>Igualar espaçamento vertical/horizontal</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="93"/> <source>If selected, each element in the array is constrained with respect to the others using construction lines</source> <translation>Se selecionado, cada elemento na rede é restrito em relação aos outros usando linhas de construção</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="116"/> <source>If selected, it substitutes dimensional constraints by geometric constraints in the copies, so that a change in the original element is directly reflected on copies</source> <translation>Se selecionado, substitui restrições de dimensão por restrições geométricas nas cópias, para que uma alteração no elemento original seja refletida diretamente nas cópias</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="100"/> <source>Constrain inter-element separation</source> <translation>Restringir a separação entre elementos</translation> </message> <message> <location filename="../../SketchRectangularArrayDialog.ui" line="121"/> <source>Clone</source> <translation>Clonar</translation> </message> </context> <context> <name>SketcherGui::SketcherGeneralWidget</name> <message> <location filename="../../TaskSketcherGeneral.cpp" line="132"/> <location filename="../../TaskSketcherGeneral.cpp" line="137"/> <location filename="../../TaskSketcherGeneral.cpp" line="142"/> <source>Normal Geometry</source> <translation>Geometria normal</translation> </message> <message> <location filename="../../TaskSketcherGeneral.cpp" line="132"/> <location filename="../../TaskSketcherGeneral.cpp" line="137"/> <location filename="../../TaskSketcherGeneral.cpp" line="142"/> <source>Construction Geometry</source> <translation>Geometria de construção</translation> </message> <message> <location filename="../../TaskSketcherGeneral.cpp" line="132"/> <location filename="../../TaskSketcherGeneral.cpp" line="137"/> <location filename="../../TaskSketcherGeneral.cpp" line="142"/> <source>External Geometry</source> <translation>Geometria externa</translation> </message> </context> <context> <name>SketcherGui::SketcherRegularPolygonDialog</name> <message> <location filename="../../SketcherRegularPolygonDialog.ui" line="17"/> <source>Create array</source> <translation>Criar matriz</translation> </message> <message> <location filename="../../SketcherRegularPolygonDialog.ui" line="25"/> <source>Number of Sides:</source> <translation>Número de lados:</translation> </message> <message> <location filename="../../SketcherRegularPolygonDialog.ui" line="32"/> <source>Number of columns of the linear array</source> <translation>Número de colunas da matriz linear</translation> </message> </context> <context> <name>SketcherGui::SketcherSettings</name> <message> <location filename="../../SketcherSettings.ui" line="14"/> <location filename="../../SketcherSettings.ui" line="109"/> <source>General</source> <translation>Geral</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="27"/> <source>Sketcher solver</source> <translation>Calculador do esboço</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="33"/> <source>Sketcher dialog will have additional section 'Advanced solver control' to adjust solver settings</source> <translation>A caixa de diálogo do esboço terá uma seção adicional 'Controle avançado do calculador' para ajustar as configurações de resolução</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="37"/> <source>Show section 'Advanced solver control' in task dialog</source> <translation>Mostrar seção 'Controle avançado do calculador' no painel de tarefas</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="53"/> <source>Dragging performance</source> <translation>Performance durante a manipulação</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="59"/> <source>Special solver algorithm will be used while dragging sketch elements. Requires to re-enter edit mode to take effect.</source> <translation>Um algoritmo especial do calculador será usado quando arrastar elementos de esboço. Necessita sair e reentrar no modo de edição para ter efeito.</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="63"/> <source>Improve solving while dragging</source> <translation>Melhorar resolução ao arrastar</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="115"/> <source>New constraints that would be redundant will automatically be removed</source> <translation>Novas restrições que seriam redundantes serão automaticamente removidas</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="118"/> <source>Auto remove redundants</source> <translation>Remover redundâncias automaticamente</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="134"/> <source>Allow to leave sketch edit mode when pressing Esc button</source> <translation>Permitir a saída do modo de edição do esboço pressionando o botão Esc</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="137"/> <source>Esc can leave sketch edit mode</source> <translation>Esc para sair do modo de edição</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="153"/> <source>Notifies about automatic constraint substitutions</source> <translation>Notificar substituições automáticas de restrições</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="156"/> <source>Notify automatic constraint substitutions</source> <translation>Notificar substituições automáticas de restrições</translation> </message> <message> <location filename="../../SketcherSettings.ui" line="20"/> <source>Sketcher</source> <translation>Esboço</translation> </message> </context> <context> <name>SketcherGui::SketcherSettingsColors</name> <message> <location filename="../../SketcherSettingsColors.ui" line="14"/> <source>Colors</source> <translation>Cores</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="20"/> <source>Sketcher colors</source> <translation>Cores de esboço</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="28"/> <source>Default edge color</source> <translation>Cor padrão da aresta</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="55"/> <source>Default vertex color</source> <translation>Cor padrão dos vértices</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="82"/> <source>Making line color</source> <translation>Cor de linha sendo desenhada</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="109"/> <source>Edit edge color</source> <translation>Editar cor da aresta</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="136"/> <source>Edit vertex color</source> <translation>Editar a cor do vértice</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="163"/> <source>Construction geometry</source> <translation>Geometria de construção</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="217"/> <source>External geometry</source> <translation>Geometria externa</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="271"/> <source>Fully constrained geometry</source> <translation>Geometria totalmente restrita</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="406"/> <source>Constraint color</source> <translation>Cor das restrições</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="460"/> <source>Expression dependent constraint color</source> <translation>Cor das restrições que dependem de expressões</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="35"/> <source>Color of edges</source> <translation>Cor das bordas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="62"/> <source>Color of vertices</source> <translation>Cor dos vértices</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="89"/> <source>Color used while new sketch elements are created</source> <translation>Cor usada enquanto novos elementos de esboço são criados</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="116"/> <source>Color of edges being edited</source> <translation>Cor das arestas sendo editadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="143"/> <source>Color of vertices being edited</source> <translation>Cor dos vértices sendo editados</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="170"/> <source>Color of construction geometry in edit mode</source> <translation>Cor da geometria de construção no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="190"/> <source>Internal alignment edge color</source> <translation>Cor de alinhamento interno de arestas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="197"/> <source>Color of edges of internal alignment geometry</source> <translation>Cor das arestas da geometria de alinhamento interno</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="224"/> <source>Color of external geometry in edit mode</source> <translation>Cor da geometria externa no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="244"/> <source>Invalid Sketch</source> <translation>Esboço inválido</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="251"/> <source>Color of geometry indicating an invalid sketch</source> <translation>Cor da geometria indicando um esboço inválido</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="278"/> <source>Color of fully constrained geometry in edit mode</source> <translation>Cor de geometria totalmente restrita no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="298"/> <source>Fully constrained edit edge color</source> <translation>Cor das arestas totalmente restritas sendo editadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="305"/> <source>Color of fully constrained edge color in edit mode</source> <translation>Cor das arestas totalmente restritas no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="325"/> <source>Fully constrained edit construction edge color</source> <translation>Cor das arestas de construção totalmente restritas sendo editadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="332"/> <source>Color of fully constrained construction edge color in edit mode</source> <translation>Cor das arestas de construção completamente restritas no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="352"/> <source>Fully constrained edit internal alignment edge color</source> <translation>Cor das arestas de alinhamento interno totalmente restritas sendo editadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="359"/> <source>Color of fully constrained internal alignment edge color in edit mode</source> <translation>Cor das arestas de alinhamento interno completamente restritas no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="379"/> <source>Fully constrained edit vertex color</source> <translation>Cor dos vértices totalmente restritos sendo editados</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="386"/> <source>Color of fully constrained vertex color in edit mode</source> <translation>Cor dos vértices totalmente restritos no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="413"/> <source>Color of driving constraints in edit mode</source> <translation>Cor das restrições ativas no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="433"/> <source>Reference constraint color</source> <translation>Cor das restrições de referência</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="440"/> <source>Color of reference constraints in edit mode</source> <translation>Cor das restrições de referência no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="467"/> <source>Color of expression dependent constraints in edit mode</source> <translation>Cor das restrições dependentes da expressão no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="487"/> <source>Deactivated constraint color</source> <translation>Cor das restrições desativadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="494"/> <source>Color of deactivated constraints in edit mode</source> <translation>Cor das restrições desativadas no modo de edição</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="514"/> <source>Dimensional constraint color</source> <translation>Cor das restrições dimensionais</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="521"/> <source>Color of dimensional driving constraints</source> <translation>Cor das restrições dimensional atuantes</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="541"/> <source>Coordinate text color</source> <translation>Cor do texto das coordenadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="548"/> <source>Text color of the coordinates</source> <translation>Cor do texto das coordenadas</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="575"/> <source>Color of crosshair cursor. (The one you get when creating a new sketch element.)</source> <translation>Cor do cursor cruzado do mouse. (Que é usado ao criar um novo elemento de esboço.)</translation> </message> <message> <location filename="../../SketcherSettingsColors.ui" line="568"/> <source>Cursor crosshair color</source> <translation>Cor do ponteiro do mouse</translation> </message> </context> <context> <name>SketcherGui::SketcherSettingsDisplay</name> <message> <location filename="../../SketcherSettingsDisplay.ui" line="14"/> <source>Display</source> <translation>Tela</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="33"/> <source>Sketch editing</source> <translation>Edição de esboço</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="39"/> <source>A dialog will pop up to input a value for new dimensional constraints</source> <translation>Um diálogo irá aparecer para inserir um valor para novas restrições de dimensão</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="42"/> <source>Ask for value after creating a dimensional constraint</source> <translation>Pedir o valor depois de criar uma restrição de dimensão</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="58"/> <source>Segments per geometry</source> <translation>Segmentos por geometria</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="65"/> <source>Current constraint creation tool will remain active after creation</source> <translation>A ferramenta de criação de restrições atual permanecerá ativa após a criação</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="68"/> <source>Constraint creation "Continue Mode"</source> <translation>Modo continuo de criação de restrições</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="84"/> <source>Line pattern used for grid lines</source> <translation>Padrão de linha usado para linhas de grade</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="94"/> <source>Base length units will not be displayed in constraints. Supports all unit systems except 'US customary' and 'Building US/Euro'.</source> <translation>Unidades de comprimento não serão exibidas em restrições. Todos os sistemas de unidades são suportados, exceto 'US customy' e 'Building US/Euro'.</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="98"/> <source>Hide base length units for supported unit systems</source> <translation>Ocultar unidades de comprimento base para sistemas de unidades suportados</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="117"/> <source>Font size</source> <translation>Tamanho da fonte</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="151"/> <source>Visibility automation</source> <translation>Automação de visibilidade</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="157"/> <source>When opening sketch, hide all features that depend on it</source> <translation>Ao abrir um esboço, ocultar todos os objetos que dependem dele</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="160"/> <source>Hide all objects that depend on the sketch</source> <translation>Esconder todos os objetos que dependem o esboço</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="176"/> <source>When opening sketch, show sources for external geometry links</source> <translation>Ao abrir um esboço, mostrar fontes de vínculos de geometria externa</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="179"/> <source>Show objects used for external geometry</source> <translation>Mostrar objetos usados para geometria externa</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="195"/> <source>When opening sketch, show objects the sketch is attached to</source> <translation>Ao abrir um esboço, mostrar os objetos aos quais o esboço está anexado</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="198"/> <source>Show objects that the sketch is attached to</source> <translation>Mostrar objetos aos quais o esboço está anexado</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="239"/> <source>Note: these settings are defaults applied to new sketches. The behavior is remembered for each sketch individually as properties on the View tab.</source> <translation>Nota: estas configurações são padrões aplicados aos novos esboços. Estas configurações são lembradas para cada esboço individualmente, e guardadas como propriedades de vista.</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="347"/> <source>View scale ratio</source> <translation>Proporção de escala de vista</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="354"/> <source>The 3D view is scaled based on this factor</source> <translation>A vista 3D é dimensionada com base neste fator</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="214"/> <source>When closing sketch, move camera back to where it was before sketch was opened</source> <translation>Ao fechar o esboço, a câmera será colocada de volta onde estava antes do esboço ser aberto</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="217"/> <source>Restore camera position after editing</source> <translation>Restaurar a posição da câmara após a edição</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="258"/> <source>Applies current visibility automation settings to all sketches in open documents</source> <translation>Aplica as configurações atuais de automação de vista a todos os esboços em documentos abertos</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="261"/> <source>Apply to existing sketches</source> <translation>Aplicar aos esboços existentes</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="271"/> <source>Font size used for labels and constraints</source> <translation>Tamanho de texto usado para rótulos e restrições</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="274"/> <source>px</source> <translation>px</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="296"/> <source>Current sketcher creation tool will remain active after creation</source> <translation>A ferramenta atual de criação de esboço permanecerá ativa após a criação</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="299"/> <source>Geometry creation "Continue Mode"</source> <translation>Modo continuo de criação da geometria</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="315"/> <source>Grid line pattern</source> <translation>Padrão das linhas da grade</translation> </message> <message> <location filename="../../SketcherSettingsDisplay.ui" line="322"/> <source>Number of polygons for geometry approximation</source> <translation>Número de polígonos para aproximação da geometria</translation> </message> <message> <location filename="../../SketcherSettings.cpp" line="219"/> <source>Unexpected C++ exception</source> <translation>Exceção inesperada de C++</translation> </message> <message> <location filename="../../SketcherSettings.cpp" line="222"/> <source>Sketcher</source> <translation>Esboço</translation> </message> </context> <context> <name>SketcherGui::SketcherValidation</name> <message> <location filename="../../TaskSketcherValidation.cpp" line="139"/> <source>No missing coincidences</source> <translation>Nenhum coincidência faltante</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="140"/> <source>No missing coincidences found</source> <translation>Nenhuma coincidência faltante foi encontrada</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="145"/> <source>Missing coincidences</source> <translation>Coincidências faltantes</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="146"/> <source>%1 missing coincidences found</source> <translation>%1 coincidências faltantes encontradas</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="182"/> <source>No invalid constraints</source> <translation>Nenhuma restrição inválida</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="183"/> <source>No invalid constraints found</source> <translation>Nenhuma restrição inválida encontrada</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="187"/> <source>Invalid constraints</source> <translation>Restrições inválidas</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="188"/> <source>Invalid constraints found</source> <translation>Restrições inválidas encontradas</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="219"/> <location filename="../../TaskSketcherValidation.cpp" line="230"/> <location filename="../../TaskSketcherValidation.cpp" line="237"/> <location filename="../../TaskSketcherValidation.cpp" line="248"/> <source>Reversed external geometry</source> <translation>Geometria externa invertida</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="220"/> <source>%1 reversed external-geometry arcs were found. Their endpoints are encircled in 3d view. %2 constraints are linking to the endpoints. The constraints have been listed in Report view (menu View -&gt; Panels -&gt; Report view). Click "Swap endpoints in constraints" button to reassign endpoints. Do this only once to sketches created in FreeCAD older than v0.15</source> <translation>%1 arcos invertidos foram encontrados na geometria externa. Seus pontos de extremidade são destacados na vista 3d. %2 restrições estão ligadas aos pontos de extremidade. Essas restrições estão indicadas no relatório (menu Vista -&gt; Vistas -&gt; Relatório). Clique em "Trocar pontos de extremidade em restrições" para reatribuir os pontos de extremidade. Faça isto apenas uma vez em esboços criados com versões de FreeCAD anteriores à 0.15</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="231"/> <source>%1 reversed external-geometry arcs were found. Their endpoints are encircled in 3d view. However, no constraints linking to the endpoints were found.</source> <translation>%1 arcos invertidos foram encontrados na geometria externa. Seus pontos de extremidade são destacados na vista 3D. No entanto, nenhuma restrição foi encontrada nos pontos de extremidade.</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="238"/> <source>No reversed external-geometry arcs were found.</source> <translation>Nenhum arco invertido foi encontrado na geometria externa.</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="249"/> <source>%1 changes were made to constraints linking to endpoints of reversed arcs.</source> <translation>%1 alterações foram feitas nas restrições ligadas a pontos de extremidade de arcos invertidos.</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="262"/> <location filename="../../TaskSketcherValidation.cpp" line="276"/> <source>Constraint orientation locking</source> <translation>Restrição de bloqueio de orientação</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="263"/> <source>Orientation locking was enabled and recomputed for %1 constraints. The constraints have been listed in Report view (menu View -&gt; Panels -&gt; Report view).</source> <translation>O bloqueio de orientação foi habilitado e recalculado para %1 restrições. Essas restrições estão indicadas no relatório (menu Vista -&gt; Painéis -&gt; Relatório).</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="277"/> <source>Orientation locking was disabled for %1 constraints. The constraints have been listed in Report view (menu View -&gt; Panels -&gt; Report view). Note that for all future constraints, the locking still defaults to ON.</source> <translation>O bloqueio de orientação foi desativado para %1 restrições. Essas restrições estão indicadas no relatório (menu Vista -&gt; Painéis -&gt; Relatório). Note que para todas as futuras restrições, o bloqueio permanece ativado por padrão.</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="289"/> <location filename="../../TaskSketcherValidation.cpp" line="301"/> <source>Delete constraints to external geom.</source> <translation>Excluir restrições para geometria externa</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="290"/> <source>You are about to delete ALL constraints that deal with external geometry. This is useful to rescue a sketch with broken/changed links to external geometry. Are you sure you want to delete the constraints?</source> <translation>Você está prestes a excluir todas as restrições conectadas com geometria externa. Isso é útil para resgatar um esboço com links para geometria externa quebrados ou alterados. Tem certeza que deseja excluir essas restrições?</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="302"/> <source>All constraints that deal with external geometry were deleted.</source> <translation>Todas as restrições conectadas com geometria externa foram eliminadas.</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="359"/> <source>No degenerated geometry</source> <translation>Nenhuma geometria corrompida</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="360"/> <source>No degenerated geometry found</source> <translation>Nenhuma geometria corrompida encontrada</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="364"/> <source>Degenerated geometry</source> <translation>Geometria corrompida</translation> </message> <message> <location filename="../../TaskSketcherValidation.cpp" line="365"/> <source>%1 degenerated geometry found</source> <translation>%1 geometrias corrompidas encontradas</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherConstrains</name> <message> <location filename="../../TaskSketcherConstrains.ui" line="26"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="34"/> <source>Filter:</source> <translation>Filtro:</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="45"/> <source>All</source> <translation>Todos</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="50"/> <source>Normal</source> <translation>Normal</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="55"/> <source>Datums</source> <translation>Datums</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="60"/> <source>Named</source> <translation>Nomeado</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="65"/> <source>Reference</source> <translation>Referência</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="75"/> <source>Internal alignments will be hidden</source> <translation>Os alinhamentos internos serão ocultos</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="78"/> <source>Hide internal alignment</source> <translation>Ocultar alinhamento interno</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="94"/> <source>Extended information will be added to the list</source> <translation>Informações adicionais serão acrescidas à lista</translation> </message> <message> <location filename="../../TaskSketcherConstrains.ui" line="97"/> <source>Extended information</source> <translation>Informação adicional</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="638"/> <source>Constraints</source> <translation>Restrições</translation> </message> <message> <location filename="../../TaskSketcherConstrains.cpp" line="856"/> <location filename="../../TaskSketcherConstrains.cpp" line="872"/> <source>Error</source> <translation>Erro</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherElements</name> <message> <location filename="../../TaskSketcherElements.ui" line="14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="22"/> <source>Type:</source> <translation>Tipo:</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="42"/> <source>Edge</source> <translation>Aresta</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="47"/> <source>Starting Point</source> <translation>Ponto de partida</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="52"/> <source>End Point</source> <translation>Ponto final</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="57"/> <source>Center Point</source> <translation>Ponto central</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="69"/> <source>Mode:</source> <translation>Modo:</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="89"/> <source>All</source> <translation>Todos</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="94"/> <source>Normal</source> <translation>Normal</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="104"/> <source>External</source> <translation>Externo</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="133"/> <source>Extended naming containing info about element mode</source> <translation>Nomeação estendida, com informações sobre o modo do elemento</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="136"/> <source>Extended naming</source> <translation>Nomeação estendida</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="146"/> <source>Only the type 'Edge' will be available for the list</source> <translation>Somente o tipo 'Aresta' estará disponível para a lista</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="149"/> <source>Auto-switch to Edge</source> <translation>Auto-seleção de aresta</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="257"/> <source>Elements</source> <translation>Elementos</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="278"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&amp;quot;%1&amp;quot;: multiple selection&lt;/p&gt;&lt;p&gt;&amp;quot;%2&amp;quot;: switch to next valid type&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&amp;quot;%1&amp;quot;: seleção múltipla&lt;/p&gt;&lt;p&gt;&amp;quot;%2&amp;quot;: mudar para o próximo tipo válido&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="747"/> <location filename="../../TaskSketcherElements.cpp" line="748"/> <location filename="../../TaskSketcherElements.cpp" line="853"/> <location filename="../../TaskSketcherElements.cpp" line="854"/> <source>Point</source> <translation>Ponto</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="750"/> <location filename="../../TaskSketcherElements.cpp" line="752"/> <location filename="../../TaskSketcherElements.cpp" line="856"/> <location filename="../../TaskSketcherElements.cpp" line="857"/> <source>Line</source> <translation>Linha</translation> </message> <message> <location filename="../../TaskSketcherElements.ui" line="99"/> <location filename="../../TaskSketcherElements.cpp" line="751"/> <location filename="../../TaskSketcherElements.cpp" line="755"/> <location filename="../../TaskSketcherElements.cpp" line="759"/> <location filename="../../TaskSketcherElements.cpp" line="763"/> <location filename="../../TaskSketcherElements.cpp" line="767"/> <location filename="../../TaskSketcherElements.cpp" line="771"/> <location filename="../../TaskSketcherElements.cpp" line="775"/> <location filename="../../TaskSketcherElements.cpp" line="779"/> <location filename="../../TaskSketcherElements.cpp" line="783"/> <source>Construction</source> <translation>Construção</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="754"/> <location filename="../../TaskSketcherElements.cpp" line="756"/> <location filename="../../TaskSketcherElements.cpp" line="859"/> <location filename="../../TaskSketcherElements.cpp" line="860"/> <source>Arc</source> <translation>Arco</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="758"/> <location filename="../../TaskSketcherElements.cpp" line="760"/> <location filename="../../TaskSketcherElements.cpp" line="862"/> <location filename="../../TaskSketcherElements.cpp" line="863"/> <source>Circle</source> <translation>Círculo</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="762"/> <location filename="../../TaskSketcherElements.cpp" line="764"/> <location filename="../../TaskSketcherElements.cpp" line="865"/> <location filename="../../TaskSketcherElements.cpp" line="866"/> <source>Ellipse</source> <translation>Elipse</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="766"/> <location filename="../../TaskSketcherElements.cpp" line="768"/> <location filename="../../TaskSketcherElements.cpp" line="868"/> <location filename="../../TaskSketcherElements.cpp" line="869"/> <source>Elliptical Arc</source> <translation>Arco elíptico</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="770"/> <location filename="../../TaskSketcherElements.cpp" line="772"/> <location filename="../../TaskSketcherElements.cpp" line="871"/> <location filename="../../TaskSketcherElements.cpp" line="872"/> <source>Hyperbolic Arc</source> <translation>Arco hiperbólico</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="774"/> <location filename="../../TaskSketcherElements.cpp" line="776"/> <location filename="../../TaskSketcherElements.cpp" line="874"/> <location filename="../../TaskSketcherElements.cpp" line="875"/> <source>Parabolic Arc</source> <translation>Arco parabólico</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="778"/> <location filename="../../TaskSketcherElements.cpp" line="780"/> <location filename="../../TaskSketcherElements.cpp" line="877"/> <location filename="../../TaskSketcherElements.cpp" line="878"/> <source>BSpline</source> <translation>BSpline</translation> </message> <message> <location filename="../../TaskSketcherElements.cpp" line="782"/> <location filename="../../TaskSketcherElements.cpp" line="784"/> <location filename="../../TaskSketcherElements.cpp" line="880"/> <location filename="../../TaskSketcherElements.cpp" line="881"/> <source>Other</source> <translation>Outro</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherGeneral</name> <message> <location filename="../../TaskSketcherGeneral.ui" line="14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="23"/> <source>A grid will be shown</source> <translation>Uma grade será mostrada</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="26"/> <source>Show grid</source> <translation>Mostrar grade</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="44"/> <source>Grid size:</source> <translation>Tamanho da grade:</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="51"/> <source>Distance between two subsequent grid lines</source> <translation>Distância entre duas linhas da grade</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="87"/> <source>New points will snap to the nearest grid line. Points must be set closer than a fifth of the grid size to a grid line to snap.</source> <translation>Novos pontos serão colocados no nó mais próximo da grade. Os pontos devem ser mais próximos de um quinto do tamanho de grade para serem colocados em um nó da grade.</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="91"/> <source>Grid snap</source> <translation>Alinhar à grade</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="107"/> <source>Sketcher proposes automatically sensible constraints.</source> <translation>O esboço propõe automaticamente restrições adequadas.</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="110"/> <source>Auto constraints</source> <translation>Restrições automáticas</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="126"/> <source>Sketcher tries not to propose redundant auto constraints</source> <translation>O esboço tenta não propor restrições redundantes automáticamente</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="129"/> <source>Avoid redundant auto constraints</source> <translation>Evitar auto-restrições redundantes</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="145"/> <source>Rendering order (global):</source> <translation>Ordem de renderização (global):</translation> </message> <message> <location filename="../../TaskSketcherGeneral.ui" line="164"/> <source>To change, drag and drop a geometry type to top or bottom</source> <translation>Para alterar, arraste e solte um tipo de geometria para cima ou para baixo</translation> </message> <message> <location filename="../../TaskSketcherGeneral.cpp" line="195"/> <source>Edit controls</source> <translation>Controles de edição</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherMessages</name> <message> <location filename="../../TaskSketcherMessages.cpp" line="51"/> <source>Solver messages</source> <translation>Mensagens</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherSolverAdvanced</name> <message> <location filename="../../TaskSketcherSolverAdvanced.cpp" line="64"/> <source>Advanced solver control</source> <translation>Controle avançado do Solver</translation> </message> </context> <context> <name>SketcherGui::TaskSketcherValidation</name> <message> <location filename="../../TaskSketcherValidation.ui" line="14"/> <source>Sketcher validation</source> <translation>Validação de esboço</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="70"/> <source>Invalid constraints</source> <translation>Restrições inválidas</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="53"/> <location filename="../../TaskSketcherValidation.ui" line="83"/> <location filename="../../TaskSketcherValidation.ui" line="113"/> <source>Fix</source> <translation>Consertar</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="46"/> <location filename="../../TaskSketcherValidation.ui" line="76"/> <location filename="../../TaskSketcherValidation.ui" line="106"/> <location filename="../../TaskSketcherValidation.ui" line="129"/> <source>Find</source> <translation>Procurar</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="90"/> <source>Delete constraints to external geom.</source> <translation>Excluir restrições para geometria externa</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="20"/> <source>Missing coincidences</source> <translation>Coincidências faltantes</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="26"/> <source>Tolerance:</source> <translation>Tolerância:</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="60"/> <source>Highlight open vertexes</source> <translation>Destacar os vértices abertos</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="36"/> <source>Ignore construction geometry</source> <translation>Ignorar a geometria de construção</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="100"/> <source>Degenerated geometry</source> <translation>Geometria corrompida</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="123"/> <source>Reversed external geometry</source> <translation>Geometria externa invertida</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="136"/> <source>Swap endpoints in constraints</source> <translation>Trocar pontos de extremidade em restrições</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="146"/> <source>Constraint orientation locking</source> <translation>Restrição de bloqueio de orientação</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="152"/> <source>Enable/Update</source> <translation>Ativar/Atualizar</translation> </message> <message> <location filename="../../TaskSketcherValidation.ui" line="159"/> <source>Disable</source> <translation>Desativar</translation> </message> </context> <context> <name>SketcherGui::ViewProviderSketch</name> <message> <location filename="../../ViewProviderSketch.cpp" line="6162"/> <source>Edit sketch</source> <translation>Editar esboço</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6176"/> <source>A dialog is already open in the task panel</source> <translation>Uma caixa de diálogo já está aberta no painel de tarefas</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6177"/> <source>Do you want to close this dialog?</source> <translation>Deseja fechar este diálogo?</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6191"/> <source>Invalid sketch</source> <translation>Esboço inválido</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6192"/> <source>Do you want to open the sketch validation tool?</source> <translation>Você quer abrir a ferramenta de validação de esboço?</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6193"/> <source>The sketch is invalid and cannot be edited.</source> <translation>O esboço é inválido e não pode ser editado.</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6407"/> <source>Please remove the following constraint:</source> <translation>Por favor, remova a seguinte restrição:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6408"/> <source>Please remove at least one of the following constraints:</source> <translation>Por favor remova pelo menos uma das seguintes restrições:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6414"/> <source>Please remove the following redundant constraint:</source> <translation>Por favor, remova a seguinte restrição redundante:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6415"/> <source>Please remove the following redundant constraints:</source> <translation>Por favor, remova as seguintes restrições redundantes:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6421"/> <source>The following constraint is partially redundant:</source> <translation>A restrição seguinte é parcialmente redundante:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6422"/> <source>The following constraints are partially redundant:</source> <translation>As restrições seguintes são parcialmente redundantes:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6428"/> <source>Please remove the following malformed constraint:</source> <translation>Por favor remova as seguintes restrições malformadas:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6429"/> <source>Please remove the following malformed constraints:</source> <translation>Por favor remova as seguintes restrições malformadas:</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6464"/> <source>Empty sketch</source> <translation>Esboço vazio</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6471"/> <source>Over-constrained sketch </source> <translation>Esboço superrestrito </translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6472"/> <location filename="../../ViewProviderSketch.cpp" line="6479"/> <location filename="../../ViewProviderSketch.cpp" line="6486"/> <location filename="../../ViewProviderSketch.cpp" line="6494"/> <location filename="../../ViewProviderSketch.cpp" line="6503"/> <source>(click to select)</source> <translation>(clique para selecionar)</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6478"/> <source>Sketch contains malformed constraints </source> <translation>O esboço contém restrições malformadas </translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6485"/> <source>Sketch contains conflicting constraints </source> <translation>Esboço contém restrições conflitantes </translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6493"/> <source>Sketch contains redundant constraints </source> <translation>Esboço contém restrições redundantes </translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6502"/> <source>Sketch contains partially redundant constraints </source> <translation>O esboço contém restrições parcialmente redundantes </translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6514"/> <source>Fully constrained sketch</source> <translation>Esboço totalmente restrito</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6521"/> <source>Under-constrained sketch with &lt;a href="#dofs"&gt;&lt;span style=" text-decoration: underline; color:#0000ff; background-color: #F8F8FF;"&gt;1 degree&lt;/span&gt;&lt;/a&gt; of freedom. %1</source> <translation>Esboço sub-restrito com &lt;a href="#dofs"&gt;&lt;span style=" text-decoration: underline; color:#0000ff; background-color: #F8F8FF;"&gt;1 grau&lt;/span&gt;&lt;/a&gt; de liberdade. %1</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6524"/> <source>Under-constrained sketch with &lt;a href="#dofs"&gt;&lt;span style=" text-decoration: underline; color:#0000ff; background-color: #F8F8FF;"&gt;%1 degrees&lt;/span&gt;&lt;/a&gt; of freedom. %2</source> <translation>Esboço sub-restrito com &lt;a href="#dofs"&gt;&lt;span style=" text-decoration: underline; color:#0000ff; background-color: #F8F8FF;"&gt;%1 graus&lt;/span&gt;&lt;/a&gt; de liberdade. %2</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6529"/> <source>Solved in %1 sec</source> <translation>Resolvido em %1 seg</translation> </message> <message> <location filename="../../ViewProviderSketch.cpp" line="6532"/> <source>Unsolved (%1 sec)</source> <translation>Não resolvidos (%1 seg)</translation> </message> </context> <context> <name>Sketcher_BSplineComb</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="347"/> <location filename="../../CommandSketcherBSpline.cpp" line="349"/> <source>Switches between showing and hiding the curvature comb for all B-splines</source> <translation>Alterna entre mostrar e ocultar o pente de curvatura para todas as B-splines</translation> </message> </context> <context> <name>Sketcher_BSplineDecreaseKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="970"/> <location filename="../../CommandSketcherBSpline.cpp" line="972"/> <source>Decreases the multiplicity of the selected knot of a B-spline</source> <translation>Diminui a multiplicidade do nó selecionado de uma B-spline</translation> </message> </context> <context> <name>Sketcher_BSplineDegree</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="333"/> <location filename="../../CommandSketcherBSpline.cpp" line="335"/> <source>Switches between showing and hiding the degree for all B-splines</source> <translation>Alterna entre mostrar e ocultar o grau para todas os B-splines</translation> </message> </context> <context> <name>Sketcher_BSplineIncreaseKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="963"/> <location filename="../../CommandSketcherBSpline.cpp" line="965"/> <source>Increases the multiplicity of the selected knot of a B-spline</source> <translation>Aumenta a multiplicidade do nó selecionado de uma B-spline</translation> </message> </context> <context> <name>Sketcher_BSplineKnotMultiplicity</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="354"/> <location filename="../../CommandSketcherBSpline.cpp" line="356"/> <source>Switches between showing and hiding the knot multiplicity for all B-splines</source> <translation>Alterna entre mostrar e ocultar a multiplicidade de nós para todas as B-splines</translation> </message> </context> <context> <name>Sketcher_BSplinePoleWeight</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="362"/> <location filename="../../CommandSketcherBSpline.cpp" line="364"/> <source>Switches between showing and hiding the control point weight for all B-splines</source> <translation>Alterna entre mostrar e ocultar o peso dos pontos de controle para todas as B-splines</translation> </message> </context> <context> <name>Sketcher_BSplinePolygon</name> <message> <location filename="../../CommandSketcherBSpline.cpp" line="340"/> <location filename="../../CommandSketcherBSpline.cpp" line="342"/> <source>Switches between showing and hiding the control polygons for all B-splines</source> <translation>Alterna entre mostrar e ocultar os polígonos de controle para todas as B-splines</translation> </message> </context> <context> <name>Sketcher_Clone</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1708"/> <location filename="../../CommandSketcherTools.cpp" line="1709"/> <source>Creates a clone of the geometry taking as reference the last selected point</source> <translation>Cria um clone da geometria tomando como referência o último ponto selecionado</translation> </message> </context> <context> <name>Sketcher_CompCopy</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1707"/> <source>Clone</source> <translation>Clonar</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1711"/> <source>Copy</source> <translation>Copiar</translation> </message> <message> <location filename="../../CommandSketcherTools.cpp" line="1715"/> <source>Move</source> <translation>Mover</translation> </message> </context> <context> <name>Sketcher_ConstrainDiameter</name> <message> <location filename="../../CommandConstraints.cpp" line="5820"/> <location filename="../../CommandConstraints.cpp" line="5821"/> <source>Fix the diameter of a circle or an arc</source> <translation>Corrigir o diâmetro de um círculo ou arco</translation> </message> </context> <context> <name>Sketcher_ConstrainRadius</name> <message> <location filename="../../CommandConstraints.cpp" line="5816"/> <location filename="../../CommandConstraints.cpp" line="5817"/> <source>Fix the radius of a circle or an arc</source> <translation>Fixar o raio de um círculo ou um arco</translation> </message> </context> <context> <name>Sketcher_Copy</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1712"/> <location filename="../../CommandSketcherTools.cpp" line="1713"/> <source>Creates a simple copy of the geometry taking as reference the last selected point</source> <translation>Cria uma cópia simples da geometria tomando como referência o último ponto selecionado</translation> </message> </context> <context> <name>Sketcher_Create3PointArc</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1893"/> <location filename="../../CommandCreateGeo.cpp" line="1894"/> <source>Create an arc by its end points and a point along the arc</source> <translation>Criar um arco a partir de seus pontos de extremidade e um ponto ao longo do arco</translation> </message> </context> <context> <name>Sketcher_Create3PointCircle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4847"/> <location filename="../../CommandCreateGeo.cpp" line="4848"/> <source>Create a circle by 3 rim points</source> <translation>Criar um círculo a partir de 3 pontos de borda</translation> </message> </context> <context> <name>Sketcher_CreateArc</name> <message> <location filename="../../CommandCreateGeo.cpp" line="1889"/> <location filename="../../CommandCreateGeo.cpp" line="1890"/> <source>Create an arc by its center and by its end points</source> <translation>Criar um arco a partir do seu centro e por seus pontos de extremidade</translation> </message> </context> <context> <name>Sketcher_CreateArcOfEllipse</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3984"/> <location filename="../../CommandCreateGeo.cpp" line="3985"/> <source>Create an arc of ellipse by its center, major radius, and endpoints</source> <translation>Criar um arco de elipse pelo centro, raio principal e pontos de extremidade</translation> </message> </context> <context> <name>Sketcher_CreateArcOfHyperbola</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3988"/> <location filename="../../CommandCreateGeo.cpp" line="3989"/> <source>Create an arc of hyperbola by its center, major radius, and endpoints</source> <translation>Criar um arco de hipérbole pelo centro, raio principal e pontos de extremidade</translation> </message> </context> <context> <name>Sketcher_CreateArcOfParabola</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3992"/> <location filename="../../CommandCreateGeo.cpp" line="3993"/> <source>Create an arc of parabola by its focus, vertex, and endpoints</source> <translation>Criar um arco de parábola pelo foco, vértice e pontos de extremidade</translation> </message> </context> <context> <name>Sketcher_CreateBSpline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4531"/> <source>B-spline by control points</source> <translation>B-spline por pontos de controle</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4532"/> <location filename="../../CommandCreateGeo.cpp" line="4533"/> <source>Create a B-spline by control points</source> <translation>Criar uma B-spline por pontos de controle</translation> </message> </context> <context> <name>Sketcher_CreateCircle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4843"/> <location filename="../../CommandCreateGeo.cpp" line="4844"/> <source>Create a circle by its center and by a rim point</source> <translation>Criar um círculo a partir do seu centro e por um ponto de borda</translation> </message> </context> <context> <name>Sketcher_CreateEllipseBy3Points</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3980"/> <location filename="../../CommandCreateGeo.cpp" line="3981"/> <source>Create a ellipse by periapsis, apoapsis, and minor radius</source> <translation>Criar uma elipse por periapsis apoapsis e menor raio</translation> </message> </context> <context> <name>Sketcher_CreateEllipseByCenter</name> <message> <location filename="../../CommandCreateGeo.cpp" line="3976"/> <location filename="../../CommandCreateGeo.cpp" line="3977"/> <source>Create an ellipse by center, major radius and point</source> <translation>Criar uma elipse pelo centro, raio maior e ponto</translation> </message> </context> <context> <name>Sketcher_CreateFillet</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5418"/> <location filename="../../CommandCreateGeo.cpp" line="5419"/> <source>Creates a radius between two lines</source> <translation>Cria um raio entre duas linhas</translation> </message> </context> <context> <name>Sketcher_CreateHeptagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6967"/> <location filename="../../CommandCreateGeo.cpp" line="6968"/> <source>Create a heptagon by its center and by one corner</source> <translation>Criar um heptágono pelo seu centro e por um canto</translation> </message> </context> <context> <name>Sketcher_CreateHexagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6963"/> <location filename="../../CommandCreateGeo.cpp" line="6964"/> <source>Create a hexagon by its center and by one corner</source> <translation>Criar um hexágono por seu centro e um canto</translation> </message> </context> <context> <name>Sketcher_CreateOctagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6971"/> <location filename="../../CommandCreateGeo.cpp" line="6972"/> <source>Create an octagon by its center and by one corner</source> <translation>Criar um octógono pelo seu centro e por um canto</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="6975"/> <location filename="../../CommandCreateGeo.cpp" line="6976"/> <source>Create a regular polygon by its center and by one corner</source> <translation>Criar um polígono regular pelo seu centro e por um vértice</translation> </message> </context> <context> <name>Sketcher_CreatePentagon</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6959"/> <location filename="../../CommandCreateGeo.cpp" line="6960"/> <source>Create a pentagon by its center and by one corner</source> <translation>Criar um pentágono pelo seu centro e por um canto</translation> </message> </context> <context> <name>Sketcher_CreatePointFillet</name> <message> <location filename="../../CommandCreateGeo.cpp" line="5422"/> <location filename="../../CommandCreateGeo.cpp" line="5423"/> <source>Fillet that preserves constraints and intersection point</source> <translation>Filete que preserva restrições e ponto de interseção</translation> </message> </context> <context> <name>Sketcher_CreateSquare</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6955"/> <location filename="../../CommandCreateGeo.cpp" line="6956"/> <source>Create a square by its center and by one corner</source> <translation>Criar um quadrado pelo seu centro e por um canto</translation> </message> </context> <context> <name>Sketcher_CreateTriangle</name> <message> <location filename="../../CommandCreateGeo.cpp" line="6951"/> <location filename="../../CommandCreateGeo.cpp" line="6952"/> <source>Create an equilateral triangle by its center and by one corner</source> <translation>Criar um triângulo equilátero, pelo seu centro e por um canto</translation> </message> </context> <context> <name>Sketcher_Create_Periodic_BSpline</name> <message> <location filename="../../CommandCreateGeo.cpp" line="4535"/> <source>Periodic B-spline by control points</source> <translation>B-spline periódica por pontos de controle</translation> </message> <message> <location filename="../../CommandCreateGeo.cpp" line="4536"/> <location filename="../../CommandCreateGeo.cpp" line="4537"/> <source>Create a periodic B-spline by control points</source> <translation>Criar uma B-spline periódica por pontos de controle</translation> </message> </context> <context> <name>Sketcher_MapSketch</name> <message> <location filename="../../Command.cpp" line="533"/> <source>No sketch found</source> <translation>Nenhum esboço encontrado</translation> </message> <message> <location filename="../../Command.cpp" line="534"/> <source>The document doesn't have a sketch</source> <translation>O documento não tem um esboço</translation> </message> <message> <location filename="../../Command.cpp" line="543"/> <source>Select sketch</source> <translation>Selecione o esboço</translation> </message> <message> <location filename="../../Command.cpp" line="544"/> <source>Select a sketch from the list</source> <translation>Selecione um esboço da lista</translation> </message> <message> <location filename="../../Command.cpp" line="598"/> <source> (incompatible with selection)</source> <translation> (incompatível com a seleção)</translation> </message> <message> <location filename="../../Command.cpp" line="600"/> <source> (current)</source> <translation> (atual)</translation> </message> <message> <location filename="../../Command.cpp" line="607"/> <source> (suggested)</source> <translation> (sugerido)</translation> </message> <message> <location filename="../../Command.cpp" line="613"/> <source>Sketch attachment</source> <translation>Esboço anexado</translation> </message> <message> <location filename="../../Command.cpp" line="615"/> <source>Current attachment mode is incompatible with the new selection. Select the method to attach this sketch to selected objects.</source> <translation>O modo de anexo atual é incompatível com a nova seleção. Selecione um outro método para anexar este esboço aos objetos selecionados.</translation> </message> <message> <location filename="../../Command.cpp" line="619"/> <source>Select the method to attach this sketch to selected objects.</source> <translation>Selecione o método para anexar este esboço aos objetos selecionados.</translation> </message> <message> <location filename="../../Command.cpp" line="656"/> <source>Map sketch</source> <translation>Esboço de mapa</translation> </message> <message> <location filename="../../Command.cpp" line="657"/> <source>Can't map a sketch to support: %1</source> <translation>Não é possível mapear um esboço para suporte:%1</translation> </message> </context> <context> <name>Sketcher_Move</name> <message> <location filename="../../CommandSketcherTools.cpp" line="1716"/> <location filename="../../CommandSketcherTools.cpp" line="1717"/> <source>Moves the geometry taking as reference the last selected point</source> <translation>Move a geometria usando como referência o último ponto selecionado</translation> </message> </context> <context> <name>Sketcher_NewSketch</name> <message> <location filename="../../Command.cpp" line="180"/> <source>Sketch attachment</source> <translation>Esboço anexado</translation> </message> <message> <location filename="../../Command.cpp" line="181"/> <source>Select the method to attach this sketch to selected object</source> <translation>Selecione o método para anexar este esboço para o objeto selecionado</translation> </message> </context> <context> <name>Sketcher_ReorientSketch</name> <message> <location filename="../../Command.cpp" line="395"/> <source>Sketch has support</source> <translation>O esboço tem suporte</translation> </message> <message> <location filename="../../Command.cpp" line="396"/> <source>Sketch with a support face cannot be reoriented. Do you want to detach it from the support?</source> <translation>Um esboço com uma face de suporte não pode ser reorientado. Deseja separá-lo do seu suporte?</translation> </message> </context> <context> <name>TaskSketcherMessages</name> <message> <location filename="../../TaskSketcherMessages.ui" line="14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="20"/> <source>Undefined degrees of freedom</source> <translation>Graus de liberdade indefinidos</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="30"/> <source>Not solved yet</source> <translation>Não resolvido ainda</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="40"/> <source>New constraints that would be redundant will automatically be removed</source> <translation>Novas restrições que seriam redundantes serão automaticamente removidas</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="43"/> <source>Auto remove redundants</source> <translation>Remover redundâncias automaticamente</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="61"/> <source>Executes a recomputation of active document after every sketch action</source> <translation>Executa um recálculo do documento ativo após cada comando</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="64"/> <source>Auto update</source> <translation>Atualização automática</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="80"/> <source>Forces recomputation of active document</source> <translation>Força um recálculo do documento ativo</translation> </message> <message> <location filename="../../TaskSketcherMessages.ui" line="83"/> <source>Update</source> <translation>Atualizar</translation> </message> </context> <context> <name>TaskSketcherSolverAdvanced</name> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="22"/> <source>Default algorithm used for Sketch solving</source> <translation>Algoritmo padrão usado para solver o Esboço</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="25"/> <source>Default solver:</source> <translation>Calculador padrão:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="32"/> <source>Solver is used for solving the geometry. LevenbergMarquardt and DogLeg are trust region optimization algorithms. BFGS solver uses the Broyden–Fletcher–Goldfarb–Shanno algorithm.</source> <translation>O calculador usado para resolver a geometria. LevenbergMarquardt e DogLeg são algoritmos de otimização de região de confiança. O calculador BFGS usa o algoritmo Broyden–Fletcher–Goldfarb–Shanno.</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="47"/> <location filename="../../TaskSketcherSolverAdvanced.ui" line="393"/> <source>BFGS</source> <translation>GFGS</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="52"/> <location filename="../../TaskSketcherSolverAdvanced.ui" line="398"/> <source>LevenbergMarquardt</source> <translation>LevenbergMarquardt</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="57"/> <location filename="../../TaskSketcherSolverAdvanced.ui" line="403"/> <source>DogLeg</source> <translation>DogLeg</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="69"/> <source>Type of function to apply in DogLeg for the Gauss step</source> <translation>Tipo de função para aplicar em DogLeg para a etapa de Gauss</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="72"/> <source>DogLeg Gauss step:</source> <translation>DogLeg passo de Gauss:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="79"/> <source>Step type used in the DogLeg algorithm</source> <translation>Tipo de etapa usado no algoritmo de DogLeg</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="92"/> <source>FullPivLU</source> <translation>FullPivLU</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="97"/> <source>LeastNorm-FullPivLU</source> <translation>LeastNorm-FullPivLU</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="102"/> <source>LeastNorm-LDLT</source> <translation>LeastNorm-LDLT</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="114"/> <source>Maximum number of iterations of the default algorithm</source> <translation>Número máximo de iterações do algoritmo padrão</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="117"/> <source>Maximum iterations:</source> <translation>Iterações máximas:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="124"/> <source>Maximum iterations to find convergence before solver is stopped</source> <translation>Máximo de iterações para encontrar a convergência antes do calculador ser interrompido</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="301"/> <source>QR algorithm:</source> <translation>Algoritmo QR:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="308"/> <source>During diagnosing the QR rank of matrix is calculated. Eigen Dense QR is a dense matrix QR with full pivoting; usually slower Eigen Sparse QR algorithm is optimized for sparse matrices; usually faster</source> <translation>Durante o diagnóstico, a classificação QR da matriz é calculada. Eigen Dense QR é uma matriz densa QR com pivô total; geralmente é mais lento o algorítimo Eigen Sparse QR é otimizado para matrizes escassas; geralmente é mais rápido</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="373"/> <source>Redundant solver:</source> <translation>Calculador de redundâncias:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="380"/> <source>Solver used to determine whether a group is redundant or conflicting</source> <translation>Calculador usado para determinar se um grupo é redundante ou conflitante</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="418"/> <source>Redundant max. iterations:</source> <translation>Iterações máximas de redundâncias:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="425"/> <source>Same as 'Maximum iterations', but for redundant solving</source> <translation>O mesmo que 'Iterações máximas', mas para resolução de redundâncias</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="454"/> <source>Redundant sketch size multiplier:</source> <translation>Multiplicador de tamanho do esboço para redundâncias:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="461"/> <source>Same as 'Sketch size multiplier', but for redundant solving</source> <translation>Igual ao 'multiplicador de tamanho do esboço', mas para resolução de redundâncias</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="487"/> <source>Redundant convergence</source> <translation>Convergência redundante</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="494"/> <source>Same as 'Convergence', but for redundant solving</source> <translation>O mesmo que 'Convergência', mas para resolução de redundâncias</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="517"/> <source>Redundant param1</source> <translation>Parâmetro de redundância 1</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="541"/> <source>Redundant param2</source> <translation>Parâmetro de redundância 2</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="565"/> <source>Redundant param3</source> <translation>Parâmetro de redundância 3</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="592"/> <source>Console debug mode:</source> <translation>Modo de depuração do console:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="599"/> <source>Verbosity of console output</source> <translation>Verbosidade da saída do console</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="150"/> <source>If selected, the Maximum iterations value is multiplied by the sketch size</source> <translation>Se selecionado, o valor de iterações máximo é multiplicado pelo tamanho do esboço</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="153"/> <source>Sketch size multiplier:</source> <translation>Multiplicador de tamanho do esboço:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="166"/> <source>Maximum iterations will be multiplied by number of parameters</source> <translation>Máximo de iterações será multiplicado pelo número de parâmetros</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="189"/> <source>Error threshold under which convergence is reached</source> <translation>Limite de erro sob as quais a convergência é alcançada</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="192"/> <source>Convergence:</source> <translation>Convergência:</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="199"/> <source>Threshold for squared error that is used to determine whether a solution converges or not</source> <translation>Limite para o erro ao quadrado que é usado para determinar se uma solução converge ou não</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="226"/> <source>Param1</source> <translation>Param1</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="250"/> <source>Param2</source> <translation>Param2</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="274"/> <source>Param3</source> <translation>Param3</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="298"/> <source>Algorithm used for the rank revealing QR decomposition</source> <translation>Algoritmo usado para a classificação revelando decomposição QR</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="323"/> <source>Eigen Dense QR</source> <translation>Eigen densa QR</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="328"/> <source>Eigen Sparse QR</source> <translation>Eigen esparsas QR</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="340"/> <source>Pivot threshold</source> <translation>Limiar de pivô</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="347"/> <source>During a QR, values under the pivot threshold are treated as zero</source> <translation>Durante um QR, valores abaixo do limiar de pivô são tratados como zero</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="350"/> <source>1E-13</source> <translation>1E-13</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="370"/> <source>Solving algorithm used for determination of Redundant constraints</source> <translation>Resolvendo algoritmo usado para determinação de restrições redundantes</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="415"/> <source>Maximum number of iterations of the solver used for determination of Redundant constraints</source> <translation>Número máximo de iterações do solver usado para determinação de restrições redundantes</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="451"/> <source>If selected, the Maximum iterations value for the redundant algorithm is multiplied by the sketch size</source> <translation>Se selecionado, o valor de iterações máximo para o algoritmo redundante é multiplicado pelo tamanho do esboço</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="484"/> <source>Error threshold under which convergence is reached for the solving of redundant constraints</source> <translation>Limite de erro sob as quais a convergência é alcançada para a resolução de restrições redundantes</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="497"/> <source>1E-10</source> <translation>1E-10</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="589"/> <source>Degree of verbosity of the debug output to the console</source> <translation>Grau de detalhamento da saída de depuração para o console</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="612"/> <source>None</source> <translation>Nenhum</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="617"/> <source>Minimum</source> <translation>Mínimo</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="622"/> <source>Iteration Level</source> <translation>Nível de iteração</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="634"/> <source>Solve</source> <translation>Resolver</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="641"/> <source>Resets all solver values to their default values</source> <translation>Redefine todos os valores do solver para seus valores predefinidos</translation> </message> <message> <location filename="../../TaskSketcherSolverAdvanced.ui" line="644"/> <source>Restore Defaults</source> <translation>Restaurar Predefinições</translation> </message> </context> <context> <name>Workbench</name> <message> <location filename="../../Workbench.cpp" line="37"/> <source>Sketcher</source> <translation>Esboço</translation> </message> <message> <location filename="../../Workbench.cpp" line="38"/> <source>Sketcher geometries</source> <translation>Geometrias do esboço</translation> </message> <message> <location filename="../../Workbench.cpp" line="39"/> <source>Sketcher constraints</source> <translation>Restrições de esboço</translation> </message> <message> <location filename="../../Workbench.cpp" line="40"/> <source>Sketcher tools</source> <translation>Ferramentas de esboço</translation> </message> <message> <location filename="../../Workbench.cpp" line="41"/> <source>Sketcher B-spline tools</source> <translation>Ferramentas de B-spline</translation> </message> <message> <location filename="../../Workbench.cpp" line="42"/> <source>Sketcher virtual space</source> <translation>Espaço virtual de esboço</translation> </message> </context> </TS>
Fat-Zer/FreeCAD_sf_master
src/Mod/Sketcher/Gui/Resources/translations/Sketcher_pt-BR.ts
TypeScript
lgpl-2.1
277,110
#ifndef BRACKETEDKEYWORDINCONTEXTDELEGATE_HH #define BRACKETEDKEYWORDINCONTEXTDELEGATE_HH #include <vector> #include <AlpinoCorpus/LexItem.hh> #include "BracketedDelegate.hh" class BracketedKeywordInContextDelegate : public BracketedDelegate { Q_OBJECT public: BracketedKeywordInContextDelegate(CorpusReaderPtr); virtual ~BracketedKeywordInContextDelegate() {} void paint(QPainter *painter, QStyleOptionViewItem const &option, QModelIndex const &index) const; QSize sizeHint(QStyleOptionViewItem const &option, QModelIndex const &index) const; private: void loadColorSettings(); QString extractFragment(std::vector<alpinocorpus::LexItem> const &items, size_t first, size_t last) const; mutable QColor d_highlightColor; }; #endif
evdmade01/dact
include/BracketedKeywordInContextDelegate.hh
C++
lgpl-2.1
770
// Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License. // // This library is distributed in the hope that it will be useful // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // // // File: ShHealOper_ChangeOrientation.cxx // Created: 11.07.06 11:46:45 // Author: Sergey KUUL #include <ShHealOper_ChangeOrientation.hxx> #include <BRep_Builder.hxx> #include <TopoDS_Iterator.hxx> //======================================================================= //function : ShHealOper_ChangeOrientation() //purpose : Constructor //======================================================================= ShHealOper_ChangeOrientation::ShHealOper_ChangeOrientation ( const TopoDS_Shape& theShape ) { Init(theShape); } //======================================================================= //function : Init //purpose : //======================================================================= void ShHealOper_ChangeOrientation::Init(const TopoDS_Shape& theShape) { ShHealOper_Tool::Init(theShape); } //======================================================================= //function : Perform //purpose : //======================================================================= Standard_Boolean ShHealOper_ChangeOrientation::Perform() { BRep_Builder B; if (myInitShape.ShapeType() == TopAbs_SHELL) { myResultShape = myInitShape.EmptyCopied(); TopoDS_Iterator itr(myInitShape); while (itr.More()) { B.Add(myResultShape,itr.Value().Reversed()); itr.Next(); } } else if (myInitShape.ShapeType() == TopAbs_FACE) { myResultShape = myInitShape.EmptyCopied(); TopoDS_Iterator itr(myInitShape); while (itr.More()) { B.Add(myResultShape,itr.Value()); itr.Next(); } myResultShape.Reverse(); } else if ( myInitShape.ShapeType() == TopAbs_WIRE || myInitShape.ShapeType() == TopAbs_EDGE) { myResultShape = myInitShape.EmptyCopied(); TopoDS_Iterator itr(myInitShape); while (itr.More()) { B.Add(myResultShape,itr.Value()); itr.Next(); } myResultShape.Reverse(); } else { return false; } return true; }
hmeyer/salome-geom
src/ShHealOper/ShHealOper_ChangeOrientation.cpp
C++
lgpl-2.1
2,864
<?php function hello($to_who /* ... */) { print "Hello $to_who!\n"; } hello("world");
bragful/ephp
test/code/test_funct_args_comment.php
PHP
lgpl-2.1
93
/* * Javascript terminal * * Copyright (c) 2011 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ "use strict"; function Term(width, height, handler) { this.w = width; this.h = height; this.cur_h = height; /* current height of the scroll back buffer */ this.tot_h = 1000; /* total height of the scroll back buffer */ this.y_base = 0; /* position of the current top screen line in the * scroll back buffer */ this.y_disp = 0; /* position of the top displayed line in the * scroll back buffer */ /* cursor position */ this.x = 0; this.y = 0; this.cursorstate = 0; this.handler = handler; this.convert_lf_to_crlf = false; this.state = 0; this.output_queue = ""; this.bg_colors = [ "#000000", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff" ]; this.fg_colors = [ "#000000", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff" ]; this.def_attr = (7 << 3) | 0; this.cur_attr = this.def_attr; this.is_mac = (navigator.userAgent.indexOf("Mac") >=0 ) ? true : false; this.key_rep_state = 0; this.key_rep_str = ""; } Term.prototype.open = function() { var y, line, i, term, c; /* set initial content */ this.lines = new Array(); c = 32 | (this.def_attr << 16); for(y = 0; y < this.cur_h;y++) { line = new Array(); for(i=0;i<this.w;i++) line[i] = c; this.lines[y] = line; } /* create terminal window */ document.writeln('<table border="0" cellspacing="0" cellpadding="0">'); for(y=0;y<this.h;y++) { document.writeln('<tr><td class="term" id="tline' + y + '"></td></tr>'); } document.writeln('</table>'); this.refresh(0, this.h - 1); // key handler document.addEventListener("keydown", this.keyDownHandler.bind(this), true); document.addEventListener("keypress", this.keyPressHandler.bind(this), true); // cursor blinking term = this; setInterval(function() { term.cursor_timer_cb(); }, 1000); }; Term.prototype.refresh = function(ymin, ymax) { var el, y, line, outline, c, w, i, cx, attr, last_attr, fg, bg, y1; for(y = ymin; y <= ymax; y++) { /* convert to HTML string */ y1 = y + this.y_disp; if (y1 >= this.cur_h) y1 -= this.cur_h; line = this.lines[y1]; outline = ""; w = this.w; if (y == this.y && this.cursor_state && this.y_disp == this.y_base) { cx = this.x; } else { cx = -1; } last_attr = this.def_attr; for(i = 0; i < w; i++) { c = line[i]; attr = c >> 16; c &= 0xffff; if (i == cx) { attr = -1; /* cursor */ } if (attr != last_attr) { if (last_attr != this.def_attr) outline += '</span>'; if (attr != this.def_attr) { if (attr == -1) { /* cursor */ outline += '<span class="termReverse">'; } else { outline += '<span style="'; fg = (attr >> 3) & 7; bg = attr & 7; if (fg != 7) { outline += 'color:' + this.fg_colors[fg] + ';'; } if (bg != 0) { outline += 'background-color:' + this.bg_colors[bg] + ';'; } outline += '">'; } } } switch(c) { case 32: outline += "&nbsp;"; break; case 38: // '&' outline += "&amp;"; break; case 60: // '<' outline += "&lt;"; break; case 62: // '>' outline += "&gt;"; break; default: if (c < 32) { outline += "&nbsp;"; } else { outline += String.fromCharCode(c); } break; } last_attr = attr; } if (last_attr != this.def_attr) { outline += '</span>'; } el = document.getElementById("tline" + y); el.innerHTML = outline; } }; Term.prototype.cursor_timer_cb = function() { this.cursor_state ^= 1; this.refresh(this.y, this.y); }; Term.prototype.show_cursor = function() { if (!this.cursor_state) { this.cursor_state = 1; this.refresh(this.y, this.y); } }; Term.prototype.scroll = function() { var y, line, x, c, y1; /* increase height of buffer if possible */ if (this.cur_h < this.tot_h) { this.cur_h++; } /* move down one line */ if (++this.y_base == this.cur_h) this.y_base = 0; this.y_disp = this.y_base; c = 32 | (this.def_attr << 16); line = new Array(); for(x=0;x<this.w;x++) line[x] = c; y1 = this.y_base + this.h - 1; if (y1 >= this.cur_h) y1 -= this.cur_h; this.lines[y1] = line; }; /* scroll down or up in the scroll back buffer by n lines */ Term.prototype.scroll_disp = function(n) { var i, y1; /* slow but it does not really matters */ if (n >= 0) { for(i = 0; i < n; i++) { if (this.y_disp == this.y_base) break; if (++this.y_disp == this.cur_h) this.y_disp = 0; } } else { n = -n; y1 = this.y_base + this.h; if (y1 >= this.cur_h) y1 -= this.cur_h; for(i = 0; i < n; i++) { if (this.y_disp == y1) break; if (--this.y_disp < 0) this.y_disp = this.cur_h - 1; } } this.refresh(0, this.h - 1); }; Term.prototype.write = function(str) { function update(y) { ymin = Math.min(ymin, y); ymax = Math.max(ymax, y); } function erase_to_eol(s, x, y) { var l, i, c, y1; y1 = s.y_base + y; if (y1 >= s.cur_h) y1 -= s.cur_h; l = s.lines[y1]; c = 32 | (s.def_attr << 16); for(i = x; i < s.w; i++) l[i] = c; update(y); } function csi_colors(s, esc_params) { var j, n; if (esc_params.length == 0) { s.cur_attr= s.def_attr; } else { for(j = 0; j < esc_params.length; j++) { n = esc_params[j]; if (n >= 30 && n <= 37) { /* foreground */ s.cur_attr = (s.cur_attr & ~(7 << 3)) | ((n - 30) << 3); } else if (n >= 40 && n <= 47) { /* background */ s.cur_attr = (s.cur_attr & ~7) | (n - 40); } else if (n == 0) { /* default attr */ s.cur_attr = s.def_attr; } } } } var TTY_STATE_NORM = 0; var TTY_STATE_ESC = 1; var TTY_STATE_CSI = 2; var i, c, ymin, ymax, l, n, j, y1; /* update region is in ymin ymax */ ymin = this.h; ymax = -1; update(this.y); // remove the cursor /* reset top of displayed screen to top of real screen */ if (this.y_base != this.y_disp) { this.y_disp = this.y_base; /* force redraw */ ymin = 0; ymax = this.h - 1; } for(i = 0; i < str.length; i++) { c = str.charCodeAt(i); switch(this.state) { case TTY_STATE_NORM: switch(c) { case 10: if (this.convert_lf_to_crlf) { this.x = 0; // emulates '\r' } this.y++; if (this.y >= this.h) { this.y--; this.scroll(); ymin = 0; ymax = this.h - 1; } break; case 13: this.x = 0; break; case 8: if (this.x > 0) { this.x--; } break; case 9: /* tab */ n = (this.x + 8) & ~7; if (n <= this.w) { this.x = n; } break; case 27: this.state = TTY_STATE_ESC; break; default: if (c >= 32) { if (this.x >= this.w) { this.x = 0; this.y++; if (this.y >= this.h) { this.y--; this.scroll(); ymin = 0; ymax = this.h - 1; } } y1 = this.y + this.y_base; if (y1 >= this.cur_h) y1 -= this.cur_h; this.lines[y1][this.x] = (c & 0xffff) | (this.cur_attr << 16); this.x++; update(this.y); } break; } break; case TTY_STATE_ESC: if (c == 91) { // '[' this.esc_params = new Array(); this.cur_param = 0; this.state = TTY_STATE_CSI; } else { this.state = TTY_STATE_NORM; } break; case TTY_STATE_CSI: if (c >= 48 && c <= 57) { // '0' '9' /* numeric */ this.cur_param = this.cur_param * 10 + c - 48; } else { /* add parsed parameter */ this.esc_params[this.esc_params.length] = this.cur_param; this.cur_param = 0; if (c == 59) // ; break; this.state = TTY_STATE_NORM; // console.log("term: csi=" + this.esc_params + " cmd="+c); switch(c) { case 65: // 'A' up n = this.esc_params[0]; if (n < 1) n = 1; this.y -= n; if (this.y < 0) this.y = 0; break; case 66: // 'B' down n = this.esc_params[0]; if (n < 1) n = 1; this.y += n; if (this.y >= this.h) this.y = this.h - 1; break; case 67: // 'C' right n = this.esc_params[0]; if (n < 1) n = 1; this.x += n; if (this.x >= this.w - 1) this.x = this.w - 1; break; case 68: // 'D' left n = this.esc_params[0]; if (n < 1) n = 1; this.x -= n; if (this.x < 0) this.x = 0; break; case 72: // 'H' goto xy { var x1, y1; y1 = this.esc_params[0] - 1; if (this.esc_params.length >= 2) x1 = this.esc_params[1] - 1; else x1 = 0; if (y1 < 0) y1 = 0; else if (y1 >= this.h) y1 = this.h - 1; if (x1 < 0) x1 = 0; else if (x1 >= this.w) x1 = this.w - 1; this.x = x1; this.y = y1; } break; case 74: // 'J' erase to end of screen erase_to_eol(this, this.x, this.y); for(j = this.y + 1; j < this.h; j++) erase_to_eol(this, 0, j); break; case 75: // 'K' erase to end of line erase_to_eol(this, this.x, this.y); break; case 109: // 'm': set color csi_colors(this, this.esc_params); break; case 110: // 'n' return the cursor position this.queue_chars("\x1b[" + (this.y + 1) + ";" + (this.x + 1) + "R"); break; default: break; } } break; } } update(this.y); // show the cursor if (ymax >= ymin) this.refresh(ymin, ymax); }; Term.prototype.writeln = function (str) { this.write(str + '\r\n'); }; Term.prototype.keyDownHandler = function (ev) { var str; str=""; switch(ev.keyCode) { case 8: /* backspace */ str = "\x7f"; break; case 9: /* tab */ str = "\x09"; break; case 13: /* enter */ str = "\x0d"; break; case 27: /* escape */ str = "\x1b"; break; case 37: /* left */ str = "\x1b[D"; break; case 39: /* right */ str = "\x1b[C"; break; case 38: /* up */ if (ev.ctrlKey) { this.scroll_disp(-1); } else { str = "\x1b[A"; } break; case 40: /* down */ if (ev.ctrlKey) { this.scroll_disp(1); } else { str = "\x1b[B"; } break; case 46: /* delete */ str = "\x1b[3~"; break; case 45: /* insert */ str = "\x1b[2~"; break; case 36: /* home */ str = "\x1bOH"; break; case 35: /* end */ str = "\x1bOF"; break; case 33: /* page up */ if (ev.ctrlKey) { this.scroll_disp(-(this.h - 1)); } else { str = "\x1b[5~"; } break; case 34: /* page down */ if (ev.ctrlKey) { this.scroll_disp(this.h - 1); } else { str = "\x1b[6~"; } break; default: if (ev.ctrlKey) { /* ctrl + key */ if (ev.keyCode >= 65 && ev.keyCode <= 90) { str = String.fromCharCode(ev.keyCode - 64); } else if (ev.keyCode == 32) { str = String.fromCharCode(0); } } else if ((!this.is_mac && ev.altKey) || (this.is_mac && ev.metaKey)) { /* meta + key (Note: we only send lower case) */ if (ev.keyCode >= 65 && ev.keyCode <= 90) { str = "\x1b" + String.fromCharCode(ev.keyCode + 32); } } break; } // console.log("keydown: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey); if (str) { if (ev.stopPropagation) ev.stopPropagation(); if (ev.preventDefault) ev.preventDefault(); this.show_cursor(); this.key_rep_state = 1; this.key_rep_str = str; this.handler(str); return false; } else { this.key_rep_state = 0; return true; } }; Term.prototype.keyPressHandler = function (ev) { var str, char_code; if (ev.stopPropagation) ev.stopPropagation(); if (ev.preventDefault) ev.preventDefault(); str=""; if (!("charCode" in ev)) { /* on Opera charCode is not defined and keypress is sent for system keys. Moreover, only keupress is repeated which is a problem for system keys. */ char_code = ev.keyCode; if (this.key_rep_state == 1) { this.key_rep_state = 2; return false; } else if (this.key_rep_state == 2) { /* repetition */ this.show_cursor(); this.handler(this.key_rep_str); return false; } } else { char_code = ev.charCode; } if (char_code != 0) { if (!ev.ctrlKey && ((!this.is_mac && !ev.altKey) || (this.is_mac && !ev.metaKey))) { str = String.fromCharCode(char_code); } } // console.log("keypress: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey); if (str) { this.show_cursor(); this.handler(str); return false; } else { return true; } }; /* output queue to send back asynchronous responses */ Term.prototype.queue_chars = function (str) { this.output_queue += str; if (this.output_queue) setTimeout(this.outputHandler.bind(this), 0); }; Term.prototype.outputHandler = function () { if (this.output_queue) { this.handler(this.output_queue); this.output_queue = ""; } };
ubercomp/jslm32
third_party/bellard/term.js
JavaScript
lgpl-2.1
18,674
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qrceditor.h" #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mw; mw.show(); return app.exec(); }
gidlbn/dlbn_02
src/shared/qrceditor/test/main.cpp
C++
lgpl-2.1
1,402
/*- * Copyright (c) * * 2012-2014, Facultad Politécnica, Universidad Nacional de Asunción. * 2012-2014, Facultad de Ciencias Médicas, Universidad Nacional de Asunción. * 2012-2013, Centro Nacional de Computación, Universidad Nacional de Asunción. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package py.una.pol.karaku.services.server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import py.una.pol.karaku.security.KarakuUser; import py.una.pol.karaku.security.KarakuUserService; /** * Clase que provee autenticación para usuarios. * * <p> * Esta pensada para ser usada con un * {@link org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint} * , pero aún así y al heredar de * {@link AbstractUserDetailsAuthenticationProvider} provee un mecanismo para * autenticar cualquier mecanismo basado en Usuario y Password. * </p> * <p> * Se basa en {@link KarakuUserService} para autenticar el usuario y luego para * obtener los permisos, esto se hace en dos fases, la primera es * {@link #retrieveUser(String, UsernamePasswordAuthenticationToken)} donde se * autentica el usuario y se autoriza el acceso a expresiones como * 'isAuthenticated()' y luego en * {@link #additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)} * se cargan los permisos necesarios para que pueda navegar. * </p> * * @author Arturo Volpe * @since 2.2 * @version 1.0 Aug 6, 2013 * @see UserDetails * */ public class KarakuWSAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider { @Autowired private KarakuUserService userService; @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) { userService.loadAuthorization(userDetails); } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) { if (userService.checkAuthenthicationByUID(username, authentication .getCredentials().toString())) { KarakuUser user = new KarakuUser(); user.setUserName(username); return user; } throw new UsernameNotFoundException(username); } }
fpuna-cia/karaku
src/main/java/py/una/pol/karaku/services/server/KarakuWSAuthenticationProvider.java
Java
lgpl-2.1
3,356
// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // set a few elements in a chunk sparse matrix and test for iterator // inequality #include "../tests.h" #include <deal.II/lac/chunk_sparse_matrix.h> #include <fstream> #include <iomanip> void test (const unsigned int chunk_size) { deallog << "Chunk size = " << chunk_size << std::endl; ChunkSparsityPattern sp (5,5,3,chunk_size); for (unsigned int i=0; i<5; ++i) for (unsigned int j=0; j<5; ++j) if ((i+2*j+1) % 3 == 0) sp.add (i,j); sp.compress (); ChunkSparseMatrix<double> m(sp); // first set a few entries for (unsigned int i=0; i<m.m(); ++i) for (unsigned int j=0; j<m.n(); ++j) if ((i+2*j+1) % 3 == 0) m.set (i,j, i*j*.5+.5); // then extract the elements (note that // some may be zero or even outside the // matrix AssertDimension(m.end()-m.begin(), m.n_nonzero_elements()); for (unsigned int i=0; i<m.m(); ++i) { deallog << "row " << i << ": "; AssertDimension(m.end(i)-m.begin(i), m.get_sparsity_pattern().row_length(i)); for (ChunkSparseMatrix<double>::const_iterator it = m.begin(i); it != m.end(i); ++it) { deallog << " done " << (it-m.begin(i)) << ", left " << (it-m.end(i)); } deallog << std::endl; } } int main () { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); try { const unsigned int chunk_sizes[] = { 1, 2, 4, 5, 7 }; for (unsigned int i=0; i<sizeof(chunk_sizes)/sizeof(chunk_sizes[0]); ++i) test (chunk_sizes[i]); } catch (std::exception &exc) { deallog << std::endl << std::endl << "----------------------------------------------------" << std::endl; deallog << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { deallog << std::endl << std::endl << "----------------------------------------------------" << std::endl; deallog << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; }; }
flow123d/dealii
tests/bits/chunk_sparse_matrix_14.cc
C++
lgpl-2.1
3,098
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.ui.dialogs.history.diff; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.history.CmsHistoryResourceHandler; import org.opencms.file.types.CmsResourceTypeImage; import org.opencms.gwt.shared.CmsHistoryResourceBean; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.util.CmsRequestUtil; import org.opencms.workplace.comparison.CmsHistoryListUtil; import com.google.common.base.Optional; import com.vaadin.server.ExternalResource; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Image; import com.vaadin.ui.Panel; /** * Displays two image versions side by side, scaled.<p> */ public class CmsImageDiff implements I_CmsDiffProvider { /** * @see org.opencms.ui.dialogs.history.diff.I_CmsDiffProvider#diff(org.opencms.file.CmsObject, org.opencms.gwt.shared.CmsHistoryResourceBean, org.opencms.gwt.shared.CmsHistoryResourceBean) */ public Optional<Component> diff(CmsObject cms, CmsHistoryResourceBean v1, CmsHistoryResourceBean v2) throws CmsException { CmsResource r1 = A_CmsAttributeDiff.readResource(cms, v1); if (OpenCms.getResourceManager().matchResourceType(CmsResourceTypeImage.getStaticTypeName(), r1.getTypeId())) { HorizontalLayout hl = new HorizontalLayout(); hl.setSpacing(true); String v1Param = v1.getVersion().getVersionNumber() != null ? "" + v1.getVersion().getVersionNumber() : "" + CmsHistoryResourceHandler.PROJECT_OFFLINE_VERSION; String v2Param = v2.getVersion().getVersionNumber() != null ? "" + v2.getVersion().getVersionNumber() : "" + CmsHistoryResourceHandler.PROJECT_OFFLINE_VERSION; String link1 = OpenCms.getLinkManager().substituteLinkForUnknownTarget( cms, CmsHistoryListUtil.getHistoryLink(cms, v1.getStructureId(), v1Param)); String link2 = OpenCms.getLinkManager().substituteLinkForUnknownTarget( cms, CmsHistoryListUtil.getHistoryLink(cms, v2.getStructureId(), v2Param)); int scaleWidth = 400; int scaleHeight = (2 * scaleWidth) / 3; final String scaleParams = "w:" + scaleWidth + ",h:" + scaleHeight + ",t:1"; // scale type 1 for thumbnails (no enlargement) link1 = CmsRequestUtil.appendParameter(link1, "__scale", scaleParams); link2 = CmsRequestUtil.appendParameter(link2, "__scale", scaleParams); Image img1 = new Image("", new ExternalResource(link1)); Image img2 = new Image("", new ExternalResource(link2)); for (Image img : new Image[] {img1, img2}) { img.setWidth("" + scaleWidth + "px"); } img1.setCaption("V1"); img2.setCaption("V2"); hl.addComponent(img1); hl.addComponent(img2); Panel result = new Panel("Image comparison"); hl.setMargin(true); result.setContent(hl); return Optional.fromNullable((Component)result); } else { return Optional.absent(); } } }
ggiudetti/opencms-core
src/org/opencms/ui/dialogs/history/diff/CmsImageDiff.java
Java
lgpl-2.1
4,356
#region Disclaimer / License // Copyright (C) 2015, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #endregion using System; using System.Collections.Generic; using System.IO; using Duplicati.Library.Interface; using SharpCompress.Common; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Writers; using SharpCompress.Writers.Zip; using SharpCompress.Readers; using System.Linq; namespace Duplicati.Library.Compression { /// <summary> /// An abstraction of a zip archive as a FileArchive, based on SharpCompress. /// Please note, duplicati does not require both Read & Write access at the same time so this has not been implemented /// </summary> public class FileArchiveZip : ICompression { /// <summary> /// The commandline option for toggling the compression level /// </summary> private const string COMPRESSION_LEVEL_OPTION = "zip-compression-level"; /// <summary> /// The old commandline option for toggling the compression level /// </summary> private const string COMPRESSION_LEVEL_OPTION_ALIAS = "compression-level"; /// <summary> /// The commandline option for toggling the compression method /// </summary> private const string COMPRESSION_METHOD_OPTION = "zip-compression-method"; /// <summary> /// The commandline option for toggling the zip64 support /// </summary> private const string COMPRESSION_ZIP64_OPTION = "zip-compression-zip64"; /// <summary> /// The default compression level /// </summary> private const SharpCompress.Compressors.Deflate.CompressionLevel DEFAULT_COMPRESSION_LEVEL = SharpCompress.Compressors.Deflate.CompressionLevel.Level9; /// <summary> /// The default compression method /// </summary> private const CompressionType DEFAULT_COMPRESSION_METHOD = CompressionType.Deflate; /// <summary> /// The default setting for the zip64 support /// </summary> private const bool DEFAULT_ZIP64 = false; /// <summary> /// Taken from SharpCompress ZipCentralDirectorEntry.cs /// </summary> private const int CENTRAL_HEADER_ENTRY_SIZE = 8 + 2 + 2 + 4 + 4 + 4 + 4 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 4; /// <summary> /// The size of the extended zip64 header /// </summary> private const int CENTRAL_HEADER_ENTRY_SIZE_ZIP64_EXTRA = 2 + 2 + 8 + 8 + 8 + 4; /// <summary> /// This property indicates that this current instance should write to a file /// </summary> private bool m_isWriting; /// <summary> /// Gets the number of bytes expected to be written after the stream is disposed /// </summary> private long m_flushBufferSize = 0; /// <summary> /// The ZipArchive instance used when reading archives /// </summary> private IArchive m_archive; /// <summary> /// The stream used to either read or write /// </summary> private Stream m_stream; /// <summary> /// Lookup table for faster access to entries based on their name. /// </summary> private Dictionary<string, IEntry> m_entryDict; /// <summary> /// The writer instance used when creating archives /// </summary> private IWriter m_writer; /// <summary> /// A flag indicating if we are using the fail-over reader interface /// </summary> public bool m_using_reader = false; /// <summary> /// The compression level applied when the hint does not indicate incompressible /// </summary> private SharpCompress.Compressors.Deflate.CompressionLevel m_defaultCompressionLevel; /// <summary> /// The compression level applied when the hint does not indicate incompressible /// </summary> private CompressionType m_compressionType; /// <summary> /// The name of the file being read /// </summary> private string m_filename; /// <summary> /// A flag indicating if zip64 is in use /// </summary> private bool m_usingZip64; /// <summary> /// Default constructor, used to read file extension and supported commands /// </summary> public FileArchiveZip() { } public IArchive Archive { get { if (m_stream == null) m_stream = new System.IO.FileStream(m_filename, FileMode.Open, FileAccess.Read, FileShare.Read); if (m_archive == null) m_archive = ArchiveFactory.Open(m_stream); return m_archive; } } public void SwitchToReader() { if (!m_using_reader) { // Close what we have using (m_stream) using (m_archive) { } m_using_reader = true; } } public Stream GetStreamFromReader(IEntry entry) { Stream fs = null; SharpCompress.Readers.Zip.ZipReader rd = null; try { fs = new System.IO.FileStream(m_filename, FileMode.Open, FileAccess.Read, FileShare.Read); rd = SharpCompress.Readers.Zip.ZipReader.Open(fs); while (rd.MoveToNextEntry()) if (entry.Key == rd.Entry.Key) return new StreamWrapper(rd.OpenEntryStream(), stream => { rd.Dispose(); fs.Dispose(); }); throw new Exception(string.Format("Stream not found: {0}", entry.Key)); } catch { if (rd != null) rd.Dispose(); if (fs != null) fs.Dispose(); throw; } } /// <summary> /// Constructs a new zip instance. /// If the file exists and has a non-zero length we read it, /// otherwise we create a new archive. /// </summary> /// <param name="filename">The name of the file to read or write</param> /// <param name="options">The options passed on the commandline</param> public FileArchiveZip(string filename, Dictionary<string, string> options) { if (string.IsNullOrEmpty(filename) && filename.Trim().Length == 0) throw new ArgumentException("filename"); if (File.Exists(filename) && new FileInfo(filename).Length > 0) { m_isWriting = false; m_filename = filename; } else { var compression = new ZipWriterOptions(CompressionType.Deflate); compression.CompressionType = DEFAULT_COMPRESSION_METHOD; compression.DeflateCompressionLevel = DEFAULT_COMPRESSION_LEVEL; m_usingZip64 = compression.UseZip64 = options.ContainsKey(COMPRESSION_ZIP64_OPTION) ? Duplicati.Library.Utility.Utility.ParseBoolOption(options, COMPRESSION_ZIP64_OPTION) : DEFAULT_ZIP64; string cpmethod; CompressionType tmptype; if (options.TryGetValue(COMPRESSION_METHOD_OPTION, out cpmethod) && Enum.TryParse<SharpCompress.Common.CompressionType>(cpmethod, true, out tmptype)) compression.CompressionType = tmptype; string cplvl; int tmplvl; if (options.TryGetValue(COMPRESSION_LEVEL_OPTION, out cplvl) && int.TryParse(cplvl, out tmplvl)) compression.DeflateCompressionLevel = (SharpCompress.Compressors.Deflate.CompressionLevel)Math.Max(Math.Min(9, tmplvl), 0); else if (options.TryGetValue(COMPRESSION_LEVEL_OPTION_ALIAS, out cplvl) && int.TryParse(cplvl, out tmplvl)) compression.DeflateCompressionLevel = (SharpCompress.Compressors.Deflate.CompressionLevel)Math.Max(Math.Min(9, tmplvl), 0); m_defaultCompressionLevel = compression.DeflateCompressionLevel; m_compressionType = compression.CompressionType; m_isWriting = true; m_stream = new System.IO.FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read); m_writer = WriterFactory.Open(m_stream, ArchiveType.Zip, compression); //Size of endheader, taken from SharpCompress ZipWriter m_flushBufferSize = 8 + 2 + 2 + 4 + 4 + 2 + 0; } } #region IFileArchive Members /// <summary> /// Gets the filename extension used by the compression module /// </summary> public string FilenameExtension { get { return "zip"; } } /// <summary> /// Gets a friendly name for the compression module /// </summary> public string DisplayName { get { return Strings.FileArchiveZip.DisplayName; } } /// <summary> /// Gets a description of the compression module /// </summary> public string Description { get { return Strings.FileArchiveZip.Description; } } /// <summary> /// Gets a list of commands supported by the compression module /// </summary> public IList<ICommandLineArgument> SupportedCommands { get { return new List<ICommandLineArgument>(new ICommandLineArgument[] { new CommandLineArgument(COMPRESSION_LEVEL_OPTION, CommandLineArgument.ArgumentType.Enumeration, Strings.FileArchiveZip.CompressionlevelShort, Strings.FileArchiveZip.CompressionlevelLong, DEFAULT_COMPRESSION_LEVEL.ToString(), null, new string[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}), new CommandLineArgument(COMPRESSION_LEVEL_OPTION_ALIAS, CommandLineArgument.ArgumentType.Enumeration, Strings.FileArchiveZip.CompressionlevelShort, Strings.FileArchiveZip.CompressionlevelLong, DEFAULT_COMPRESSION_LEVEL.ToString(), null, new string[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, Strings.FileArchiveZip.CompressionlevelDeprecated(COMPRESSION_LEVEL_OPTION)), new CommandLineArgument(COMPRESSION_METHOD_OPTION, CommandLineArgument.ArgumentType.Enumeration, Strings.FileArchiveZip.CompressionmethodShort, Strings.FileArchiveZip.CompressionmethodLong(COMPRESSION_LEVEL_OPTION), DEFAULT_COMPRESSION_METHOD.ToString(), null, Enum.GetNames(typeof(CompressionType))), new CommandLineArgument(COMPRESSION_ZIP64_OPTION, CommandLineArgument.ArgumentType.Boolean, Strings.FileArchiveZip.Compressionzip64Short, Strings.FileArchiveZip.Compressionzip64Long, DEFAULT_ZIP64.ToString()) }); } } /// <summary> /// Returns a list of files matching the given prefix /// </summary> /// <param name="prefix">The prefix to match</param> /// <returns>A list of files matching the prefix</returns> public string[] ListFiles(string prefix) { return ListFilesWithSize(prefix).Select(x => x.Key).ToArray(); } /// <summary> /// Returns a list of files matching the given prefix /// </summary> /// <param name="prefix">The prefix to match</param> /// <returns>A list of files matching the prefix</returns> public IEnumerable<KeyValuePair<string, long>> ListFilesWithSize(string prefix) { LoadEntryTable(); var q = m_entryDict.Values.AsEnumerable(); if (!string.IsNullOrEmpty(prefix)) q = q.Where(x => x.Key.StartsWith(prefix, Duplicati.Library.Utility.Utility.ClientFilenameStringComparision) || x.Key.Replace('\\', '/').StartsWith(prefix, Duplicati.Library.Utility.Utility.ClientFilenameStringComparision) ); return q.Select(x => new KeyValuePair<string, long>(x.Key, x.Size)).ToArray(); } /// <summary> /// Opens an file for reading /// </summary> /// <param name="file">The name of the file to open</param> /// <returns>A stream with the file contents</returns> public Stream OpenRead(string file) { if (m_isWriting) throw new InvalidOperationException("Cannot read while writing"); var ze = GetEntry(file); if (ze == null) return null; if (ze is IArchiveEntry) return ((IArchiveEntry)ze).OpenEntryStream(); else if (ze is SharpCompress.Common.Zip.ZipEntry) return GetStreamFromReader(ze); throw new Exception(string.Format("Unexpected result: {0}", ze.GetType().FullName)); } /// <summary> /// Helper method to load the entry table /// </summary> private void LoadEntryTable() { if (m_entryDict == null) { try { var d = new Dictionary<string, IEntry>(Duplicati.Library.Utility.Utility.ClientFilenameStringComparer); foreach (var en in Archive.Entries) d[en.Key] = en; m_entryDict = d; } catch (Exception ex) { // If we get an exception here, it may be caused by the Central Header // being defect, so we switch to the less efficient reader interface if (m_using_reader) throw; Logging.Log.WriteMessage("Zip archive appears to have a broken Central Record Header, switching to stream mode", Logging.LogMessageType.Warning, ex); SwitchToReader(); var d = new Dictionary<string, IEntry>(Duplicati.Library.Utility.Utility.ClientFilenameStringComparer); try { using (var fs = new System.IO.FileStream(m_filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var rd = SharpCompress.Readers.Zip.ZipReader.Open(fs, new ReaderOptions() { LookForHeader = false })) while (rd.MoveToNextEntry()) { d[rd.Entry.Key] = rd.Entry; // Some streams require this // to correctly find the next entry using (rd.OpenEntryStream()) { } } } catch (Exception ex2) { // If we have zero files, or just a manifest, don't bother if (d.Count < 2) throw; Logging.Log.WriteMessage(string.Format("Zip archive appears to have broken records, returning the {0} records that could be recovered", d.Count), Logging.LogMessageType.Warning, ex2); } m_entryDict = d; } } } /// <summary> /// Internal function that returns a ZipEntry for a filename, or null if no such file exists /// </summary> /// <param name="file">The name of the file to find</param> /// <returns>The ZipEntry for the file or null if no such file was found</returns> private IEntry GetEntry(string file) { if (m_isWriting) throw new InvalidOperationException("Cannot read while writing"); LoadEntryTable(); IEntry e; if (m_entryDict.TryGetValue(file, out e)) return e; if (m_entryDict.TryGetValue(file.Replace('/', '\\'), out e)) return e; return null; } /// <summary> /// Creates a file in the archive and returns a writeable stream /// </summary> /// <param name="file">The name of the file to create</param> /// <param name="hint">A hint to the compressor as to how compressible the file data is</param> /// <param name="lastWrite">The time the file was last written</param> /// <returns>A writeable stream for the file contents</returns> public virtual Stream CreateFile(string file, CompressionHint hint, DateTime lastWrite) { if (!m_isWriting) throw new InvalidOperationException("Cannot write while reading"); m_flushBufferSize += CENTRAL_HEADER_ENTRY_SIZE + System.Text.Encoding.UTF8.GetByteCount(file); if (m_usingZip64) m_flushBufferSize += CENTRAL_HEADER_ENTRY_SIZE_ZIP64_EXTRA; return ((ZipWriter)m_writer).WriteToStream(file, new ZipWriterEntryOptions() { DeflateCompressionLevel = hint == CompressionHint.Noncompressible ? SharpCompress.Compressors.Deflate.CompressionLevel.None : m_defaultCompressionLevel, ModificationDateTime = lastWrite, CompressionType = m_compressionType }); } /// <summary> /// Returns a value that indicates if the file exists /// </summary> /// <param name="file">The name of the file to test existence for</param> /// <returns>True if the file exists, false otherwise</returns> public bool FileExists(string file) { if (m_isWriting) throw new InvalidOperationException("Cannot read while writing"); return GetEntry(file) != null; } /// <summary> /// Gets the current size of the archive /// </summary> public long Size { get { return m_isWriting ? m_stream.Length : Archive.TotalSize; } } /// <summary> /// The size of the current unflushed buffer /// </summary> public long FlushBufferSize { get { return m_flushBufferSize; } } /// <summary> /// Gets the last write time for a file /// </summary> /// <param name="file">The name of the file to query</param> /// <returns>The last write time for the file</returns> public DateTime GetLastWriteTime(string file) { IEntry entry = GetEntry(file); if (entry != null) { if (entry.LastModifiedTime.HasValue) return entry.LastModifiedTime.Value; else return DateTime.MinValue; } throw new FileNotFoundException(Strings.FileArchiveZip.FileNotFoundError(file)); } #endregion #region IDisposable Members public void Dispose() { if (m_archive != null) m_archive.Dispose(); m_archive = null; if (m_writer != null) m_writer.Dispose(); m_writer = null; if (m_stream != null) m_stream.Dispose(); m_stream = null; } #endregion } }
gerco/duplicati
Duplicati/Library/Compression/FileArchiveZip.cs
C#
lgpl-2.1
21,007
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: searchstatslib.php 57965 2016-03-17 20:04:49Z jonnybradley $ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } /** * */ class SearchStatsLib extends TikiLib { function clear_search_stats() { $query = "delete from tiki_search_stats"; $result = $this->query($query, array()); } function register_term_hit($term) { $term = trim($term); $table = $this->table('tiki_search_stats'); $table->insertOrUpdate( array( 'hits' => $table->increment(1), ), array( 'term' => $term, 'hits' => 1, ) ); } /** * @param $offset * @param $maxRecords * @param $sort_mode * @param $find * @return array */ function list_search_stats($offset, $maxRecords, $sort_mode, $find) { if ($find) { $mid = " where (`term` like ?)"; $bindvars = array("%$find%"); } else { $mid = ""; $bindvars = array(); } $query = "select * from `tiki_search_stats` $mid order by " . $this->convertSortMode($sort_mode); $query_cant = "select count(*) from `tiki_search_stats` $mid"; $result = $this->query($query, $bindvars, $maxRecords, $offset); $cant = $this->getOne($query_cant, $bindvars); $ret = array(); while ($res = $result->fetchRow(DB_FETCHMODE_ASSOC)) { $ret[] = $res; } $retval = array(); $retval["data"] = $ret; $retval["cant"] = $cant; return $retval; } }
lorddavy/TikiWiki-Improvement-Project
lib/search/searchstatslib.php
PHP
lgpl-2.1
1,759
#!/usr/bin/env python3 import os, sys, glob, pickle, subprocess sys.path.insert(0, os.path.dirname(__file__)) from clang import cindex sys.path = sys.path[1:] def configure_libclang(): llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm'] try: libdir = subprocess.check_output(['llvm-config', '--libdir']).decode('utf-8').strip() llvm_libdirs.insert(0, libdir) except OSError: pass for d in llvm_libdirs: if not os.path.exists(d): continue files = glob.glob(os.path.join(d, 'libclang.so*')) if len(files) != 0: cindex.Config.set_library_file(files[0]) return class Call: def __init__(self, cursor, decl): self.ident = cursor.displayname.decode('utf-8') self.filename = cursor.location.file.name.decode('utf-8') ex = cursor.extent self.start_line = ex.start.line self.start_column = ex.start.column self.end_line = ex.end.line self.end_column = ex.end.column self.decl_filename = decl.location.file.name.decode('utf-8') class Definition: def __init__(self, cursor): self.ident = cursor.spelling.decode('utf-8') self.display = cursor.displayname.decode('utf-8') self.filename = cursor.location.file.name.decode('utf-8') ex = cursor.extent self.start_line = ex.start.line self.start_column = ex.start.column self.end_line = ex.end.line self.end_column = ex.end.column def process_diagnostics(tu): diagnostics = tu.diagnostics haserr = False for d in diagnostics: sys.stderr.write('{0}\n'.format(d.format.decode('utf-8'))) if d.severity > cindex.Diagnostic.Warning: haserr = True if haserr: sys.exit(1) def walk_cursors(tu, files): proc = list(tu.cursor.get_children()) while len(proc) > 0: cursor = proc[0] proc = proc[1:] if cursor.location.file is None: continue fname = cursor.location.file.name.decode('utf-8') if fname in files: yield cursor proc += list(cursor.get_children()) def newer(a, b): try: return os.stat(a).st_mtime > os.stat(b).st_mtime except: return True def scan_libgit2_glib(cflags, files, git2dir): files = [os.path.abspath(f) for f in files] dname = os.path.dirname(__file__) allcalls = {} l = 0 if not os.getenv('SILENT'): sys.stderr.write('\n') i = 0 for f in files: if not os.getenv('SILENT'): name = os.path.basename(f) if len(name) > l: l = len(name) perc = int((i / len(files)) * 100) sys.stderr.write('[{0: >3}%] Processing ... {1}{2}\r'.format(perc, name, ' ' * (l - len(name)))) i += 1 astf = os.path.join(dname, '.' + os.path.basename(f) + '.cache') if not newer(f, astf): with open(astf, 'rb') as fo: calls = pickle.load(fo) else: tu = cindex.TranslationUnit.from_source(f, cflags) process_diagnostics(tu) calls = {} for cursor in walk_cursors(tu, files): if cursor.kind == cindex.CursorKind.CALL_EXPR or \ cursor.kind == cindex.CursorKind.DECL_REF_EXPR: cdecl = cursor.get_referenced() if cdecl.kind != cindex.CursorKind.FUNCTION_DECL: continue if (not cdecl is None) and (not cdecl.location.file is None): fdefname = cdecl.location.file.name.decode('utf-8') if fdefname.startswith(git2dir): call = Call(cursor, cdecl) if call.ident in calls: calls[call.ident].append(call) else: calls[call.ident] = [call] with open(astf, 'wb') as fo: pickle.dump(calls, fo) for k in calls: if k in allcalls: allcalls[k] += calls[k] else: allcalls[k] = list(calls[k]) if not os.getenv('SILENT'): sys.stderr.write('\r[100%] Processing ... done{0}\n'.format(' ' * (l - 4))) return allcalls def scan_libgit2(cflags, git2dir): tu = cindex.TranslationUnit.from_source(git2dir + '.h', cflags) process_diagnostics(tu) headers = glob.glob(os.path.join(git2dir, '*.h')) defs = {} objapi = ['lookup', 'lookup_prefix', 'free', 'id', 'owner'] objderiv = ['commit', 'tree', 'tag', 'blob'] ignore = set() for deriv in objderiv: for api in objapi: ignore.add('git_' + deriv + '_' + api) for cursor in walk_cursors(tu, headers): if cursor.kind == cindex.CursorKind.FUNCTION_DECL: deff = Definition(cursor) if not deff.ident in ignore: defs[deff.ident] = deff return defs configure_libclang() pos = sys.argv.index('--') cflags = sys.argv[1:pos] files = sys.argv[pos+1:] incdir = os.getenv('LIBGIT2_INCLUDE_DIR') defs = scan_libgit2(cflags, incdir) calls = scan_libgit2_glib(cflags, files, incdir) notused = {} perfile = {} nperfile = {} for d in defs: o = defs[d] if not d in calls: notused[d] = defs[d] if not o.filename in nperfile: nperfile[o.filename] = [o] else: nperfile[o.filename].append(o) if not o.filename in perfile: perfile[o.filename] = [o] else: perfile[o.filename].append(o) ss = [notused[f] for f in notused] ss.sort(key=lambda x: '{0} {1}'.format(os.path.basename(x.filename), x.ident)) lastf = None keys = list(perfile.keys()) keys.sort() for filename in keys: b = os.path.basename(filename) f = perfile[filename] n_perfile = len(f) if filename in nperfile: n_nperfile = len(nperfile[filename]) else: n_nperfile = 0 perc = int(((n_perfile - n_nperfile) / n_perfile) * 100) print('\n File {0}, coverage {1}% ({2} out of {3}):'.format(b, perc, n_perfile - n_nperfile, n_perfile)) cp = list(f) cp.sort(key=lambda x: "{0} {1}".format(not x.ident in calls, x.ident)) for d in cp: if d.ident in calls: print(' \033[32m✓ {0}\033[0m'.format(d.display)) else: print(' \033[31m✗ {0}\033[0m'.format(d.display)) perc = int(((len(defs) - len(notused)) / len(defs)) * 100) print('\nTotal coverage: {0}% ({1} functions out of {2} are being called)\n'.format(perc, len(defs) - len(notused), len(defs))) # vi:ts=4:et
chergert/libgit2-glib
tools/coverage.py
Python
lgpl-2.1
6,733
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "customwizardpage.h" #include "customwizardparameters.h" #include <utils/pathchooser.h> #include <utils/qtcassert.h> #include <QtCore/QRegExp> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtGui/QWizardPage> #include <QtGui/QFormLayout> #include <QtGui/QVBoxLayout> #include <QtGui/QLineEdit> #include <QtGui/QLabel> #include <QtGui/QRegExpValidator> #include <QtGui/QComboBox> #include <QtGui/QTextEdit> #include <QtGui/QSpacerItem> enum { debug = 0 }; namespace ProjectExplorer { namespace Internal { // ----------- TextFieldComboBox TextFieldComboBox::TextFieldComboBox(QWidget *parent) : QComboBox(parent) { setEditable(false); connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(slotCurrentIndexChanged(int))); } QString TextFieldComboBox::text() const { return valueAt(currentIndex()); } void TextFieldComboBox::setText(const QString &s) { const int index = findData(QVariant(s), Qt::UserRole); if (index != -1 && index != currentIndex()) setCurrentIndex(index); } void TextFieldComboBox::slotCurrentIndexChanged(int i) { emit text4Changed(valueAt(i)); } void TextFieldComboBox::setItems(const QStringList &displayTexts, const QStringList &values) { QTC_ASSERT(displayTexts.size() == values.size(), return) clear(); addItems(displayTexts); const int count = values.count(); for (int i = 0; i < count; i++) setItemData(i, QVariant(values.at(i)), Qt::UserRole); } QString TextFieldComboBox::valueAt(int i) const { return i >= 0 && i < count() ? itemData(i, Qt::UserRole).toString() : QString(); } // -------------- TextCheckBox TextFieldCheckBox::TextFieldCheckBox(const QString &text, QWidget *parent) : QCheckBox(text, parent), m_trueText(QLatin1String("true")), m_falseText(QLatin1String("false")) { connect(this, SIGNAL(stateChanged(int)), this, SLOT(slotStateChanged(int))); } QString TextFieldCheckBox::text() const { return isChecked() ? m_trueText : m_falseText; } void TextFieldCheckBox::setText(const QString &s) { setChecked(s == m_trueText); } void TextFieldCheckBox::slotStateChanged(int cs) { emit textChanged(cs == Qt::Checked ? m_trueText : m_falseText); } // --------------- CustomWizardFieldPage CustomWizardFieldPage::LineEditData::LineEditData(QLineEdit* le, const QString &defText) : lineEdit(le), defaultText(defText) { } CustomWizardFieldPage::TextEditData::TextEditData(QTextEdit* le, const QString &defText) : textEdit(le), defaultText(defText) { } CustomWizardFieldPage::CustomWizardFieldPage(const QSharedPointer<CustomWizardContext> &ctx, const QSharedPointer<CustomWizardParameters> &parameters, QWidget *parent) : QWizardPage(parent), m_parameters(parameters), m_context(ctx), m_formLayout(new QFormLayout), m_errorLabel(new QLabel) { QVBoxLayout *vLayout = new QVBoxLayout; m_formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow); if (debug) qDebug() << Q_FUNC_INFO << parameters->fields.size(); foreach(const CustomWizardField &f, parameters->fields) addField(f); vLayout->addLayout(m_formLayout); m_errorLabel->setVisible(false); m_errorLabel->setStyleSheet(QLatin1String("background: red")); vLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); vLayout->addWidget(m_errorLabel); setLayout(vLayout); } CustomWizardFieldPage::~CustomWizardFieldPage() { } void CustomWizardFieldPage::addRow(const QString &name, QWidget *w) { m_formLayout->addRow(name, w); } void CustomWizardFieldPage::showError(const QString &m) { m_errorLabel->setText(m); m_errorLabel->setVisible(true); } void CustomWizardFieldPage::clearError() { m_errorLabel->setText(QString()); m_errorLabel->setVisible(false); } // Create widget a control based on the control attributes map // and register it with the QWizard. void CustomWizardFieldPage::addField(const CustomWizardField &field)\ { // Register field, indicate mandatory by '*' (only when registering) QString fieldName = field.name; if (field.mandatory) fieldName += QLatin1Char('*'); bool spansRow = false; // Check known classes: QComboBox const QString className = field.controlAttributes.value(QLatin1String("class")); QWidget *fieldWidget = 0; if (className == QLatin1String("QComboBox")) { fieldWidget = registerComboBox(fieldName, field); } else if (className == QLatin1String("QTextEdit")) { fieldWidget = registerTextEdit(fieldName, field); } else if (className == QLatin1String("Utils::PathChooser")) { fieldWidget = registerPathChooser(fieldName, field); } else if (className == QLatin1String("QCheckBox")) { fieldWidget = registerCheckBox(fieldName, field.description, field); spansRow = true; // Do not create a label for the checkbox. } else { fieldWidget = registerLineEdit(fieldName, field); } if (spansRow) { m_formLayout->addRow(fieldWidget); } else { addRow(field.description, fieldWidget); } } // Return the list of values and display texts for combo static void comboChoices(const CustomWizardField::ControlAttributeMap &controlAttributes, QStringList *values, QStringList *displayTexts) { typedef CustomWizardField::ControlAttributeMap::ConstIterator AttribMapConstIt; values->clear(); displayTexts->clear(); // Pre 2.2 Legacy: "combochoices" attribute with a comma-separated list, for // display == value. const AttribMapConstIt attribConstEnd = controlAttributes.constEnd(); const AttribMapConstIt choicesIt = controlAttributes.constFind(QLatin1String("combochoices")); if (choicesIt != attribConstEnd) { const QString &choices = choicesIt.value(); if (!choices.isEmpty()) *values = *displayTexts = choices.split(QLatin1Char(',')); return; } // From 2.2 on: Separate lists of value and text. Add all values found. for (int i = 0; ; i++) { const QString valueKey = CustomWizardField::comboEntryValueKey(i); const AttribMapConstIt valueIt = controlAttributes.constFind(valueKey); if (valueIt == attribConstEnd) break; values->push_back(valueIt.value()); const QString textKey = CustomWizardField::comboEntryTextKey(i); displayTexts->push_back(controlAttributes.value(textKey)); } } QWidget *CustomWizardFieldPage::registerComboBox(const QString &fieldName, const CustomWizardField &field) { TextFieldComboBox *combo = new TextFieldComboBox; do { // Set up items and current index QStringList values; QStringList displayTexts; comboChoices(field.controlAttributes, &values, &displayTexts); combo->setItems(displayTexts, values); bool ok; const QString currentIndexS = field.controlAttributes.value(QLatin1String("defaultindex")); if (currentIndexS.isEmpty()) break; const int currentIndex = currentIndexS.toInt(&ok); if (!ok || currentIndex < 0 || currentIndex >= combo->count()) break; combo->setCurrentIndex(currentIndex); } while (false); registerField(fieldName, combo, "text", SIGNAL(text4Changed(QString))); return combo; } // QComboBox QWidget *CustomWizardFieldPage::registerTextEdit(const QString &fieldName, const CustomWizardField &field) { QTextEdit *textEdit = new QTextEdit; registerField(fieldName, textEdit, "plainText", SIGNAL(textChanged(QString))); const QString defaultText = field.controlAttributes.value(QLatin1String("defaulttext")); m_textEdits.push_back(TextEditData(textEdit, defaultText)); return textEdit; } // QTextEdit QWidget *CustomWizardFieldPage::registerPathChooser(const QString &fieldName, const CustomWizardField & /*field*/) { Utils::PathChooser *pathChooser = new Utils::PathChooser; registerField(fieldName, pathChooser, "path", SIGNAL(changed(QString))); return pathChooser; } // Utils::PathChooser QWidget *CustomWizardFieldPage::registerCheckBox(const QString &fieldName, const QString &fieldDescription, const CustomWizardField &field) { typedef CustomWizardField::ControlAttributeMap::const_iterator AttributeMapConstIt; TextFieldCheckBox *checkBox = new TextFieldCheckBox(fieldDescription); const bool defaultValue = field.controlAttributes.value(QLatin1String("defaultvalue")) == QLatin1String("true"); checkBox->setChecked(defaultValue); const AttributeMapConstIt trueTextIt = field.controlAttributes.constFind(QLatin1String("truevalue")); if (trueTextIt != field.controlAttributes.constEnd()) // Also set empty texts checkBox->setTrueText(trueTextIt.value()); const AttributeMapConstIt falseTextIt = field.controlAttributes.constFind(QLatin1String("falsevalue")); if (falseTextIt != field.controlAttributes.constEnd()) // Also set empty texts checkBox->setFalseText(falseTextIt.value()); registerField(fieldName, checkBox, "text", SIGNAL(textChanged(QString))); return checkBox; } QWidget *CustomWizardFieldPage::registerLineEdit(const QString &fieldName, const CustomWizardField &field) { QLineEdit *lineEdit = new QLineEdit; const QString validationRegExp = field.controlAttributes.value(QLatin1String("validator")); if (!validationRegExp.isEmpty()) { QRegExp re(validationRegExp); if (re.isValid()) { lineEdit->setValidator(new QRegExpValidator(re, lineEdit)); } else { qWarning("Invalid custom wizard field validator regular expression %s.", qPrintable(validationRegExp)); } } registerField(fieldName, lineEdit, "text", SIGNAL(textEdited(QString))); const QString defaultText = field.controlAttributes.value(QLatin1String("defaulttext")); m_lineEdits.push_back(LineEditData(lineEdit, defaultText)); return lineEdit; } void CustomWizardFieldPage::initializePage() { QWizardPage::initializePage(); clearError(); // Note that the field mechanism will always restore the value // set on it when entering the page, so, there is no point in // trying to preserve user modifications of the text. foreach(const LineEditData &led, m_lineEdits) { if (!led.defaultText.isEmpty()) { QString defaultText = led.defaultText; CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText); led.lineEdit->setText(defaultText); } } foreach(const TextEditData &ted, m_textEdits) { if (!ted.defaultText.isEmpty()) { QString defaultText = ted.defaultText; CustomWizardContext::replaceFields(m_context->baseReplacements, &defaultText); ted.textEdit->setText(defaultText); } } } bool CustomWizardFieldPage::validatePage() { clearError(); // Check line edits with validators foreach(const LineEditData &led, m_lineEdits) { if (const QValidator *val = led.lineEdit->validator()) { int pos = 0; QString text = led.lineEdit->text(); if (val->validate(text, pos) != QValidator::Acceptable) { led.lineEdit->setFocus(); return false; } } } // Any user validation rules -> Check all and display messages with // place holders applied. if (!m_parameters->rules.isEmpty()) { const QMap<QString, QString> values = replacementMap(wizard(), m_context, m_parameters->fields); QString message; if (!CustomWizardValidationRule::validateRules(m_parameters->rules, values, &message)) { showError(message); return false; } } return QWizardPage::validatePage(); } QMap<QString, QString> CustomWizardFieldPage::replacementMap(const QWizard *w, const QSharedPointer<CustomWizardContext> &ctx, const FieldList &f) { QMap<QString, QString> fieldReplacementMap = ctx->baseReplacements; foreach(const Internal::CustomWizardField &field, f) { const QString value = w->field(field.name).toString(); fieldReplacementMap.insert(field.name, value); } // Insert paths for generator scripts. fieldReplacementMap.insert(QLatin1String("Path"), QDir::toNativeSeparators(ctx->path)); fieldReplacementMap.insert(QLatin1String("TargetPath"), QDir::toNativeSeparators(ctx->targetPath)); return fieldReplacementMap; } // --------------- CustomWizardPage CustomWizardPage::CustomWizardPage(const QSharedPointer<CustomWizardContext> &ctx, const QSharedPointer<CustomWizardParameters> &parameters, QWidget *parent) : CustomWizardFieldPage(ctx, parameters, parent), m_pathChooser(new Utils::PathChooser) { addRow(tr("Path:"), m_pathChooser); connect(m_pathChooser, SIGNAL(validChanged()), this, SIGNAL(completeChanged())); } QString CustomWizardPage::path() const { return m_pathChooser->path(); } void CustomWizardPage::setPath(const QString &path) { m_pathChooser->setPath(path); } bool CustomWizardPage::isComplete() const { return m_pathChooser->isValid(); } } // namespace Internal } // namespace ProjectExplorer
yinyunqiao/qtcreator
src/plugins/projectexplorer/customwizard/customwizardpage.cpp
C++
lgpl-2.1
15,232
/**************************************************************************** ** ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebSockets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwebsocketprotocol_p.h" #include <QtCore/QString> #include <QtCore/QSet> #include <QtCore/QtEndian> QT_BEGIN_NAMESPACE /*! \namespace QWebSocketProtocol \inmodule QtWebSockets \brief Contains constants related to the WebSocket standard. */ /*! \enum QWebSocketProtocol::CloseCode \inmodule QtWebSockets The close codes supported by WebSockets V13 \value CloseCodeNormal Normal closure \value CloseCodeGoingAway Going away \value CloseCodeProtocolError Protocol error \value CloseCodeDatatypeNotSupported Unsupported data \value CloseCodeReserved1004 Reserved \value CloseCodeMissingStatusCode No status received \value CloseCodeAbnormalDisconnection Abnormal closure \value CloseCodeWrongDatatype Invalid frame payload data \value CloseCodePolicyViolated Policy violation \value CloseCodeTooMuchData Message too big \value CloseCodeMissingExtension Mandatory extension missing \value CloseCodeBadOperation Internal server error \value CloseCodeTlsHandshakeFailed TLS handshake failed \sa QWebSocket::close() */ /*! \enum QWebSocketProtocol::Version \inmodule QtWebSockets \brief The different defined versions of the WebSocket protocol. For an overview of the differences between the different protocols, see <http://code.google.com/p/pywebsocket/wiki/WebSocketProtocolSpec> \value VersionUnknown Unknown or unspecified version. \value Version0 hixie76: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 & hybi-00: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00. Works with key1, key2 and a key in the payload. Attribute: Sec-WebSocket-Draft value 0. Not supported by QtWebSockets. \value Version4 hybi-04: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-04.txt. Changed handshake: key1, key2, key3 ==> Sec-WebSocket-Key, Sec-WebSocket-Nonce, Sec-WebSocket-Accept Sec-WebSocket-Draft renamed to Sec-WebSocket-Version Sec-WebSocket-Version = 4. Not supported by QtWebSockets. \value Version5 hybi-05: http://tools.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-05.txt. Sec-WebSocket-Version = 5 Removed Sec-WebSocket-Nonce Added Sec-WebSocket-Accept. Not supported by QtWebSockets. \value Version6 Sec-WebSocket-Version = 6. Not supported by QtWebSockets. \value Version7 hybi-07: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07. Sec-WebSocket-Version = 7. Not supported by QtWebSockets. \value Version8 hybi-8, hybi-9, hybi-10, hybi-11 and hybi-12. Status codes 1005 and 1006 are added and all codes are now unsigned Internal error results in 1006. Not supported by QtWebSockets. \value Version13 hybi-13, hybi14, hybi-15, hybi-16, hybi-17 and RFC 6455. Sec-WebSocket-Version = 13 Status code 1004 is now reserved Added 1008, 1009 and 1010 Must support TLS Clarify multiple version support. Supported by QtWebSockets. \value VersionLatest Refers to the latest known version to QtWebSockets. */ /*! \enum QWebSocketProtocol::OpCode \inmodule QtWebSockets The frame opcodes as defined by the WebSockets standard \value OpCodeContinue Continuation frame \value OpCodeText Text frame \value OpCodeBinary Binary frame \value OpCodeReserved3 Reserved \value OpCodeReserved4 Reserved \value OpCodeReserved5 Reserved \value OpCodeReserved6 Reserved \value OpCodeReserved7 Reserved \value OpCodeClose Close frame \value OpCodePing Ping frame \value OpCodePong Pong frame \value OpCodeReservedB Reserved \value OpCodeReservedC Reserved \value OpCodeReservedD Reserved \value OpCodeReservedE Reserved \value OpCodeReservedF Reserved \internal */ /*! \fn QWebSocketProtocol::isOpCodeReserved(OpCode code) Checks if \a code is a valid OpCode \internal */ /*! \fn QWebSocketProtocol::isCloseCodeValid(int closeCode) Checks if \a closeCode is a valid WebSocket close code \internal */ /*! \fn QWebSocketProtocol::currentVersion() Returns the latest version that WebSocket is supporting \internal */ /*! Parses the \a versionString and converts it to a Version value \internal */ QWebSocketProtocol::Version QWebSocketProtocol::versionFromString(const QString &versionString) { bool ok = false; Version version = VersionUnknown; const int ver = versionString.toInt(&ok); QSet<Version> supportedVersions; supportedVersions << Version0 << Version4 << Version5 << Version6 << Version7 << Version8 << Version13; if (Q_LIKELY(ok) && (supportedVersions.contains(static_cast<Version>(ver)))) version = static_cast<Version>(ver); return version; } /*! Mask the \a payload with the given \a maskingKey and stores the result back in \a payload. \internal */ void QWebSocketProtocol::mask(QByteArray *payload, quint32 maskingKey) { Q_ASSERT(payload); mask(payload->data(), payload->size(), maskingKey); } /*! Masks the \a payload of length \a size with the given \a maskingKey and stores the result back in \a payload. \internal */ void QWebSocketProtocol::mask(char *payload, quint64 size, quint32 maskingKey) { Q_ASSERT(payload); const quint8 mask[] = { quint8((maskingKey & 0xFF000000u) >> 24), quint8((maskingKey & 0x00FF0000u) >> 16), quint8((maskingKey & 0x0000FF00u) >> 8), quint8((maskingKey & 0x000000FFu)) }; int i = 0; while (size-- > 0) *payload++ ^= mask[i++ % 4]; } QT_END_NAMESPACE
SfietKonstantin/qtwebsockets
src/websockets/qwebsocketprotocol.cpp
C++
lgpl-2.1
8,694
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** from __future__ import print_function import FreeCAD import Path import PathScripts.PathDressup as PathDressup import PathScripts.PathGeom as PathGeom import PathScripts.PathLog as PathLog import PathScripts.PathUtil as PathUtil import PathScripts.PathUtils as PathUtils import math from PySide import QtCore # lazily loaded modules from lazy_loader.lazy_loader import LazyLoader DraftGeomUtils = LazyLoader('DraftGeomUtils', globals(), 'DraftGeomUtils') Part = LazyLoader('Part', globals(), 'Part') LOG_MODULE = PathLog.thisModule() PathLog.setLevel(PathLog.Level.NOTICE, LOG_MODULE) #PathLog.trackModule(LOG_MODULE) # Qt translation handling def translate(context, text, disambig=None): return QtCore.QCoreApplication.translate(context, text, disambig) movecommands = ['G0', 'G00', 'G1', 'G01', 'G2', 'G02', 'G3', 'G03'] movestraight = ['G1', 'G01'] movecw = ['G2', 'G02'] moveccw = ['G3', 'G03'] movearc = movecw + moveccw def debugMarker(vector, label, color=None, radius=0.5): if PathLog.getLevel(LOG_MODULE) == PathLog.Level.DEBUG: obj = FreeCAD.ActiveDocument.addObject("Part::Sphere", label) obj.Label = label obj.Radius = radius obj.Placement = FreeCAD.Placement(vector, FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0)) if color: obj.ViewObject.ShapeColor = color def debugCircle(vector, r, label, color=None): if PathLog.getLevel(LOG_MODULE) == PathLog.Level.DEBUG: obj = FreeCAD.ActiveDocument.addObject("Part::Cylinder", label) obj.Label = label obj.Radius = r obj.Height = 1 obj.Placement = FreeCAD.Placement(vector, FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0)) obj.ViewObject.Transparency = 90 if color: obj.ViewObject.ShapeColor = color def addAngle(a1, a2): a = a1 + a2 while a <= -math.pi: a += 2*math.pi while a > math.pi: a -= 2*math.pi return a def anglesAreParallel(a1, a2): an1 = addAngle(a1, 0) an2 = addAngle(a2, 0) if an1 == an2: return True if an1 == addAngle(an2, math.pi): return True return False def getAngle(v): a = v.getAngle(FreeCAD.Vector(1, 0, 0)) if v.y < 0: return -a return a def pointFromCommand(cmd, pt, X='X', Y='Y', Z='Z'): x = cmd.Parameters.get(X, pt.x) y = cmd.Parameters.get(Y, pt.y) z = cmd.Parameters.get(Z, pt.z) return FreeCAD.Vector(x, y, z) def edgesForCommands(cmds, startPt): edges = [] lastPt = startPt for cmd in cmds: if cmd.Name in movecommands: pt = pointFromCommand(cmd, lastPt) if cmd.Name in movestraight: edges.append(Part.Edge(Part.LineSegment(lastPt, pt))) elif cmd.Name in movearc: center = lastPt + pointFromCommand(cmd, FreeCAD.Vector(0, 0, 0), 'I', 'J', 'K') A = lastPt - center B = pt - center d = -B.x * A.y + B.y * A.x if d == 0: # we're dealing with half a circle here angle = getAngle(A) + math.pi/2 if cmd.Name in movecw: angle -= math.pi else: C = A + B angle = getAngle(C) R = (lastPt - center).Length ptm = center + FreeCAD.Vector(math.cos(angle), math.sin(angle), 0) * R edges.append(Part.Edge(Part.Arc(lastPt, ptm, pt))) lastPt = pt return edges class Style(object): # pylint: disable=no-init Dogbone = 'Dogbone' Tbone_H = 'T-bone horizontal' Tbone_V = 'T-bone vertical' Tbone_L = 'T-bone long edge' Tbone_S = 'T-bone short edge' All = [Dogbone, Tbone_H, Tbone_V, Tbone_L, Tbone_S] class Side(object): # pylint: disable=no-init Left = 'Left' Right = 'Right' All = [Left, Right] @classmethod def oppositeOf(cls, side): if side == cls.Left: return cls.Right if side == cls.Right: return cls.Left return None class Incision(object): # pylint: disable=no-init Fixed = 'fixed' Adaptive = 'adaptive' Custom = 'custom' All = [Adaptive, Fixed, Custom] class Smooth(object): # pylint: disable=no-init Neither = 0 In = 1 Out = 2 InAndOut = In | Out # Chord # A class to represent the start and end point of a path command. If the underlying # Command is a rotate command the receiver does represent a chord in the geometric # sense of the word. If the underlying command is a straight move then the receiver # represents the actual move. # This implementation really only deals with paths in the XY plane. Z is assumed to # be constant in all calculated results. # Instances of Chord are generally considered immutable and all movement member # functions return new instances. class Chord (object): def __init__(self, start=None, end=None): if not start: start = FreeCAD.Vector() if not end: end = FreeCAD.Vector() self.Start = start self.End = end def __str__(self): return "Chord([%g, %g, %g] -> [%g, %g, %g])" % (self.Start.x, self.Start.y, self.Start.z, self.End.x, self.End.y, self.End.z) def moveTo(self, newEnd): return Chord(self.End, newEnd) def moveToParameters(self, params): x = params.get('X', self.End.x) y = params.get('Y', self.End.y) z = params.get('Z', self.End.z) return self.moveTo(FreeCAD.Vector(x, y, z)) def moveBy(self, x, y, z): return self.moveTo(self.End + FreeCAD.Vector(x, y, z)) def move(self, distance, angle): dx = distance * math.cos(angle) dy = distance * math.sin(angle) return self.moveBy(dx, dy, 0) def asVector(self): return self.End - self.Start def asDirection(self): return self.asVector().normalize() def asLine(self): return Part.LineSegment(self.Start, self.End) def asEdge(self): return Part.Edge(self.asLine()) def getLength(self): return self.asVector().Length def getDirectionOfVector(self, B): A = self.asDirection() # if the 2 vectors are identical, they head in the same direction PathLog.debug(" {}.getDirectionOfVector({})".format(A, B)) if PathGeom.pointsCoincide(A, B): return 'Straight' d = -A.x*B.y + A.y*B.x if d < 0: return Side.Left if d > 0: return Side.Right # at this point the only direction left is backwards return 'Back' def getDirectionOf(self, chordOrVector): if type(chordOrVector) is Chord: return self.getDirectionOfVector(chordOrVector.asDirection()) return self.getDirectionOfVector(chordOrVector.normalize()) def getAngleOfVector(self, ref): angle = self.asVector().getAngle(ref) # unfortunately they never figure out the sign :( # positive angles go up, so when the reference vector is left # then the receiver must go down if self.getDirectionOfVector(ref) == Side.Left: return -angle return angle def getAngle(self, refChordOrVector): if type(refChordOrVector) is Chord: return self.getAngleOfVector(refChordOrVector.asDirection()) return self.getAngleOfVector(refChordOrVector.normalize()) def getAngleXY(self): return self.getAngle(FreeCAD.Vector(1, 0, 0)) def commandParams(self, f): params = {"X": self.End.x, "Y": self.End.y, "Z": self.End.z} if f: params['F'] = f return params def g1Command(self, f): return Path.Command("G1", self.commandParams(f)) def arcCommand(self, cmd, center, f): params = self.commandParams(f) d = center - self.Start params['I'] = d.x params['J'] = d.y params['K'] = 0 return Path.Command(cmd, params) def g2Command(self, center, f): return self.arcCommand("G2", center, f) def g3Command(self, center, f): return self.arcCommand("G3", center, f) def isAPlungeMove(self): return not PathGeom.isRoughly(self.End.z, self.Start.z) def isANoopMove(self): PathLog.debug("{}.isANoopMove(): {}".format(self, PathGeom.pointsCoincide(self.Start, self.End))) return PathGeom.pointsCoincide(self.Start, self.End) def foldsBackOrTurns(self, chord, side): direction = chord.getDirectionOf(self) PathLog.info(" - direction = %s/%s" % (direction, side)) return direction == 'Back' or direction == side def connectsTo(self, chord): return PathGeom.pointsCoincide(self.End, chord.Start) class Bone(object): def __init__(self, boneId, obj, lastCommand, inChord, outChord, smooth, F): self.obj = obj self.boneId = boneId self.lastCommand = lastCommand self.inChord = inChord self.outChord = outChord self.smooth = smooth self.smooth = Smooth.Neither self.F = F # initialized later self.cDist = None self.cAngle = None self.tAngle = None self.cPt = None def angle(self): if self.cAngle is None: baseAngle = self.inChord.getAngleXY() turnAngle = self.outChord.getAngle(self.inChord) theta = addAngle(baseAngle, (turnAngle - math.pi)/2) if self.obj.Side == Side.Left: theta = addAngle(theta, math.pi) self.tAngle = turnAngle self.cAngle = theta return self.cAngle def distance(self, toolRadius): if self.cDist is None: self.angle() # make sure the angles are initialized self.cDist = toolRadius / math.cos(self.tAngle/2) return self.cDist def corner(self, toolRadius): if self.cPt is None: self.cPt = self.inChord.move(self.distance(toolRadius), self.angle()).End return self.cPt def location(self): return (self.inChord.End.x, self.inChord.End.y) def locationZ(self): return (self.inChord.End.x, self.inChord.End.y, self.inChord.End.z) def adaptiveLength(self, boneAngle, toolRadius): theta = self.angle() distance = self.distance(toolRadius) # there is something weird happening if the boneAngle came from a horizontal/vertical t-bone # for some reason pi/2 is not equal to pi/2 if math.fabs(theta - boneAngle) < 0.00001: # moving directly towards the corner PathLog.debug("adaptive - on target: %.2f - %.2f" % (distance, toolRadius)) return distance - toolRadius PathLog.debug("adaptive - angles: corner=%.2f bone=%.2f diff=%.12f" % (theta/math.pi, boneAngle/math.pi, theta - boneAngle)) # The bones root and end point form a triangle with the intersection of the tool path # with the toolRadius circle around the bone end point. # In case the math looks questionable, look for "triangle ssa" # c = distance # b = self.toolRadius # beta = fabs(boneAngle - theta) beta = math.fabs(addAngle(boneAngle, -theta)) # pylint: disable=invalid-unary-operand-type D = (distance / toolRadius) * math.sin(beta) if D > 1: # no intersection PathLog.debug("adaptive - no intersection - no bone") return 0 gamma = math.asin(D) alpha = math.pi - beta - gamma if PathGeom.isRoughly(0.0, math.sin(beta)): # it is not a good idea to divide by 0 length = 0.0 else: length = toolRadius * math.sin(alpha) / math.sin(beta) if D < 1 and toolRadius < distance: # there exists a second solution beta2 = beta gamma2 = math.pi - gamma alpha2 = math.pi - beta2 - gamma2 length2 = toolRadius * math.sin(alpha2) / math.sin(beta2) length = min(length, length2) PathLog.debug("adaptive corner=%.2f * %.2f˚ -> bone=%.2f * %.2f˚" % (distance, theta, length, boneAngle)) return length class ObjectDressup(object): def __init__(self, obj, base): # Tool Properties obj.addProperty("App::PropertyLink", "Base", "Base", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "The base path to modify")) obj.addProperty("App::PropertyEnumeration", "Side", "Dressup", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "The side of path to insert bones")) obj.Side = [Side.Left, Side.Right] obj.Side = Side.Right obj.addProperty("App::PropertyEnumeration", "Style", "Dressup", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "The style of bones")) obj.Style = Style.All obj.Style = Style.Dogbone obj.addProperty("App::PropertyIntegerList", "BoneBlacklist", "Dressup", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "Bones that aren't dressed up")) obj.BoneBlacklist = [] obj.setEditorMode('BoneBlacklist', 2) # hide this one obj.addProperty("App::PropertyEnumeration", "Incision", "Dressup", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "The algorithm to determine the bone length")) obj.Incision = Incision.All obj.Incision = Incision.Adaptive obj.addProperty("App::PropertyFloat", "Custom", "Dressup", QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "Dressup length if Incision == custom")) obj.Custom = 0.0 obj.Proxy = self obj.Base = base # initialized later self.boneShapes = None self.toolRadius = 0 self.dbg = None self.locationBlacklist = None self.shapes = None self.boneId = None self.bones = None def onDocumentRestored(self, obj): obj.setEditorMode('BoneBlacklist', 2) # hide this one def __getstate__(self): return None def __setstate__(self, state): return None def theOtherSideOf(self, side): if side == Side.Left: return Side.Right return Side.Left # Answer true if a dogbone could be on either end of the chord, given its command def canAttachDogbone(self, cmd, chord): return cmd.Name in movestraight and not chord.isAPlungeMove() and not chord.isANoopMove() def shouldInsertDogbone(self, obj, inChord, outChord): return outChord.foldsBackOrTurns(inChord, self.theOtherSideOf(obj.Side)) def findPivotIntersection(self, pivot, pivotEdge, edge, refPt, d, color): # pylint: disable=unused-argument PathLog.track("(%.2f, %.2f)^%.2f - [(%.2f, %.2f), (%.2f, %.2f)]" % (pivotEdge.Curve.Center.x, pivotEdge.Curve.Center.y, pivotEdge.Curve.Radius, edge.Vertexes[0].Point.x, edge.Vertexes[0].Point.y, edge.Vertexes[1].Point.x, edge.Vertexes[1].Point.y)) ppt = None pptDistance = 0 for pt in DraftGeomUtils.findIntersection(edge, pivotEdge, dts=False): # debugMarker(pt, "pti.%d-%s.in" % (self.boneId, d), color, 0.2) distance = (pt - refPt).Length PathLog.debug(" --> (%.2f, %.2f): %.2f" % (pt.x, pt.y, distance)) if not ppt or pptDistance < distance: ppt = pt pptDistance = distance if not ppt: tangent = DraftGeomUtils.findDistance(pivot, edge) if tangent: PathLog.debug("Taking tangent as intersect %s" % tangent) ppt = pivot + tangent else: PathLog.debug("Taking chord start as intersect %s" % edge.Vertexes[0].Point) ppt = edge.Vertexes[0].Point # debugMarker(ppt, "ptt.%d-%s.in" % (self.boneId, d), color, 0.2) PathLog.debug(" --> (%.2f, %.2f)" % (ppt.x, ppt.y)) return ppt def pointIsOnEdge(self, point, edge): param = edge.Curve.parameter(point) return edge.FirstParameter <= param <= edge.LastParameter def smoothChordCommands(self, bone, inChord, outChord, edge, wire, corner, smooth, color=None): if smooth == 0: PathLog.info(" No smoothing requested") return [bone.lastCommand, outChord.g1Command(bone.F)] d = 'in' refPoint = inChord.Start if smooth == Smooth.Out: d = 'out' refPoint = outChord.End if DraftGeomUtils.areColinear(inChord.asEdge(), outChord.asEdge()): PathLog.info(" straight edge %s" % d) return [outChord.g1Command(bone.F)] pivot = None pivotDistance = 0 PathLog.info("smooth: (%.2f, %.2f)-(%.2f, %.2f)" % (edge.Vertexes[0].Point.x, edge.Vertexes[0].Point.y, edge.Vertexes[1].Point.x, edge.Vertexes[1].Point.y)) for e in wire.Edges: self.dbg.append(e) if type(e.Curve) == Part.LineSegment or type(e.Curve) == Part.Line: PathLog.debug(" (%.2f, %.2f)-(%.2f, %.2f)" % (e.Vertexes[0].Point.x, e.Vertexes[0].Point.y, e.Vertexes[1].Point.x, e.Vertexes[1].Point.y)) else: PathLog.debug(" (%.2f, %.2f)^%.2f" % (e.Curve.Center.x, e.Curve.Center.y, e.Curve.Radius)) for pt in DraftGeomUtils.findIntersection(edge, e, True, findAll=True): if not PathGeom.pointsCoincide(pt, corner) and self.pointIsOnEdge(pt, e): # debugMarker(pt, "candidate-%d-%s" % (self.boneId, d), color, 0.05) PathLog.debug(" -> candidate") distance = (pt - refPoint).Length if not pivot or pivotDistance > distance: pivot = pt pivotDistance = distance else: PathLog.debug(" -> corner intersect") if pivot: # debugCircle(pivot, self.toolRadius, "pivot.%d-%s" % (self.boneId, d), color) pivotEdge = Part.Edge(Part.Circle(pivot, FreeCAD.Vector(0, 0, 1), self.toolRadius)) t1 = self.findPivotIntersection(pivot, pivotEdge, inChord.asEdge(), inChord.End, d, color) t2 = self.findPivotIntersection(pivot, pivotEdge, outChord.asEdge(), inChord.End, d, color) commands = [] if not PathGeom.pointsCoincide(t1, inChord.Start): PathLog.debug(" add lead in") commands.append(Chord(inChord.Start, t1).g1Command(bone.F)) if bone.obj.Side == Side.Left: PathLog.debug(" add g3 command") commands.append(Chord(t1, t2).g3Command(pivot, bone.F)) else: PathLog.debug(" add g2 command center=(%.2f, %.2f) -> from (%2f, %.2f) to (%.2f, %.2f" % (pivot.x, pivot.y, t1.x, t1.y, t2.x, t2.y)) commands.append(Chord(t1, t2).g2Command(pivot, bone.F)) if not PathGeom.pointsCoincide(t2, outChord.End): PathLog.debug(" add lead out") commands.append(Chord(t2, outChord.End).g1Command(bone.F)) # debugMarker(pivot, "pivot.%d-%s" % (self.boneId, d), color, 0.2) # debugMarker(t1, "pivot.%d-%s.in" % (self.boneId, d), color, 0.1) # debugMarker(t2, "pivot.%d-%s.out" % (self.boneId, d), color, 0.1) return commands PathLog.info(" no pivot found - straight command") return [inChord.g1Command(bone.F), outChord.g1Command(bone.F)] def inOutBoneCommands(self, bone, boneAngle, fixedLength): corner = bone.corner(self.toolRadius) bone.tip = bone.inChord.End # in case there is no bone PathLog.debug("corner = (%.2f, %.2f)" % (corner.x, corner.y)) # debugMarker(corner, 'corner', (1., 0., 1.), self.toolRadius) length = fixedLength if bone.obj.Incision == Incision.Custom: length = bone.obj.Custom if bone.obj.Incision == Incision.Adaptive: length = bone.adaptiveLength(boneAngle, self.toolRadius) if length == 0: PathLog.info("no bone after all ..") return [bone.lastCommand, bone.outChord.g1Command(bone.F)] # track length for marker visuals self.length = max(self.length, length) boneInChord = bone.inChord.move(length, boneAngle) boneOutChord = boneInChord.moveTo(bone.outChord.Start) # debugCircle(boneInChord.Start, self.toolRadius, 'boneStart') # debugCircle(boneInChord.End, self.toolRadius, 'boneEnd') bone.tip = boneInChord.End if bone.smooth == 0: return [bone.lastCommand, boneInChord.g1Command(bone.F), boneOutChord.g1Command(bone.F), bone.outChord.g1Command(bone.F)] # reconstruct the corner and convert to an edge offset = corner - bone.inChord.End iChord = Chord(bone.inChord.Start + offset, bone.inChord.End + offset) oChord = Chord(bone.outChord.Start + offset, bone.outChord.End + offset) iLine = iChord.asLine() oLine = oChord.asLine() cornerShape = Part.Shape([iLine, oLine]) # construct a shape representing the cut made by the bone vt0 = FreeCAD.Vector(0, self.toolRadius, 0) vt1 = FreeCAD.Vector(length, self.toolRadius, 0) vb0 = FreeCAD.Vector(0, -self.toolRadius, 0) vb1 = FreeCAD.Vector(length, -self.toolRadius, 0) vm2 = FreeCAD.Vector(length + self.toolRadius, 0, 0) boneBot = Part.LineSegment(vb1, vb0) boneLid = Part.LineSegment(vb0, vt0) boneTop = Part.LineSegment(vt0, vt1) # what we actually want is an Arc - but findIntersect only returns the coincident if one exists # which really sucks because that's the one we're probably not interested in .... boneArc = Part.Arc(vt1, vm2, vb1) # boneArc = Part.Circle(FreeCAD.Vector(length, 0, 0), FreeCAD.Vector(0,0,1), self.toolRadius) boneWire = Part.Shape([boneTop, boneArc, boneBot, boneLid]) boneWire.rotate(FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(0, 0, 1), boneAngle * 180 / math.pi) boneWire.translate(bone.inChord.End) self.boneShapes = [cornerShape, boneWire] bone.inCommands = self.smoothChordCommands(bone, bone.inChord, boneInChord, Part.Edge(iLine), boneWire, corner, bone.smooth & Smooth.In, (1., 0., 0.)) bone.outCommands = self.smoothChordCommands(bone, boneOutChord, bone.outChord, Part.Edge(oLine), boneWire, corner, bone.smooth & Smooth.Out, (0., 1., 0.)) return bone.inCommands + bone.outCommands def dogbone(self, bone): boneAngle = bone.angle() length = self.toolRadius * 0.41422 # 0.41422 = 2/sqrt(2) - 1 + (a tiny bit) return self.inOutBoneCommands(bone, boneAngle, length) def tboneHorizontal(self, bone): angle = bone.angle() boneAngle = 0 if math.fabs(angle) > math.pi/2: boneAngle = math.pi return self.inOutBoneCommands(bone, boneAngle, self.toolRadius) def tboneVertical(self, bone): angle = bone.angle() boneAngle = math.pi/2 if PathGeom.isRoughly(angle, math.pi) or angle < 0: boneAngle = -boneAngle return self.inOutBoneCommands(bone, boneAngle, self.toolRadius) def tboneEdgeCommands(self, bone, onIn): if onIn: boneAngle = bone.inChord.getAngleXY() else: boneAngle = bone.outChord.getAngleXY() if Side.Right == bone.outChord.getDirectionOf(bone.inChord): boneAngle = boneAngle - math.pi/2 else: boneAngle = boneAngle + math.pi/2 onInString = 'out' if onIn: onInString = 'in' PathLog.debug("tboneEdge boneAngle[%s]=%.2f (in=%.2f, out=%.2f)" % (onInString, boneAngle/math.pi, bone.inChord.getAngleXY()/math.pi, bone.outChord.getAngleXY()/math.pi)) return self.inOutBoneCommands(bone, boneAngle, self.toolRadius) def tboneLongEdge(self, bone): inChordIsLonger = bone.inChord.getLength() > bone.outChord.getLength() return self.tboneEdgeCommands(bone, inChordIsLonger) def tboneShortEdge(self, bone): inChordIsShorter = bone.inChord.getLength() < bone.outChord.getLength() return self.tboneEdgeCommands(bone, inChordIsShorter) def boneIsBlacklisted(self, bone): blacklisted = False parentConsumed = False if bone.boneId in bone.obj.BoneBlacklist: blacklisted = True elif bone.location() in self.locationBlacklist: bone.obj.BoneBlacklist.append(bone.boneId) blacklisted = True elif hasattr(bone.obj.Base, 'BoneBlacklist'): parentConsumed = bone.boneId not in bone.obj.Base.BoneBlacklist blacklisted = parentConsumed if blacklisted: self.locationBlacklist.add(bone.location()) return (blacklisted, parentConsumed) # Generate commands necessary to execute the dogbone def boneCommands(self, bone, enabled): if enabled: if bone.obj.Style == Style.Dogbone: return self.dogbone(bone) if bone.obj.Style == Style.Tbone_H: return self.tboneHorizontal(bone) if bone.obj.Style == Style.Tbone_V: return self.tboneVertical(bone) if bone.obj.Style == Style.Tbone_L: return self.tboneLongEdge(bone) if bone.obj.Style == Style.Tbone_S: return self.tboneShortEdge(bone) else: return [bone.lastCommand, bone.outChord.g1Command(bone.F)] def insertBone(self, bone): PathLog.debug(">----------------------------------- %d --------------------------------------" % bone.boneId) self.boneShapes = [] blacklisted, inaccessible = self.boneIsBlacklisted(bone) enabled = not blacklisted self.bones.append((bone.boneId, bone.locationZ(), enabled, inaccessible)) self.boneId = bone.boneId if False and PathLog.getLevel(LOG_MODULE) == PathLog.Level.DEBUG and bone.boneId > 2: commands = self.boneCommands(bone, False) else: commands = self.boneCommands(bone, enabled) bone.commands = commands self.shapes[bone.boneId] = self.boneShapes PathLog.debug("<----------------------------------- %d --------------------------------------" % bone.boneId) return commands def removePathCrossing(self, commands, bone1, bone2): commands.append(bone2.lastCommand) bones = bone2.commands if True and hasattr(bone1, "outCommands") and hasattr(bone2, "inCommands"): inEdges = edgesForCommands(bone1.outCommands, bone1.tip) outEdges = edgesForCommands(bone2.inCommands, bone2.inChord.Start) for i in range(len(inEdges)): e1 = inEdges[i] for j in range(len(outEdges)-1, -1, -1): e2 = outEdges[j] cutoff = DraftGeomUtils.findIntersection(e1, e2) for pt in cutoff: # debugCircle(e1.Curve.Center, e1.Curve.Radius, "bone.%d-1" % (self.boneId), (1.,0.,0.)) # debugCircle(e2.Curve.Center, e2.Curve.Radius, "bone.%d-2" % (self.boneId), (0.,1.,0.)) if PathGeom.pointsCoincide(pt, e1.valueAt(e1.LastParameter)) or PathGeom.pointsCoincide(pt, e2.valueAt(e2.FirstParameter)): continue # debugMarker(pt, "it", (0.0, 1.0, 1.0)) # 1. remove all redundant commands commands = commands[:-(len(inEdges) - i)] # 2., correct where c1 ends c1 = bone1.outCommands[i] c1Params = c1.Parameters c1Params.update({'X': pt.x, 'Y': pt.y, 'Z': pt.z}) c1 = Path.Command(c1.Name, c1Params) commands.append(c1) # 3. change where c2 starts, this depends on the command itself c2 = bone2.inCommands[j] if c2.Name in movearc: center = e2.Curve.Center offset = center - pt c2Params = c2.Parameters c2Params.update({'I': offset.x, 'J': offset.y, 'K': offset.z}) c2 = Path.Command(c2.Name, c2Params) bones = [c2] bones.extend(bone2.commands[j+1:]) else: bones = bone2.commands[j:] # there can only be the one ... return commands, bones return commands, bones def execute(self, obj, forReal=True): if not obj.Base: return if forReal and not obj.Base.isDerivedFrom("Path::Feature"): return if not obj.Base.Path: return if not obj.Base.Path.Commands: return self.setup(obj, False) commands = [] # the dressed commands lastChord = Chord() # the last chord lastCommand = None # the command that generated the last chord lastBone = None # track last bone for optimizations oddsAndEnds = [] # track chords that are connected to plunges - in case they form a loop boneId = 1 self.bones = [] self.locationBlacklist = set() self.length = 0 # boneIserted = False for (i, thisCommand) in enumerate(obj.Base.Path.Commands): # if i > 14: # if lastCommand: # commands.append(lastCommand) # lastCommand = None # commands.append(thisCommand) # continue PathLog.info("%3d: %s" % (i, thisCommand)) if thisCommand.Name in movecommands: thisChord = lastChord.moveToParameters(thisCommand.Parameters) thisIsACandidate = self.canAttachDogbone(thisCommand, thisChord) if thisIsACandidate and lastCommand and self.shouldInsertDogbone(obj, lastChord, thisChord): PathLog.info(" Found bone corner: {}".format(lastChord.End)) bone = Bone(boneId, obj, lastCommand, lastChord, thisChord, Smooth.InAndOut, thisCommand.Parameters.get('F')) bones = self.insertBone(bone) boneId += 1 if lastBone: PathLog.info(" removing potential path crossing") # debugMarker(thisChord.Start, "it", (1.0, 0.0, 1.0)) commands, bones = self.removePathCrossing(commands, lastBone, bone) commands.extend(bones[:-1]) lastCommand = bones[-1] lastBone = bone elif lastCommand and thisChord.isAPlungeMove(): PathLog.info(" Looking for connection in odds and ends") haveNewLastCommand = False for chord in (chord for chord in oddsAndEnds if lastChord.connectsTo(chord)): if self.shouldInsertDogbone(obj, lastChord, chord): PathLog.info(" and there is one") PathLog.debug(" odd/end={} last={}".format(chord, lastChord)) bone = Bone(boneId, obj, lastCommand, lastChord, chord, Smooth.In, lastCommand.Parameters.get('F')) bones = self.insertBone(bone) boneId += 1 if lastBone: PathLog.info(" removing potential path crossing") # debugMarker(chord.Start, "it", (0.0, 1.0, 1.0)) commands, bones = self.removePathCrossing(commands, lastBone, bone) commands.extend(bones[:-1]) lastCommand = bones[-1] haveNewLastCommand = True if not haveNewLastCommand: commands.append(lastCommand) lastCommand = None commands.append(thisCommand) lastBone = None elif thisIsACandidate: PathLog.info(" is a candidate, keeping for later") if lastCommand: commands.append(lastCommand) lastCommand = thisCommand lastBone = None elif thisChord.isANoopMove(): PathLog.info(" ignoring and dropping noop move") continue else: PathLog.info(" nope") if lastCommand: commands.append(lastCommand) lastCommand = None commands.append(thisCommand) lastBone = None if lastChord.isAPlungeMove() and thisIsACandidate: PathLog.info(" adding to odds and ends") oddsAndEnds.append(thisChord) lastChord = thisChord else: if thisCommand.Name[0] != '(': PathLog.info(" Clean slate") if lastCommand: commands.append(lastCommand) lastCommand = None lastBone = None commands.append(thisCommand) # for cmd in commands: # PathLog.debug("cmd = '%s'" % cmd) path = Path.Path(commands) obj.Path = path def setup(self, obj, initial): PathLog.info("Here we go ... ") if initial: if hasattr(obj.Base, "BoneBlacklist"): # dressing up a bone dressup obj.Side = obj.Base.Side else: PathLog.info("Default side = right") # otherwise dogbones are opposite of the base path's side side = Side.Right if hasattr(obj.Base, 'Side') and obj.Base.Side == 'Inside': PathLog.info("inside -> side = left") side = Side.Left else: PathLog.info("not inside -> side stays right") if hasattr(obj.Base, 'Direction') and obj.Base.Direction == 'CCW': PathLog.info("CCW -> switch sides") side = Side.oppositeOf(side) else: PathLog.info("CW -> stay on side") obj.Side = side self.toolRadius = 5 tc = PathDressup.toolController(obj.Base) if tc is None or tc.ToolNumber == 0: self.toolRadius = 5 else: tool = tc.Proxy.getTool(tc) # PathUtils.getTool(obj, tc.ToolNumber) if not tool or float(tool.Diameter) == 0: self.toolRadius = 5 else: self.toolRadius = float(tool.Diameter) / 2 self.shapes = {} self.dbg = [] def boneStateList(self, obj): state = {} # If the receiver was loaded from file, then it never generated the bone list. if not hasattr(self, 'bones'): self.execute(obj) for (nr, loc, enabled, inaccessible) in self.bones: item = state.get((loc[0], loc[1])) if item: item[2].append(nr) item[3].append(loc[2]) else: state[(loc[0], loc[1])] = (enabled, inaccessible, [nr], [loc[2]]) return state class Marker(object): def __init__(self, pt, r, h): if PathGeom.isRoughly(h, 0): h = 0.1 self.pt = pt self.r = r self.h = h self.sep = coin.SoSeparator() self.pos = coin.SoTranslation() self.pos.translation = (pt.x, pt.y, pt.z + h / 2) self.rot = coin.SoRotationXYZ() self.rot.axis = self.rot.X self.rot.angle = math.pi / 2 self.cyl = coin.SoCylinder() self.cyl.radius = r self.cyl.height = h # self.cyl.removePart(self.cyl.TOP) # self.cyl.removePart(self.cyl.BOTTOM) self.material = coin.SoMaterial() self.sep.addChild(self.pos) self.sep.addChild(self.rot) self.sep.addChild(self.material) self.sep.addChild(self.cyl) self.lowlight() def setSelected(self, selected): if selected: self.highlight() else: self.lowlight() def highlight(self): self.material.diffuseColor = self.color(1) self.material.transparency = 0.45 def lowlight(self): self.material.diffuseColor = self.color(0) self.material.transparency = 0.75 def color(self, id): if id == 1: return coin.SbColor(.9, .9, .5) return coin.SbColor(.9, .5, .9) class TaskPanel(object): DataIds = QtCore.Qt.ItemDataRole.UserRole DataKey = QtCore.Qt.ItemDataRole.UserRole + 1 DataLoc = QtCore.Qt.ItemDataRole.UserRole + 2 def __init__(self, viewProvider, obj): self.viewProvider = viewProvider self.obj = obj self.form = FreeCADGui.PySideUic.loadUi(":/panels/DogboneEdit.ui") self.s = None FreeCAD.ActiveDocument.openTransaction(translate("Path_DressupDogbone", "Edit Dogbone Dress-up")) self.height = 10 self.markers = [] def reject(self): FreeCAD.ActiveDocument.abortTransaction() FreeCADGui.Control.closeDialog() FreeCAD.ActiveDocument.recompute() FreeCADGui.Selection.removeObserver(self.s) self.cleanup() def accept(self): self.getFields() FreeCAD.ActiveDocument.commitTransaction() FreeCADGui.ActiveDocument.resetEdit() FreeCADGui.Control.closeDialog() FreeCAD.ActiveDocument.recompute() FreeCADGui.Selection.removeObserver(self.s) FreeCAD.ActiveDocument.recompute() self.cleanup() def cleanup(self): self.viewProvider.showMarkers(False) for m in self.markers: self.viewProvider.switch.removeChild(m.sep) self.markers = [] def getFields(self): self.obj.Style = str(self.form.styleCombo.currentText()) self.obj.Side = str(self.form.sideCombo.currentText()) self.obj.Incision = str(self.form.incisionCombo.currentText()) self.obj.Custom = self.form.custom.value() blacklist = [] for i in range(0, self.form.bones.count()): item = self.form.bones.item(i) if item.checkState() == QtCore.Qt.CheckState.Unchecked: blacklist.extend(item.data(self.DataIds)) self.obj.BoneBlacklist = sorted(blacklist) self.obj.Proxy.execute(self.obj) def updateBoneList(self): itemList = [] for loc, (enabled, inaccessible, ids, zs) in PathUtil.keyValueIter(self.obj.Proxy.boneStateList(self.obj)): lbl = '(%.2f, %.2f): %s' % (loc[0], loc[1], ','.join(str(id) for id in ids)) item = QtGui.QListWidgetItem(lbl) if enabled: item.setCheckState(QtCore.Qt.CheckState.Checked) else: item.setCheckState(QtCore.Qt.CheckState.Unchecked) flags = QtCore.Qt.ItemFlag.ItemIsSelectable if not inaccessible: flags |= QtCore.Qt.ItemFlag.ItemIsEnabled | QtCore.Qt.ItemFlag.ItemIsUserCheckable item.setFlags(flags) item.setData(self.DataIds, ids) item.setData(self.DataKey, ids[0]) item.setData(self.DataLoc, loc) itemList.append(item) self.form.bones.clear() markers = [] for item in sorted(itemList, key=lambda item: item.data(self.DataKey)): self.form.bones.addItem(item) loc = item.data(self.DataLoc) r = max(self.obj.Proxy.length, 1) markers.append(Marker(FreeCAD.Vector(loc[0], loc[1], min(zs)), r, max(1, max(zs) - min(zs)))) for m in self.markers: self.viewProvider.switch.removeChild(m.sep) for m in markers: self.viewProvider.switch.addChild(m.sep) self.markers = markers def updateUI(self): customSelected = self.obj.Incision == Incision.Custom self.form.custom.setEnabled(customSelected) self.form.customLabel.setEnabled(customSelected) self.updateBoneList() if PathLog.getLevel(LOG_MODULE) == PathLog.Level.DEBUG: for obj in FreeCAD.ActiveDocument.Objects: if obj.Name.startswith('Shape'): FreeCAD.ActiveDocument.removeObject(obj.Name) PathLog.info('object name %s' % self.obj.Name) if hasattr(self.obj.Proxy, "shapes"): PathLog.info("showing shapes attribute") for shapes in self.obj.Proxy.shapes.values(): for shape in shapes: Part.show(shape) else: PathLog.info("no shapes attribute found") def updateModel(self): self.getFields() self.updateUI() FreeCAD.ActiveDocument.recompute() def setupCombo(self, combo, text, items): if items and len(items) > 0: for i in range(combo.count(), -1, -1): combo.removeItem(i) combo.addItems(items) index = combo.findText(text, QtCore.Qt.MatchFixedString) if index >= 0: combo.setCurrentIndex(index) def setFields(self): self.setupCombo(self.form.styleCombo, self.obj.Style, Style.All) self.setupCombo(self.form.sideCombo, self.obj.Side, Side.All) self.setupCombo(self.form.incisionCombo, self.obj.Incision, Incision.All) self.form.custom.setMinimum(0.0) self.form.custom.setDecimals(3) self.form.custom.setValue(self.obj.Custom) self.updateUI() def open(self): self.s = SelObserver() # install the function mode resident FreeCADGui.Selection.addObserver(self.s) def setupUi(self): self.setFields() # now that the form is filled, setup the signal handlers self.form.styleCombo.currentIndexChanged.connect(self.updateModel) self.form.sideCombo.currentIndexChanged.connect(self.updateModel) self.form.incisionCombo.currentIndexChanged.connect(self.updateModel) self.form.custom.valueChanged.connect(self.updateModel) self.form.bones.itemChanged.connect(self.updateModel) self.form.bones.itemSelectionChanged.connect(self.updateMarkers) self.viewProvider.showMarkers(True) def updateMarkers(self): index = self.form.bones.currentRow() for i, m in enumerate(self.markers): m.setSelected(i == index) class SelObserver(object): def __init__(self): import PathScripts.PathSelection as PST PST.eselect() def __del__(self): import PathScripts.PathSelection as PST PST.clear() def addSelection(self, doc, obj, sub, pnt): # pylint: disable=unused-argument FreeCADGui.doCommand('Gui.Selection.addSelection(FreeCAD.ActiveDocument.' + obj + ')') FreeCADGui.updateGui() class ViewProviderDressup(object): def __init__(self, vobj): self.vobj = vobj self.obj = None def attach(self, vobj): self.obj = vobj.Object if self.obj and self.obj.Base: for i in self.obj.Base.InList: if hasattr(i, "Group"): group = i.Group for g in group: if g.Name == self.obj.Base.Name: group.remove(g) i.Group = group # FreeCADGui.ActiveDocument.getObject(obj.Base.Name).Visibility = False self.switch = coin.SoSwitch() vobj.RootNode.addChild(self.switch) def showMarkers(self, on): sw = coin.SO_SWITCH_ALL if on else coin.SO_SWITCH_NONE self.switch.whichChild = sw def claimChildren(self): return [self.obj.Base] def setEdit(self, vobj, mode=0): # pylint: disable=unused-argument FreeCADGui.Control.closeDialog() panel = TaskPanel(self, vobj.Object) FreeCADGui.Control.showDialog(panel) panel.setupUi() return True def __getstate__(self): return None def __setstate__(self, state): return None def onDelete(self, arg1=None, arg2=None): '''this makes sure that the base operation is added back to the project and visible''' # pylint: disable=unused-argument if arg1.Object and arg1.Object.Base: FreeCADGui.ActiveDocument.getObject(arg1.Object.Base.Name).Visibility = True job = PathUtils.findParentJob(arg1.Object) if job: job.Proxy.addOperation(arg1.Object.Base, arg1.Object) arg1.Object.Base = None return True def Create(base, name='DogboneDressup'): ''' Create(obj, name='DogboneDressup') ... dresses the given PathProfile/PathContour object with dogbones. ''' obj = FreeCAD.ActiveDocument.addObject('Path::FeaturePython', name) dbo = ObjectDressup(obj, base) job = PathUtils.findParentJob(base) job.Proxy.addOperation(obj, base) if FreeCAD.GuiUp: obj.ViewObject.Proxy = ViewProviderDressup(obj.ViewObject) obj.Base.ViewObject.Visibility = False dbo.setup(obj, True) return obj class CommandDressupDogbone(object): # pylint: disable=no-init def GetResources(self): return {'Pixmap': 'Path_Dressup', 'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "Dogbone Dress-up"), 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_DressupDogbone", "Creates a Dogbone Dress-up object from a selected path")} def IsActive(self): if FreeCAD.ActiveDocument is not None: for o in FreeCAD.ActiveDocument.Objects: if o.Name[:3] == "Job": return True return False def Activated(self): # check that the selection contains exactly what we want selection = FreeCADGui.Selection.getSelection() if len(selection) != 1: FreeCAD.Console.PrintError(translate("Path_DressupDogbone", "Please select one path object")+"\n") return baseObject = selection[0] if not baseObject.isDerivedFrom("Path::Feature"): FreeCAD.Console.PrintError(translate("Path_DressupDogbone", "The selected object is not a path")+"\n") return # everything ok! FreeCAD.ActiveDocument.openTransaction(translate("Path_DressupDogbone", "Create Dogbone Dress-up")) FreeCADGui.addModule('PathScripts.PathDressupDogbone') FreeCADGui.doCommand("PathScripts.PathDressupDogbone.Create(FreeCAD.ActiveDocument.%s)" % baseObject.Name) FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui from pivy import coin FreeCADGui.addCommand('Path_DressupDogbone', CommandDressupDogbone()) FreeCAD.Console.PrintLog("Loading DressupDogbone... done\n")
Fat-Zer/FreeCAD_sf_master
src/Mod/Path/PathScripts/PathDressupDogbone.py
Python
lgpl-2.1
49,208
/* Copyright (C) 2005 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include <fstream> #include <string> #include <vector> namespace BOOM { std::vector<std::string> read_file(std::istream &in) { std::vector<std::string> ans; while (in) { std::string line; getline(in, line); if (!in) break; ans.push_back(line); } return ans; } std::vector<std::string> read_file(const std::string &fname) { std::ifstream in(fname.c_str()); return read_file(in); } } // namespace BOOM
cran/Boom
src/cpputil/read_file.cpp
C++
lgpl-2.1
1,230
YUI.add('event-simulate', function (Y, NAME) { (function() { /** * Simulate user interaction by generating native DOM events. * * @module event-simulate * @requires event */ //shortcuts var L = Y.Lang, isFunction = L.isFunction, isString = L.isString, isBoolean = L.isBoolean, isObject = L.isObject, isNumber = L.isNumber, //mouse events supported mouseEvents = { click: 1, dblclick: 1, mouseover: 1, mouseout: 1, mousedown: 1, mouseup: 1, mousemove: 1, contextmenu:1 }, msPointerEvents = { MSPointerOver: 1, MSPointerOut: 1, MSPointerDown: 1, MSPointerUp: 1, MSPointerMove: 1 }, //key events supported keyEvents = { keydown: 1, keyup: 1, keypress: 1 }, //HTML events supported uiEvents = { submit: 1, blur: 1, change: 1, focus: 1, resize: 1, scroll: 1, select: 1 }, //events that bubble by default bubbleEvents = { scroll: 1, resize: 1, reset: 1, submit: 1, change: 1, select: 1, error: 1, abort: 1 }, //touch events supported touchEvents = { touchstart: 1, touchmove: 1, touchend: 1, touchcancel: 1 }, gestureEvents = { gesturestart: 1, gesturechange: 1, gestureend: 1 }; //all key, mouse and touch events bubble Y.mix(bubbleEvents, mouseEvents); Y.mix(bubbleEvents, keyEvents); Y.mix(bubbleEvents, touchEvents); /* * Note: Intentionally not for YUIDoc generation. * Simulates a key event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. Note: keydown causes Safari 2.x to * crash. * @method simulateKeyEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: keyup, keydown, and keypress. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 3 specifies that all key events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 3 specifies that all * key events can be cancelled. The default * is true. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} keyCode (Optional) The code for the key that is in use. * The default is 0. * @param {int} charCode (Optional) The Unicode code for the character * associated with the key being used. The default is 0. */ function simulateKeyEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, keyCode /*:int*/, charCode /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateKeyEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); switch(type){ case "textevent": //DOM Level 3 type = "keypress"; break; case "keyup": case "keydown": case "keypress": break; default: Y.error("simulateKeyEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateKeyEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all key events bubble } if (!isBoolean(cancelable)){ cancelable = true; //all key events can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(keyCode)){ keyCode = 0; } if (!isNumber(charCode)){ charCode = 0; } //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ try { //try to create key event customEvent = Y.config.doc.createEvent("KeyEvents"); /* * Interesting problem: Firefox implemented a non-standard * version of initKeyEvent() based on DOM Level 2 specs. * Key event was removed from DOM Level 2 and re-introduced * in DOM Level 3 with a different interface. Firefox is the * only browser with any implementation of Key Events, so for * now, assume it's Firefox if the above line doesn't error. */ // @TODO: Decipher between Firefox's implementation and a correct one. customEvent.initKeyEvent(type, bubbles, cancelable, view, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode); } catch (ex /*:Error*/){ /* * If it got here, that means key events aren't officially supported. * Safari/WebKit is a real problem now. WebKit 522 won't let you * set keyCode, charCode, or other properties if you use a * UIEvent, so we first must try to create a generic event. The * fun part is that this will throw an error on Safari 2.x. The * end result is that we need another try...catch statement just to * deal with this mess. */ try { //try to create generic event - will fail in Safari 2.x customEvent = Y.config.doc.createEvent("Events"); } catch (uierror /*:Error*/){ //the above failed, so create a UIEvent for Safari 2.x customEvent = Y.config.doc.createEvent("UIEvents"); } finally { customEvent.initEvent(type, bubbles, cancelable); //initialize customEvent.view = view; customEvent.altKey = altKey; customEvent.ctrlKey = ctrlKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; customEvent.keyCode = keyCode; customEvent.charCode = charCode; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; /* * IE doesn't support charCode explicitly. CharCode should * take precedence over any keyCode value for accurate * representation. */ customEvent.keyCode = (charCode > 0) ? charCode : keyCode; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateKeyEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a mouse event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateMouseEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} button (Optional) The button being pressed while the event * is executing. The value should be 0 for the primary mouse button * (typically the left button), 1 for the terciary mouse button * (typically the middle button), and 2 for the secondary mouse button * (typically the right button). The default is 0. * @param {HTMLElement} relatedTarget (Optional) For mouseout events, * this is the element that the mouse has moved to. For mouseover * events, this is the element that the mouse has moved from. This * argument is ignored for all other events. The default is null. */ function simulateMouseEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/, screenX /*:int*/, screenY /*:int*/, clientX /*:int*/, clientY /*:int*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, button /*:int*/, relatedTarget /*:HTMLElement*/) /*:Void*/ { //check target if (!target){ Y.error("simulateMouseEvent(): Invalid target."); } if (isString(type)){ //make sure it's a supported mouse event or an msPointerEvent. if (!mouseEvents[type.toLowerCase()] && !msPointerEvents[type]){ Y.error("simulateMouseEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateMouseEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all mouse events bubble } if (!isBoolean(cancelable)){ cancelable = (type !== "mousemove"); //mousemove is the only one that can't be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //number of mouse clicks must be at least one } if (!isNumber(screenX)){ screenX = 0; } if (!isNumber(screenY)){ screenY = 0; } if (!isNumber(clientX)){ clientX = 0; } if (!isNumber(clientY)){ clientY = 0; } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(button)){ button = 0; } relatedTarget = relatedTarget || null; //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ customEvent = Y.config.doc.createEvent("MouseEvents"); //Safari 2.x (WebKit 418) still doesn't implement initMouseEvent() if (customEvent.initMouseEvent){ customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget); } else { //Safari //the closest thing available in Safari 2.x is UIEvents customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initEvent(type, bubbles, cancelable); customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; customEvent.button = button; customEvent.relatedTarget = relatedTarget; } /* * Check to see if relatedTarget has been assigned. Firefox * versions less than 2.0 don't allow it to be assigned via * initMouseEvent() and the property is readonly after event * creation, so in order to keep YAHOO.util.getRelatedTarget() * working, assign to the IE proprietary toElement property * for mouseout event and fromElement property for mouseover * event. */ if (relatedTarget && !customEvent.relatedTarget){ if (type === "mouseout"){ customEvent.toElement = relatedTarget; } else if (type === "mouseover"){ customEvent.fromElement = relatedTarget; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; //fix button property for IE's wacky implementation switch(button){ case 0: customEvent.button = 1; break; case 1: customEvent.button = 4; break; case 2: //leave as is break; default: customEvent.button = 0; } /* * Have to use relatedTarget because IE won't allow assignment * to toElement or fromElement on generic events. This keeps * YAHOO.util.customEvent.getRelatedTarget() functional. */ customEvent.relatedTarget = relatedTarget; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateMouseEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a UI event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateHTMLEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. */ function simulateUIEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateUIEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); //make sure it's a supported mouse event if (!uiEvents[type]){ Y.error("simulateUIEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateUIEvent(): Event type must be a string."); } //try to create a mouse event var customEvent = null; //setup default values if (!isBoolean(bubbles)){ bubbles = (type in bubbleEvents); //not all events bubble } if (!isBoolean(cancelable)){ cancelable = (type === "submit"); //submit is the only one that can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //usually not used but defaulted to this } //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ //just a generic UI Event object is needed customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initUIEvent(type, bubbles, cancelable, view, detail); //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateUIEvent(): No event simulation framework present."); } } /* * (iOS only) This is for creating native DOM gesture events which only iOS * v2.0+ is supporting. * * @method simulateGestureEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateGestureEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean scale, // float rotation // float ) { var customEvent; if(!Y.UA.ios || Y.UA.ios<2.0) { Y.error("simulateGestureEvent(): Native gesture DOM eventframe is not available in this platform."); } // check taget if (!target){ Y.error("simulateGestureEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!gestureEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateGestureEvent(): Event type must be a string."); } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default if (!Y.Lang.isBoolean(cancelable)) { cancelable = true; } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 2; } // usually not used. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)){ scale = 1.0; } if (!Y.Lang.isNumber(rotation)){ rotation = 0.0; } customEvent = Y.config.doc.createEvent("GestureEvent"); customEvent.initGestureEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, target, scale, rotation); target.dispatchEvent(customEvent); } /* * @method simulateTouchEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {TouchList} touches A collection of Touch objects representing * all touches associated with this event. * @param {TouchList} targetTouches A collection of Touch objects * representing all touches associated with this target. * @param {TouchList} changedTouches A collection of Touch objects * representing all touches that changed in this event. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateTouchEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean touches, // TouchList targetTouches, // TouchList changedTouches, // TouchList scale, // float rotation // float ) { var customEvent; // check taget if (!target){ Y.error("simulateTouchEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!touchEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateTouchEvent(): Event type must be a string."); } // note that the caller is responsible to pass appropriate touch objects. // check touch objects // Android(even 4.0) doesn't define TouchList yet /*if(type === 'touchstart' || type === 'touchmove') { if(!touches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } } else if(type === 'touchend') { if(!changedTouches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } }*/ if(type === 'touchstart' || type === 'touchmove') { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object in touches'); } } else if(type === 'touchend') { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object in changedTouches'); } } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default. if (!Y.Lang.isBoolean(cancelable)) { cancelable = (type !== "touchcancel"); // touchcancel is not cancelled } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 1; } // usually not used. defaulted to # of touch objects. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)) { scale = 1.0; } if (!Y.Lang.isNumber(rotation)) { rotation = 0.0; } //check for DOM-compliant browsers first if (Y.Lang.isFunction(Y.config.doc.createEvent)) { if (Y.UA.android) { /* * Couldn't find android start version that supports touch event. * Assumed supported(btw APIs broken till icecream sandwitch) * from the beginning. */ if(Y.UA.android < 4.0) { /* * Touch APIs are broken in androids older than 4.0. We will use * simulated touch apis for these versions. * App developer still can listen for touch events. This events * will be dispatched with touch event types. * * (Note) Used target for the relatedTarget. Need to verify if * it has a side effect. */ customEvent = Y.config.doc.createEvent("MouseEvents"); customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, 0, target); customEvent.touches = touches; customEvent.targetTouches = targetTouches; customEvent.changedTouches = changedTouches; } else { customEvent = Y.config.doc.createEvent("TouchEvent"); // Andoroid isn't compliant W3C initTouchEvent method signature. customEvent.initTouchEvent(touches, targetTouches, changedTouches, type, view, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey); } } else if (Y.UA.ios) { if(Y.UA.ios >= 2.0) { customEvent = Y.config.doc.createEvent("TouchEvent"); // Available iOS 2.0 and later customEvent.initTouchEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, touches, targetTouches, changedTouches, scale, rotation); } else { Y.error('simulateTouchEvent(): No touch event simulation framework present for iOS, '+Y.UA.ios+'.'); } } else { Y.error('simulateTouchEvent(): Not supported agent yet, '+Y.UA.userAgent); } //fire the event target.dispatchEvent(customEvent); //} else if (Y.Lang.isObject(doc.createEventObject)){ // Windows Mobile/IE, support later } else { Y.error('simulateTouchEvent(): No event simulation framework present.'); } } /** * Simulates the event or gesture with the given name on a target. * @param {HTMLElement} target The DOM element that's the target of the event. * @param {String} type The type of event or name of the supported gesture to simulate * (i.e., "click", "doubletap", "flick"). * @param {Object} options (Optional) Extra options to copy onto the event object. * For gestures, options are used to refine the gesture behavior. * @return {void} * @for Event * @method simulate * @static */ Y.Event.simulate = function(target, type, options){ options = options || {}; if (mouseEvents[type] || msPointerEvents[type]){ simulateMouseEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget); } else if (keyEvents[type]){ simulateKeyEvent(target, type, options.bubbles, options.cancelable, options.view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode); } else if (uiEvents[type]){ simulateUIEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail); // touch low-level event simulation } else if (touchEvents[type]) { if((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.phantomjs) && !(Y.UA.chrome && Y.UA.chrome < 6)) { simulateTouchEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.touches, options.targetTouches, options.changedTouches, options.scale, options.rotation); } else { Y.error("simulate(): Event '" + type + "' can't be simulated. Use gesture-simulate module instead."); } // ios gesture low-level event simulation (iOS v2+ only) } else if(Y.UA.ios && Y.UA.ios >= 2.0 && gestureEvents[type]) { simulateGestureEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.scale, options.rotation); // anything else } else { Y.error("simulate(): Event '" + type + "' can't be simulated."); } }; })(); }, 'patched-v3.11.0', {"requires": ["event-base"]});
FuadEfendi/lpotal
tomcat-7.0.57/webapps/ROOT/html/js/aui/event-simulate/event-simulate.js
JavaScript
lgpl-2.1
37,238
// // DockObject.cs // // Author: // Lluis Sanchez Gual // // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using Gtk; using System.Globalization; namespace MonoDevelop.Components.Docking { internal abstract class DockObject { public event EventHandler<EventArgs> AllocationChanged; DockGroup parentGroup; DockFrame frame; Gdk.Rectangle rect; // The current size in pixels of this item double size = -1; // The current size in pixels of this item, but as an integer. // In general it is the same value as size, but it may change a bit due to rounding. int allocSize = -1; double defaultHorSize = -1; double defaultVerSize = -1; double prefSize = 0; // Those are the last known coordinates of the item. They are stored in StoreAllocation // and restored to rect in RestoreAllocation. This is needed for example when a layout // is cloned. It is convenient to have allocation information in the cloned layout, even // if the layout has never been displayed (e.g., to decide the autohide dock location) int ax=-1, ay=-1; public DockObject (DockFrame frame) { this.frame = frame; } internal DockGroup ParentGroup { get { return parentGroup; } set { parentGroup = value; if (size < 0) size = prefSize = DefaultSize; } } public double Size { get { return size; } set { size = value; } } public bool HasAllocatedSize { get { return allocSize != -1; } } public double DefaultSize { get { if (defaultHorSize < 0) InitDefaultSizes (); if (parentGroup != null) { if (parentGroup.Type == DockGroupType.Horizontal) return defaultHorSize; else if (parentGroup.Type == DockGroupType.Vertical) return defaultVerSize; } return 0; } set { if (parentGroup != null) { if (parentGroup.Type == DockGroupType.Horizontal) defaultHorSize = value; else if (parentGroup.Type == DockGroupType.Vertical) defaultVerSize = value; } } } public DockVisualStyle VisualStyle { get; set; } internal void ResetDefaultSize () { defaultHorSize = -1; defaultVerSize = -1; } public int MinSize { get { int w,h; GetMinSize (out w, out h); if (parentGroup != null) { if (parentGroup.Type == DockGroupType.Horizontal) return w; else if (parentGroup.Type == DockGroupType.Vertical) return h; } return w; } } public abstract bool Expand { get; } public virtual void SizeAllocate (Gdk.Rectangle rect) { this.rect = rect; } internal Gdk.Rectangle Allocation { get { return rect; } set { rect = value; } } public int AllocSize { get { return allocSize; } set { allocSize = value; OnAllocationChanged (); } } public MonoDevelop.Components.Docking.DockFrame Frame { get { return frame; } } public double PrefSize { get { return prefSize; } set { prefSize = value; } } void InitDefaultSizes () { int width, height; GetDefaultSize (out width, out height); if (width == -1) width = frame.DefaultItemWidth; if (height == -1) height = frame.DefaultItemHeight; defaultHorSize = (double) width; defaultVerSize = (double) height; } internal virtual void GetDefaultSize (out int width, out int height) { width = -1; height = -1; } internal virtual void GetMinSize (out int width, out int height) { width = 0; height = 0; } internal abstract void QueueResize (); internal abstract bool GetDockTarget (DockItem item, int px, int py, out DockDelegate dockDelegate, out Gdk.Rectangle rect); internal abstract Gtk.Requisition SizeRequest (); internal abstract bool Visible { get; } internal abstract void Dump (int ind); internal virtual void RestoreAllocation () { if (parentGroup != null) { int x = ax != -1 ? ax : 0; int y = ay != -1 ? ay : 0; if (parentGroup.Type == DockGroupType.Horizontal) rect = new Gdk.Rectangle (x, y, (int)size, parentGroup.Allocation.Height); else if (parentGroup.Type == DockGroupType.Vertical) rect = new Gdk.Rectangle (x, y, parentGroup.Allocation.Width, (int)size); } } internal virtual void StoreAllocation () { if (Visible) { if (parentGroup == null || parentGroup.Type == DockGroupType.Horizontal) size = prefSize = (int) rect.Width; else if (parentGroup.Type == DockGroupType.Vertical) size = prefSize = (int) rect.Height; ax = Allocation.X; ay = Allocation.Y; } } internal virtual void Write (XmlWriter writer) { writer.WriteAttributeString ("size", size.ToString (CultureInfo.InvariantCulture)); writer.WriteAttributeString ("prefSize", prefSize.ToString (CultureInfo.InvariantCulture)); writer.WriteAttributeString ("defaultHorSize", defaultHorSize.ToString (CultureInfo.InvariantCulture)); writer.WriteAttributeString ("defaultVerSize", defaultVerSize.ToString (CultureInfo.InvariantCulture)); } internal virtual void Read (XmlReader reader) { size = double.Parse (reader.GetAttribute ("size"), CultureInfo.InvariantCulture); prefSize = double.Parse (reader.GetAttribute ("prefSize"), CultureInfo.InvariantCulture); defaultHorSize = double.Parse (reader.GetAttribute ("defaultHorSize"), CultureInfo.InvariantCulture); defaultVerSize = double.Parse (reader.GetAttribute ("defaultVerSize"), CultureInfo.InvariantCulture); } public virtual void CopyFrom (DockObject ob) { parentGroup = null; frame = ob.frame; rect = ob.rect; size = ob.size; allocSize = ob.allocSize; defaultHorSize = ob.defaultHorSize; defaultVerSize = ob.defaultVerSize; prefSize = ob.prefSize; } public DockObject Clone () { DockObject ob = (DockObject) this.MemberwiseClone (); ob.CopyFrom (this); return ob; } public virtual void CopySizeFrom (DockObject obj) { size = obj.size; allocSize = obj.allocSize; defaultHorSize = obj.defaultHorSize; defaultVerSize = obj.defaultVerSize; prefSize = obj.prefSize; } public virtual bool IsNextToMargin (Gtk.PositionType margin, bool visibleOnly) { if (ParentGroup == null) return true; if (!ParentGroup.IsNextToMargin (margin, visibleOnly)) return false; return ParentGroup.IsChildNextToMargin (margin, this, visibleOnly); } protected void OnAllocationChanged () { if (ParentGroup != null) { ParentGroup.OnAllocationChanged (); } else { AllocationChanged?.Invoke (this, EventArgs.Empty); } } } }
mono/linux-packaging-monodevelop
src/core/MonoDevelop.Ide/MonoDevelop.Components.Docking/DockObject.cs
C#
lgpl-2.1
7,753
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace Gst.WebRTC { using System; using System.Runtime.InteropServices; #region Autogenerated code [GLib.GType (typeof (Gst.WebRTC.WebRTCFECTypeGType))] public enum WebRTCFECType { None = 0, UlpRed = 1, } internal class WebRTCFECTypeGType { [DllImport ("gstwebrtc-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gst_webrtc_fec_type_get_type (); public static GLib.GType GType { get { return new GLib.GType (gst_webrtc_fec_type_get_type ()); } } } #endregion }
gstreamer-sharp/gstreamer-sharp
sources/generated/Gst.WebRTC/WebRTCFECType.cs
C#
lgpl-2.1
633
/* $Id$ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ using System; namespace Wombat { /// <summary> /// A class that represents a single option contract. Instances of /// this object are typically created by the MamdaOptionChainListener. /// Applications may attach a custom object to each instance of /// MamdaOptionContract. /// </summary> /// <remarks> /// Note: User applications can be notified of creation of /// MamdaOptionContract instances via the /// MamdaOptionChainListener.onOptionContractCreate() method. /// </remarks> public class MamdaOptionContract { public enum PutOrCall : byte { Unknown = (byte)'Z', Call = (byte)'C', Put = (byte)'P' } public enum ExerciseStyle : byte { Unknown = (byte)'Z', American = (byte)'A', European = (byte)'E', Capped = (byte)'C' } private MamdaOptionContract() { // Hide the default constructor. } /// <summary> /// Constructor from expiration date, strike price, and put/call /// indicator. /// </summary> /// <param name="symbol"></param> /// <param name="exchange"></param> /// <param name="expireDate"></param> /// <param name="strikePrice"></param> /// <param name="putCall"></param> public MamdaOptionContract( string symbol, string exchange, DateTime expireDate, double strikePrice, PutOrCall putCall) { mSymbol = symbol; mExchange = exchange; mExpireDate = expireDate; mStrikePrice = strikePrice; mPutCall = putCall; } /// <summary> /// Set the open interest size. /// </summary> /// <param name="openInterest"></param> public void setOpenInterest(long openInterest) { mOpenInterest = openInterest; } /// <summary> /// Set the exercise style. /// </summary> /// <param name="exerciseStyle"></param> public void setExerciseStyle(ExerciseStyle exerciseStyle) { mExerciseStyle = exerciseStyle; } /// <summary> /// Return the OPRA contract symbol. /// </summary> /// <returns></returns> public string getSymbol() { return mSymbol; } /// <summary> /// Return the exchange. /// </summary> /// <returns></returns> public string getExchange() { return mExchange; } /// <summary> /// Return the expiration date. /// </summary> /// <returns></returns> public DateTime getExpireDate() { return mExpireDate; } /// <summary> /// Return the expiration date as a commonly formatted string (MMyy). /// </summary> /// <returns></returns> public string getExpireDateStr() { return mExpireFormat.Format(mExpireDate); } /// <summary> /// Return the strike price. /// </summary> /// <returns></returns> public double getStrikePrice() { return mStrikePrice; } /// <summary> /// Return the put/call indicator. /// </summary> /// <returns></returns> public PutOrCall getPutCall() { return mPutCall; } /// <summary> /// Return the open interest. /// </summary> /// <returns></returns> public long getOpenInterest() { return mOpenInterest; } /// <summary> /// Return the exercise style. /// </summary> /// <returns></returns> public ExerciseStyle getExerciseStyle() { return mExerciseStyle; } /// <summary> /// Add a MamdaTradeHandler for handling trade updates to this option contract. /// </summary> /// <param name="handler"></param> public void addTradeHandler(MamdaTradeHandler handler) { mTradeListener.addHandler(handler); } /// <summary> /// Add a MamdaQuoteHandler for handling quote updates to this /// option contract. /// </summary> /// <param name="handler"></param> public void addQuoteHandler(MamdaQuoteHandler handler) { mQuoteListener.addHandler(handler); } /// <summary> /// Add a MamdaFundamentalHandler for handling fundamental updates /// to this option contract. /// </summary> /// <param name="handler"></param> public void addFundamentalHandler(MamdaFundamentalHandler handler) { mFundamentalListeners.addHandler(handler); } /// <summary> /// Add a custom object to this option contract. Such an object /// might contain customer per-contract data. /// </summary> /// <param name="obj"></param> public void setCustomObject(object obj) { mCustomObject = obj; } /// <summary> /// Return the current trade fields. /// </summary> /// <returns></returns> public MamdaTradeRecap getTradeInfo() { return mTradeListener; } /// <summary> /// Return the current quote fields. /// </summary> /// <returns></returns> public MamdaQuoteRecap getQuoteInfo() { return mQuoteListener; } /// <summary> /// Return the current fundamental fields. /// </summary> /// <returns></returns> public MamdaFundamentals getFundamentalsInfo() { return mFundamentalListeners; } /// <summary> /// Return the custom object. /// </summary> /// <returns></returns> public object getCustomObject() { return mCustomObject; } /// <summary> /// Return the trade listener. /// </summary> /// <returns></returns> public MamdaTradeListener getTradeListener() { return mTradeListener; } /// <summary> /// Return the current quote listener. /// </summary> /// <returns></returns> public MamdaQuoteListener getQuoteListener() { return mQuoteListener; } /// <summary> /// Return the current fundamental listener. /// </summary> /// <returns></returns> public MamdaFundamentalListener getFundamentalListener() { return mFundamentalListeners; } /// <summary> /// Set whether this contract is in the "view" within the option /// chain. /// <see cref="MamdaOptionChain"/> /// </summary> /// <param name="inView"></param> public void setInView(bool inView) { mInView = inView; } /// <summary> /// Return whether this contract is in the "view" within the option /// chain. /// <see cref="MamdaOptionChain"/> /// </summary> /// <returns></returns> public bool getInView() { return mInView; } private string mSymbol; private string mExchange; private DateTime mExpireDate = DateTime.MinValue; private double mStrikePrice = 0.0; private PutOrCall mPutCall = PutOrCall.Unknown; private long mOpenInterest; private ExerciseStyle mExerciseStyle; private bool mInScope; private MamdaTradeListener mTradeListener = new MamdaTradeListener(); private MamdaQuoteListener mQuoteListener = new MamdaQuoteListener(); private MamdaFundamentalListener mFundamentalListeners = new MamdaFundamentalListener(); private object mCustomObject; private bool mInView; private SimpleDateFormat mExpireFormat = new SimpleDateFormat("MMMyy"); } }
philippreston/OpenMAMA
mamda/dotnet/src/cs/Options/MamdaOptionContract.cs
C#
lgpl-2.1
7,728
// IFC SDK : IFC2X3 C++ Early Classes // Copyright (C) 2009 CSTB // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full license is in Licence.txt file included with this // distribution or is available at : // http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. #include <ifc2x3/IfcElementType.h> #include <ifc2x3/CopyOp.h> #include <ifc2x3/IfcTypeProduct.h> #include <ifc2x3/Visitor.h> #include <Step/BaseObject.h> #include <Step/ClassType.h> #include <Step/String.h> #include <string> #include "precompiled.h" using namespace ifc2x3; IfcElementType::IfcElementType(Step::Id id, Step::SPFData *args) : IfcTypeProduct(id, args) { m_elementType = Step::getUnset(m_elementType); } IfcElementType::~IfcElementType() { } bool IfcElementType::acceptVisitor(Step::BaseVisitor *visitor) { return static_cast< Visitor * > (visitor)->visitIfcElementType(this); } const std::string &IfcElementType::type() const { return IfcElementType::s_type.getName(); } const Step::ClassType &IfcElementType::getClassType() { return IfcElementType::s_type; } const Step::ClassType &IfcElementType::getType() const { return IfcElementType::s_type; } bool IfcElementType::isOfType(const Step::ClassType &t) const { return IfcElementType::s_type == t ? true : IfcTypeProduct::isOfType(t); } IfcLabel IfcElementType::getElementType() { if (Step::BaseObject::inited()) { return m_elementType; } else { return Step::getUnset(m_elementType); } } const IfcLabel IfcElementType::getElementType() const { IfcElementType * deConstObject = const_cast< IfcElementType * > (this); return deConstObject->getElementType(); } void IfcElementType::setElementType(const IfcLabel &value) { m_elementType = value; } void IfcElementType::unsetElementType() { m_elementType = Step::getUnset(getElementType()); } bool IfcElementType::testElementType() const { return !Step::isUnset(getElementType()); } bool IfcElementType::init() { bool status = IfcTypeProduct::init(); std::string arg; if (!status) { return false; } arg = m_args->getNext(); if (arg == "$" || arg == "*") { m_elementType = Step::getUnset(m_elementType); } else { m_elementType = Step::String::fromSPF(arg); } return true; } void IfcElementType::copy(const IfcElementType &obj, const CopyOp &copyop) { IfcTypeProduct::copy(obj, copyop); setElementType(obj.m_elementType); return; } IFC2X3_EXPORT Step::ClassType IfcElementType::s_type("IfcElementType");
cstb/ifc2x3-SDK
src/ifc2x3/IfcElementType.cpp
C++
lgpl-2.1
3,037
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.server.registry; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.context.Flag; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.filter.KeyFilter; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.remoting.transport.Address; import org.jboss.as.clustering.logging.ClusteringLogger; import org.jboss.threads.JBossThreadFactory; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.group.Group; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.group.NodeFactory; import org.wildfly.clustering.registry.Registry; import org.wildfly.clustering.server.logging.ClusteringServerLogger; import org.wildfly.clustering.service.concurrent.ClassLoaderThreadFactory; import org.wildfly.security.manager.WildFlySecurityManager; /** * Clustered {@link Registry} backed by an Infinispan cache. * @author Paul Ferraro * @param <K> key type * @param <V> value type */ @org.infinispan.notifications.Listener public class CacheRegistry<K, V> implements Registry<K, V>, KeyFilter<Object> { private static ThreadFactory createThreadFactory(Class<?> targetClass) { PrivilegedAction<ThreadFactory> action = () -> new JBossThreadFactory(new ThreadGroup(targetClass.getSimpleName()), Boolean.FALSE, null, "%G - %t", null, null); return new ClassLoaderThreadFactory(WildFlySecurityManager.doUnchecked(action), AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> targetClass.getClassLoader())); } private final ExecutorService topologyChangeExecutor = Executors.newSingleThreadExecutor(createThreadFactory(this.getClass())); private final Map<Registry.Listener<K, V>, ExecutorService> listeners = new ConcurrentHashMap<>(); private final Cache<Node, Map.Entry<K, V>> cache; private final Batcher<? extends Batch> batcher; private final Group group; private final NodeFactory<Address> factory; private final Runnable closeTask; private final Map.Entry<K, V> entry; public CacheRegistry(CacheRegistryConfiguration<K, V> config, Map.Entry<K, V> entry, Runnable closeTask) { this.cache = config.getCache(); this.batcher = config.getBatcher(); this.group = config.getGroup(); this.factory = config.getNodeFactory(); this.closeTask = closeTask; this.entry = new AbstractMap.SimpleImmutableEntry<>(entry); this.populateRegistry(); this.cache.addListener(this, new CacheRegistryFilter()); } private void populateRegistry() { try (Batch batch = this.batcher.createBatch()) { this.cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(this.group.getLocalNode(), this.entry); } } @Override public boolean accept(Object key) { return key instanceof Node; } @Override public void close() { this.cache.removeListener(this); this.shutdown(this.topologyChangeExecutor); Node node = this.getGroup().getLocalNode(); try (Batch batch = this.batcher.createBatch()) { // If this remove fails, the entry will be auto-removed on topology change by the new primary owner this.cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FAIL_SILENTLY).remove(node); } catch (CacheException e) { ClusteringLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); } finally { // Cleanup any unregistered listeners this.listeners.values().forEach(executor -> this.shutdown(executor)); this.listeners.clear(); this.closeTask.run(); } } @Override public void addListener(Registry.Listener<K, V> listener) { this.listeners.computeIfAbsent(listener, key -> Executors.newSingleThreadExecutor(createThreadFactory(listener.getClass()))); } @Override public void removeListener(Registry.Listener<K, V> listener) { ExecutorService executor = this.listeners.remove(listener); if (executor != null) { this.shutdown(executor); } } @Override public Group getGroup() { return this.group; } @Override public Map<K, V> getEntries() { Set<Node> nodes = this.group.getNodes().stream().collect(Collectors.toSet()); try (Batch batch = this.batcher.createBatch()) { return this.cache.getAdvancedCache().getAll(nodes).values().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); } } @Override public Map.Entry<K, V> getEntry(Node node) { try (Batch batch = this.batcher.createBatch()) { return this.cache.get(node); } } @TopologyChanged public void topologyChanged(TopologyChangedEvent<Node, Map.Entry<K, V>> event) { if (event.isPre()) return; ConsistentHash previousHash = event.getConsistentHashAtStart(); List<Address> previousMembers = previousHash.getMembers(); ConsistentHash hash = event.getConsistentHashAtEnd(); List<Address> members = hash.getMembers(); Address localAddress = event.getCache().getCacheManager().getAddress(); // Determine which nodes have left the cache view Set<Address> addresses = new HashSet<>(previousMembers); addresses.removeAll(members); try { this.topologyChangeExecutor.submit(() -> { if (!addresses.isEmpty()) { // We're only interested in the entries for which we are the primary owner List<Node> nodes = addresses.stream().filter(address -> hash.locatePrimaryOwner(address).equals(localAddress)).map(address -> this.factory.createNode(address)).collect(Collectors.toList()); if (!nodes.isEmpty()) { Cache<Node, Map.Entry<K, V>> cache = this.cache.getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS); Map<K, V> removed = new HashMap<>(); try (Batch batch = this.batcher.createBatch()) { for (Node node: nodes) { Map.Entry<K, V> old = cache.remove(node); if (old != null) { removed.put(old.getKey(), old.getValue()); } } } catch (CacheException e) { ClusteringServerLogger.ROOT_LOGGER.registryPurgeFailed(e, this.cache.getCacheManager().toString(), this.cache.getName(), nodes); } // Invoke listeners outside above tx context if (!removed.isEmpty()) { this.notifyListeners(Event.Type.CACHE_ENTRY_REMOVED, removed); } } } else { // This is a merge after cluster split: re-populate the cache registry with lost registry entries if (!previousMembers.contains(localAddress)) { // If this node is not a member at merge start, its mapping is lost and needs to be recreated and listeners notified try { this.populateRegistry(); // Local cache events do not trigger notifications this.notifyListeners(Event.Type.CACHE_ENTRY_CREATED, this.entry); } catch (CacheException e) { ClusteringServerLogger.ROOT_LOGGER.failedToRestoreLocalRegistryEntry(e, this.cache.getCacheManager().toString(), this.cache.getName()); } } } }); } catch (RejectedExecutionException e) { // Executor was shutdown } } @CacheEntryCreated @CacheEntryModified public void event(CacheEntryEvent<Node, Map.Entry<K, V>> event) { if (event.isOriginLocal() || event.isPre()) return; if (!this.listeners.isEmpty()) { Map.Entry<K, V> entry = event.getValue(); if (entry != null) { this.notifyListeners(event.getType(), entry); } } } @CacheEntryRemoved public void removed(CacheEntryRemovedEvent<Node, Map.Entry<K, V>> event) { if (event.isOriginLocal() || event.isPre()) return; if (!this.listeners.isEmpty()) { Map.Entry<K, V> entry = event.getOldValue(); // WFLY-4938 For some reason, the old value can be null if (entry != null) { this.notifyListeners(event.getType(), entry); } } } private void notifyListeners(Event.Type type, Map.Entry<K, V> entry) { this.notifyListeners(type, Collections.singletonMap(entry.getKey(), entry.getValue())); } private void notifyListeners(Event.Type type, Map<K, V> entries) { for (Map.Entry<Listener<K, V>, ExecutorService> entry: this.listeners.entrySet()) { Listener<K, V> listener = entry.getKey(); ExecutorService executor = entry.getValue(); try { executor.submit(() -> { try { switch (type) { case CACHE_ENTRY_CREATED: { listener.addedEntries(entries); break; } case CACHE_ENTRY_MODIFIED: { listener.updatedEntries(entries); break; } case CACHE_ENTRY_REMOVED: { listener.removedEntries(entries); break; } default: { throw new IllegalStateException(type.name()); } } } catch (Throwable e) { ClusteringServerLogger.ROOT_LOGGER.registryListenerFailed(e, this.cache.getCacheManager().getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName(), this.cache.getName(), type, entries); } }); } catch (RejectedExecutionException e) { // Executor was shutdown } } } private void shutdown(ExecutorService executor) { PrivilegedAction<List<Runnable>> action = () -> executor.shutdownNow(); WildFlySecurityManager.doUnchecked(action); try { executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
tomazzupan/wildfly
clustering/server/src/main/java/org/wildfly/clustering/server/registry/CacheRegistry.java
Java
lgpl-2.1
13,247
var searchData= [ ['takeoff',['takeOff',['../class_flight_controller.html#a514f2619b98216e9fca0ad876d000966',1,'FlightController']]] ];
cranktec/EasyCopter
documentation/html/search/functions_a.js
JavaScript
lgpl-2.1
138
/** * Copyright notice * * This file is part of the Processing library `gwoptics' * http://www.gwoptics.org/processing/gwoptics_p5lib/ * * Copyright (C) 2009 onwards Daniel Brown and Andreas Freise * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 2.1 as published * by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.gwoptics.graphics.graph2D.traces; import org.gwoptics.graphics.IRenderable; import org.gwoptics.graphics.graph2D.IGraph2D; import org.gwoptics.graphics.graph2D.effects.ITraceColourEffect; /** * <p> This interface provides the functionality that is required of a trace * object, to be used by the Graph2D control. </p> <p> Classes implementing this * interface should be programmed for efficiency, as they are called many times * per draw loop. The intended way to work is to store the points of the line in * an internal array. When the draw() method is called from the IRenderable * interface the method should use the array for plotting the trace. Usually the * trace will not change so it is unnescessary to recalculate the equations * everytime. </p> <p> Traces also have the option of having an * ITraceColourEffect applied to it. The draw() method should use this effect * object to determine the colour of the trace at given points. </p> * * @author Daniel Brown 13/7/09 * @since 0.4.0 * @see ITraceColourEffect * @see ILine2DEquation */ public interface IGraph2DTrace extends IRenderable { /** * Sets an internal variable to store a reference to the graph object the * trace is being plotted on */ void setGraph(IGraph2D grp); /** * This is called everytime the equation callback object is changed. */ void generate(); /** * alters the initial position of the trace on the graph */ void setPosition(int x, int y); /** * <p> Before the trace is added to the graph control this method is called. * It allows a trace to check the settings of other traces that have * previously been added for in Compatibilities. Leave method empty in * implementation if no checks are necessary. </p> <p>w onAddTrace is called * from with a synchronised lock so the traces object won't be modified whilst * reading it. Therefore it is not necessary to provide custom thread locks. * </p> */ void onAddTrace(Object traces[]); /** * <p> Before the trace is officially removed from the trace list of a Graph2D * object, the onRemove method is called. This allows the trace object to * provide any cleanup needed, if at all needed. Leave blank if nothing is * needed. * </p> */ void onRemoveTrace(); }
gwoptics/gwoptics_plib
src/org/gwoptics/graphics/graph2D/traces/IGraph2DTrace.java
Java
lgpl-2.1
3,265
/* FeatureAlgorithm.cpp */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* */ /* Copyright (C) 2007 Open Microscopy Environment */ /* Massachusetts Institue of Technology, */ /* National Institutes of Health, */ /* University of Dundee */ /* */ /* */ /* */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* Written by: */ /* Christopher E. Coletta <colettace [at] mail [dot] nih [dot] gov> */ /* Ilya G. Goldberg <goldbergil [at] mail [dot] nih [dot] gov> */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include "FeatureNames.h" #include "FeatureAlgorithms.h" #include "cmatrix.h" #include <iostream> #include <cstdlib> #include <cmath> //start #including the functions directly once you start pulling them out of cmatrix //#include "transforms/Chebyshev.h" /* global variable */ extern int verbosity; void FeatureAlgorithm::print_info() const { std::cout << typeLabel() << " '" << name << "' (" << n_features << " features) " << std::endl; } bool FeatureAlgorithm::register_task() const { return (FeatureNames::registerFeatureAlgorithm (this)); } //=========================================================================== ChebyshevFourierCoefficients::ChebyshevFourierCoefficients() : FeatureAlgorithm ("Chebyshev-Fourier Coefficients", 32) { // cout << "Instantiating new " << name << " object." << endl; } std::vector<double> ChebyshevFourierCoefficients::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.ChebyshevFourierTransform2D(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool ChebyshevFourierCoefficientsReg = ComputationTaskInstances::add (new ChebyshevFourierCoefficients); //=========================================================================== ChebyshevCoefficients::ChebyshevCoefficients() : FeatureAlgorithm ("Chebyshev Coefficients", 32) { // cout << "Instantiating new " << name << " object." << endl; } /** * Chebyshev Coefficients are calculated by performing a Chebyshev transform, * and generating a histogram of pixel intensities. * */ std::vector<double> ChebyshevCoefficients::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.ChebyshevStatistics2D(coeffs.data(), 0, 32); return coeffs; } // Register a static instance of the class using a global bool static bool ChebyshevCoefficientsReg = ComputationTaskInstances::add (new ChebyshevCoefficients); //=========================================================================== ZernikeCoefficients::ZernikeCoefficients() : FeatureAlgorithm ("Zernike Coefficients", 72) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> ZernikeCoefficients::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); long output_size; // output size is normally 72 IN_matrix.zernike2D(coeffs.data(), &output_size); return coeffs; } // Register a static instance of the class using a global bool static bool ZernikeCoefficientsReg = ComputationTaskInstances::add (new ZernikeCoefficients); //=========================================================================== HaralickTextures::HaralickTextures() : FeatureAlgorithm ("Haralick Textures", 28) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> HaralickTextures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.HaralickTexture2D(0,coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool HaralickTexturesReg = ComputationTaskInstances::add (new HaralickTextures); //=========================================================================== MultiscaleHistograms::MultiscaleHistograms() : FeatureAlgorithm ("Multiscale Histograms", 24) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> MultiscaleHistograms::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.MultiScaleHistogram(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool MultiscaleHistogramsReg = ComputationTaskInstances::add (new MultiscaleHistograms); //=========================================================================== TamuraTextures::TamuraTextures() : FeatureAlgorithm ("Tamura Textures", 6) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> TamuraTextures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.TamuraTexture2D(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool TamuraTexturesReg = ComputationTaskInstances::add (new TamuraTextures); //=========================================================================== CombFirstFourMoments::CombFirstFourMoments() : FeatureAlgorithm ("Comb Moments", 48) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> CombFirstFourMoments::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.CombFirstFourMoments2D(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool CombFirstFourMomentsReg = ComputationTaskInstances::add (new CombFirstFourMoments); //=========================================================================== RadonCoefficients::RadonCoefficients() : FeatureAlgorithm ("Radon Coefficients", 12) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> RadonCoefficients::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.RadonTransform2D(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool RadonCoefficientsReg = ComputationTaskInstances::add (new RadonCoefficients); //=========================================================================== /* fractal brownian fractal analysis bins - the maximal order of the fractal output - array of the size k the code is based on: CM Wu, YC Chen and KS Hsieh, Texture features for classification of ultrasonic liver images, IEEE Trans Med Imag 11 (1992) (2), pp. 141Ð152. method of approaximation of CC Chen, JS Daponte and MD Fox, Fractal feature analysis and classification in medical imaging, IEEE Trans Med Imag 8 (1989) (2), pp. 133Ð142. */ FractalFeatures::FractalFeatures() : FeatureAlgorithm ("Fractal Features", 20) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> FractalFeatures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); int bins = n_features; int width = IN_matrix.width; int height = IN_matrix.height; readOnlyPixels IN_matrix_pix_plane = IN_matrix.ReadablePixels(); int x, y, k, bin = 0; int K = ( ( width > height ) ? height : width) / 5; // MIN int step = (int) floor ( K / bins ); if( step < 1 ) step = 1; // avoid an infinite loop if the image is small for( k = 1; k < K; k = k + step ) { double sum = 0.0; for( x = 0; x < width; x++ ) for( y = 0; y < height - k; y++ ) sum += fabs( IN_matrix_pix_plane(y,x) - IN_matrix_pix_plane(y+k,x) ); for( x = 0; x < width - k; x++ ) for( y = 0; y < height; y++ ) sum += fabs( IN_matrix_pix_plane(y,x) - IN_matrix_pix_plane(y,x + k) ); if( bin < bins ) coeffs[ bin++ ] = sum / ( width * ( width - k ) + height * ( height - k ) ); } return coeffs; } // Register a static instance of the class using a global bool static bool FractalFeaturesReg = ComputationTaskInstances::add (new FractalFeatures); //=========================================================================== PixelIntensityStatistics::PixelIntensityStatistics() : FeatureAlgorithm ("Pixel Intensity Statistics", 5) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> PixelIntensityStatistics::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); Moments2 stats; IN_matrix.GetStats (stats); coeffs[0] = stats.mean(); coeffs[1] = IN_matrix.get_median(); coeffs[2] = stats.std(); coeffs[3] = stats.min(); coeffs[4] = stats.max(); return coeffs; } // Register a static instance of the class using a global bool static bool PixelIntensityStatisticsReg = ComputationTaskInstances::add (new PixelIntensityStatistics); //=========================================================================== EdgeFeatures::EdgeFeatures() : FeatureAlgorithm ("Edge Features", 28) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> EdgeFeatures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); unsigned long EdgeArea = 0; double MagMean=0, MagMedian=0, MagVar=0, MagHist[8]={0,0,0,0,0,0,0,0}, DirecMean=0, DirecMedian=0, DirecVar=0, DirecHist[8]={0,0,0,0,0,0,0,0}, DirecHomogeneity=0, DiffDirecHist[4]={0,0,0,0}; IN_matrix.EdgeStatistics(&EdgeArea, &MagMean, &MagMedian, &MagVar, MagHist, &DirecMean, &DirecMedian, &DirecVar, DirecHist, &DirecHomogeneity, DiffDirecHist, 8); int j, here = 0; coeffs[here++] = double( EdgeArea ); for( j=0; j<4; j++ ){ coeffs[here++] = DiffDirecHist[j]; } for( j=0; j<8; j++ ){ coeffs[here++] = DirecHist[j]; } coeffs[here++] = DirecHomogeneity; coeffs[here++] = DirecMean; coeffs[here++] = DirecMedian; coeffs[here++] = DirecVar; for( j=0; j<8; j++ ){ coeffs[here++] = MagHist[j]; } coeffs[here++] = MagMean; coeffs[here++] = MagMedian; coeffs[here++] = MagVar; return coeffs; } // Register a static instance of the class using a global bool static bool EdgeFeaturesReg = ComputationTaskInstances::add (new EdgeFeatures); //=========================================================================== ObjectFeatures::ObjectFeatures() : FeatureAlgorithm ("Otsu Object Features", 34) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> ObjectFeatures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); unsigned long feature_count=0, AreaMin=0, AreaMax=0; long Euler=0; unsigned int AreaMedian=0, area_histogram[10]={0,0,0,0,0,0,0,0,0,0}, dist_histogram[10]={0,0,0,0,0,0,0,0,0,0}; double centroid_x=0, centroid_y=0, AreaMean=0, AreaVar=0, DistMin=0, DistMax=0, DistMean=0, DistMedian=0, DistVar=0; IN_matrix.FeatureStatistics(&feature_count, &Euler, &centroid_x, &centroid_y, &AreaMin, &AreaMax, &AreaMean, &AreaMedian, &AreaVar, area_histogram, &DistMin, &DistMax, &DistMean, &DistMedian, &DistVar, dist_histogram, 10); int j, here = 0; for( j = 0; j < 10; j++ ){ coeffs[here++] = area_histogram[j]; } coeffs[here++] = AreaMax; coeffs[here++] = AreaMean; coeffs[here++] = AreaMedian; coeffs[here++] = AreaMin; coeffs[here++] = AreaVar; coeffs[here++] = centroid_x; coeffs[here++] = centroid_y; coeffs[here++] = feature_count; for( j = 0; j < 10; j++ ) { coeffs[here++] = dist_histogram[j]; } coeffs[here++] = DistMax; coeffs[here++] = DistMean; coeffs[here++] = DistMedian; coeffs[here++] = DistMin; coeffs[here++] = DistVar; coeffs[here++] = Euler; return coeffs; } // Register a static instance of the class using a global bool static bool ObjectFeaturesReg = ComputationTaskInstances::add (new ObjectFeatures); //=========================================================================== InverseObjectFeatures::InverseObjectFeatures() : FeatureAlgorithm ("Inverse-Otsu Object Features", 34) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> InverseObjectFeatures::execute (const ImageMatrix &IN_matrix) const { ImageMatrix InvMatrix; InvMatrix.copy (IN_matrix); InvMatrix.invert(); static ObjectFeatures ObjFeaturesInst; return (ObjFeaturesInst.execute (InvMatrix)); } // Register a static instance of the class using a global bool static bool InverseObjectFeaturesReg = ComputationTaskInstances::add (new InverseObjectFeatures); //=========================================================================== GaborTextures::GaborTextures() : FeatureAlgorithm ("Gabor Textures", 7) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> GaborTextures::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize (n_features, 0); IN_matrix.GaborFilters2D(coeffs.data()); return coeffs; } // Register a static instance of the class using a global bool static bool GaborTexturesReg = ComputationTaskInstances::add (new GaborTextures); //=========================================================================== /* gini compute the gini coefficient paper reference: Roberto G. Abraham, Sidney van den Bergh, Preethi Nair, A NEW APPROACH TO GALAXY MORPHOLOGY. I. ANALYSIS OF THE SLOAN DIGITAL SKY SURVEY EARLY DATA RELEASE, The Astrophysical Journal, vol. 588, p. 218-229, 2003. */ GiniCoefficient::GiniCoefficient() : FeatureAlgorithm ("Gini Coefficient", 1) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> GiniCoefficient::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.resize(n_features, 0); long pixel_index, num_pixels; double *pixels, mean = 0.0, g = 0.0; long i, count = 0; double val; num_pixels = IN_matrix.height * IN_matrix.width; pixels = new double[ num_pixels ]; readOnlyPixels IN_matrix_pix_plane = IN_matrix.ReadablePixels(); for( pixel_index = 0; pixel_index < num_pixels; pixel_index++ ) { val = IN_matrix_pix_plane.array().coeff(pixel_index); if( val > 0 ) { pixels[ count ] = val; mean += val; count++; } } if( count > 0 ) mean = mean / count; qsort( pixels, count, sizeof(double), compare_doubles ); for( i = 1; i <= count; i++) g += (2. * i - count - 1.) * pixels[i-1]; delete [] pixels; if( count <= 1 || mean <= 0.0 ) coeffs[0] = 0.0; // avoid division by zero else coeffs[0] = g / ( mean * count * ( count-1 ) ); return coeffs; } // Register a static instance of the class using a global bool static bool GiniCoefficientReg = ComputationTaskInstances::add (new GiniCoefficient); //=========================================================================== /* Color Histogram compute the Color Histogram */ ColorHistogram::ColorHistogram() : FeatureAlgorithm ("Color Histogram", COLORS_NUM+1) { //cout << "Instantiating new " << name << " object." << endl; } std::vector<double> ColorHistogram::execute (const ImageMatrix &IN_matrix) const { std::vector<double> coeffs; if (verbosity > 3) std::cout << "calculating " << name << std::endl; coeffs.assign(n_features, 0); unsigned int x,y, width = IN_matrix.width, height = IN_matrix.height; HSVcolor hsv_pixel; unsigned long color_index=0; double certainties[COLORS_NUM+1]; readOnlyColors clr_plane = IN_matrix.ReadableColors(); // find the colors for( y = 0; y < height; y++ ) { for( x = 0; x < width; x++ ) { hsv_pixel = clr_plane (y, x); color_index = FindColor( hsv_pixel.h, hsv_pixel.s, hsv_pixel.v, certainties ); coeffs[ color_index ]++; } } /* normalize the color histogram */ for (color_index = 0; color_index <= COLORS_NUM; color_index++) coeffs[color_index] /= (width*height); return coeffs; } // Register a static instance of the class using a global bool static bool ColorHistogramReg = ComputationTaskInstances::add (new ColorHistogram);
chris-allan/pychrm
src/FeatureAlgorithms.cpp
C++
lgpl-2.1
18,945
///////////////////////////////////////////////////////////////////////////////// // // Multilayer Feature Graph (MFG), version 1.0 // Copyright (C) 2011-2015 Yan Lu, Dezhen Song // Netbot Laboratory, Texas A&M University, USA // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ///////////////////////////////////////////////////////////////////////////////// /******************************************************************************** * Estimate rotation/translation between two views ********************************************************************************/ #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> // replaced with: #ifdef __APPLE__ #include <GLUT/glut.h> #include <OpenGL/gl.h> #elif __linux__ #include <GL/glut.h> #include <GL/gl.h> #else #include <gl/glut.h> #include <gl/gl.h> #endif #include <math.h> #include <fstream> #include "utils.h" #include "consts.h" #include "mfgutils.h" #include "levmar.h" #include "view.h" #include "features2d.h" #include "features3d.h" using namespace std; struct Data_optimizeRt_withVP { vector<vector<cv::Point2d>> pointPairs; cv::Mat K; vector<vector<cv::Mat>> vpPairs; double weightVP; }; void costFun_optimizeRt_withVP(double *p, double *error, int N, int M, void *adata) // M measurement size // N para size { struct Data_optimizeRt_withVP *dptr = (struct Data_optimizeRt_withVP *) adata; Eigen::Quaterniond q(p[0], p[1], p[2], p[3]); q.normalize(); cv::Mat R = (cv::Mat_<double>(3, 3) << q.matrix()(0, 0), q.matrix()(0, 1), q.matrix()(0, 2), q.matrix()(1, 0), q.matrix()(1, 1), q.matrix()(1, 2), q.matrix()(2, 0), q.matrix()(2, 1), q.matrix()(2, 2)); double t_norm = sqrt(p[4] * p[4] + p[5] * p[5] + p[6] * p[6]); p[4] = p[4] / t_norm; p[5] = p[5] / t_norm; p[6] = p[6] / t_norm; cv::Mat t = (cv::Mat_<double>(3, 1) << p[4], p[5], p[6]); cv::Mat K = dptr->K; double weightVp = dptr->weightVP; double cost = 0; int errEndIdx = 0; cv::Mat F = K.t().inv() * (vec2SkewMat(t) * R) * K.inv(); for (int i = 0; i < dptr->pointPairs.size(); ++i, ++errEndIdx) { error[errEndIdx] = sqrt(fund_samperr(cvpt2mat(dptr->pointPairs[i][0]), cvpt2mat(dptr->pointPairs[i][1]), F)); cost += error[errEndIdx] * error[errEndIdx]; } for (int i = 0; i < dptr->vpPairs.size(); ++i, ++errEndIdx) { cv::Mat vp1 = K.inv() * dptr->vpPairs[i][0]; cv::Mat vp2 = R.t() * K.inv() * dptr->vpPairs[i][1]; vp1 = vp1 / cv::norm(vp1); vp2 = vp2 / cv::norm(vp2); error[errEndIdx] = cv::norm(vp1.cross(vp2)) * weightVp; cost = cost + error[errEndIdx] * error[errEndIdx]; } // cout<<cost<<'\t'; } void optimizeRt_withVP(cv::Mat K, vector<vector<cv::Mat>> vppairs, double weightVP, vector<vector<cv::Point2d>> &featPtMatches, cv::Mat R, cv::Mat t) // optimize relative pose (from 5-point alg) using vanishing point correspondences // input: K, vppairs, featPtMatches // output: R, t { int numMeasure = vppairs.size() + featPtMatches.size(); double *measurement = new double[numMeasure]; for (int i = 0; i < numMeasure; ++i) measurement[i] = 0; double opts[LM_OPTS_SZ], info[LM_INFO_SZ]; opts[0] = LM_INIT_MU; // opts[1] = 1E-15; opts[2] = 1E-50; // original 1e-50 opts[3] = 1E-20; opts[4] = -LM_DIFF_DELTA; int maxIter = 5000; Eigen::Matrix3d Rx; Rx << R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2), R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2), R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2); Eigen::Quaterniond q(Rx); int numPara = 7 ; double *para = new double[numPara]; para[0] = q.w(); para[1] = q.x(); para[2] = q.y(); para[3] = q.z(); para[4] = t.at<double>(0); para[5] = t.at<double>(1); para[6] = t.at<double>(2); // --- pass additional data --- Data_optimizeRt_withVP data; data.pointPairs = featPtMatches; data.K = K; data.vpPairs = vppairs; data.weightVP = weightVP; int ret = dlevmar_dif(costFun_optimizeRt_withVP, para, measurement, numPara, numMeasure, maxIter, opts, info, NULL, NULL, (void *)&data); delete[] measurement; q.w() = para[0]; q.x() = para[1]; q.y() = para[2]; q.z() = para[3]; q.normalize(); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) R.at<double>(i, j) = q.matrix()(i, j); t.at<double>(0) = para[4]; t.at<double>(1) = para[5]; t.at<double>(2) = para[6]; } struct Data_optimize_t_givenR { vector<vector<cv::Point2d>> pointPairs; cv::Mat K, R; }; void costFun_optimize_t_givenR(double *p, double *error, int N, int M, void *adata) // M measurement size // N para size { struct Data_optimize_t_givenR *dptr = (struct Data_optimize_t_givenR *) adata; cv::Mat R = dptr->R; double t_norm = sqrt(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]); p[0] = p[0] / t_norm; p[1] = p[1] / t_norm; p[2] = p[2] / t_norm; cv::Mat t = (cv::Mat_<double>(3, 1) << p[0], p[1], p[2]); cv::Mat K = dptr->K; double cost = 0; int errEndIdx = 0; cv::Mat F = K.t().inv() * (vec2SkewMat(t) * R) * K.inv(); for (int i = 0; i < dptr->pointPairs.size(); ++i, ++errEndIdx) { error[errEndIdx] = sqrt(fund_samperr(cvpt2mat(dptr->pointPairs[i][0]), cvpt2mat(dptr->pointPairs[i][1]), F)); cost += error[errEndIdx] * error[errEndIdx]; } cout << cost << '\t'; } void optimize_t_givenR(cv::Mat K, cv::Mat R, vector<vector<cv::Point2d>> &featPtMatches, cv::Mat t) // optimize relative pose (from 5-point alg) using vanishing point correspondences // input: K, R, vppairs, featPtMatches // output: t { int numMeasure = featPtMatches.size(); double *measurement = new double[numMeasure]; for (int i = 0; i < numMeasure; ++i) measurement[i] = 0; double opts[LM_OPTS_SZ], info[LM_INFO_SZ]; opts[0] = LM_INIT_MU; // opts[1] = 1E-15; opts[2] = 1E-50; // original 1e-50 opts[3] = 1E-20; opts[4] = -LM_DIFF_DELTA; int maxIter = 1000; int numPara = 3; double *para = new double[numPara]; para[0] = t.at<double>(0); para[1] = t.at<double>(1); para[2] = t.at<double>(2); // --- pass additional data --- Data_optimize_t_givenR data; data.pointPairs = featPtMatches; data.K = K; data.R = R; int ret = dlevmar_dif(costFun_optimize_t_givenR, para, measurement, numPara, numMeasure, maxIter, opts, info, NULL, NULL, (void *)&data); delete[] measurement; t.at<double>(0) = para[0]; t.at<double>(1) = para[1]; t.at<double>(2) = para[2]; }
chen0510566/MFG
src/mfgcore/twoview.cpp
C++
lgpl-3.0
7,585
/** * Kopernicus Planetary System Modifier * ==================================== * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis) * Maintained by: Thomas P., NathanKell and KillAshley * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace * ------------------------------------------------------------- * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * This library is intended to be used as a plugin for Kerbal Space Program * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program * itself is governed by the terms of its EULA, not the license above. * * https://kerbalspaceprogram.com */ using System.Collections.Generic; using UnityEngine; namespace Kopernicus { namespace Components { /// <summary> /// Class to render a ring around a planet /// </summary> public class Ring : MonoBehaviour { /// Settings public float innerRadius; public float outerRadius; public Quaternion rotation; public Texture2D texture; public Color color; public bool lockRotation; public bool unlit; public int steps = 128; /// <summary> /// Create the Ring Mesh /// </summary> void Start() { if (gameObject.GetComponent<MeshFilter>() == null) BuildRing(); } /// <summary> /// Builds the Ring /// </summary> public void BuildRing() { // Prepare GameObject parent = transform.parent.gameObject; List<Vector3> vertices = new List<Vector3>(); List<Vector2> Uvs = new List<Vector2>(); List<int> Tris = new List<int>(); List<Vector3> Normals = new List<Vector3>(); // Mesh wrapping for (float i = 0f; i < 360f; i += (360f / steps)) { // Rotation Vector3 eVert = Quaternion.Euler(0, i, 0) * Vector3.right; // Inner Radius vertices.Add(eVert * (innerRadius * (1f / parent.transform.localScale.x))); Normals.Add(Vector3.left); Uvs.Add(Vector2.one); // Outer Radius vertices.Add(eVert * (outerRadius * (1f / parent.transform.localScale.x))); Normals.Add(Vector3.left); Uvs.Add(Vector2.zero); } for (float i = 0f; i < 360f; i += (360f / steps)) { // Rotation Vector3 eVert = Quaternion.Euler(0, i, 0) * Vector3.right; // Inner Radius vertices.Add(eVert * (innerRadius * (1f / parent.transform.localScale.x))); Normals.Add(Vector3.left); Uvs.Add(Vector2.one); // Outer Radius vertices.Add(eVert * (outerRadius * (1f / parent.transform.localScale.x))); Normals.Add(Vector3.left); Uvs.Add(Vector2.zero); } // Tri Wrapping int Wrapping = steps * 2; for (int i = 0; i < Wrapping; i += 2) { Tris.Add((i) % Wrapping); Tris.Add((i + 1) % Wrapping); Tris.Add((i + 2) % Wrapping); Tris.Add((i + 1) % Wrapping); Tris.Add((i + 3) % Wrapping); Tris.Add((i + 2) % Wrapping); } for (int i = 0; i < Wrapping; i += 2) { Tris.Add(Wrapping + (i + 2) % Wrapping); Tris.Add(Wrapping + (i + 1) % Wrapping); Tris.Add(Wrapping + (i) % Wrapping); Tris.Add(Wrapping + (i + 2) % Wrapping); Tris.Add(Wrapping + (i + 3) % Wrapping); Tris.Add(Wrapping + (i + 1) % Wrapping); } // Update Rotation transform.localRotation = rotation; // Update Scale and Layer transform.localScale = parent.transform.localScale; transform.position = parent.transform.localPosition; gameObject.layer = parent.layer; // Create MeshFilter MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>(); // Set mesh meshFilter.mesh = new Mesh(); meshFilter.mesh.vertices = vertices.ToArray(); meshFilter.mesh.triangles = Tris.ToArray(); meshFilter.mesh.uv = Uvs.ToArray(); meshFilter.mesh.RecalculateNormals(); meshFilter.mesh.RecalculateBounds(); meshFilter.mesh.Optimize(); meshFilter.sharedMesh = meshFilter.mesh; // Set texture MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>(); Renderer parentRenderer = parent.GetComponent<Renderer>(); if (unlit) meshRenderer.material = new Material(Shader.Find("Unlit/Transparent")); else meshRenderer.material = new Material(Shader.Find("Transparent/Diffuse")); meshRenderer.material.mainTexture = texture; meshRenderer.material.color = color; meshRenderer.material.renderQueue = parentRenderer.material.renderQueue; parentRenderer.material.renderQueue--; } /// <summary> /// Update the scale and the lock /// </summary> void Update() { transform.localScale = transform.parent.localScale; if (lockRotation) transform.rotation = rotation; } /// <summary> /// Update the scale and the lock /// </summary> void FixedUpdate() { transform.localScale = transform.parent.localScale; if (lockRotation) transform.rotation = rotation; } /// <summary> /// Update the scale and the lock /// </summary> void LateUpdate() { transform.localScale = transform.parent.localScale; if (lockRotation) transform.rotation = rotation; } } } }
Borisbee1/Kopernicus
Kopernicus/Kopernicus.Components/Ring.cs
C#
lgpl-3.0
7,416
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2019 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * Psi4 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ /*************************************************************************** * PSIMRCC * Copyright (C) 2007 by Francesco Evangelista and Andrew Simmonett * frank@ccc.uga.edu andysim@ccc.uga.edu * A multireference coupled cluster code ***************************************************************************/ #include "psi4/libpsi4util/libpsi4util.h" #include "idmrpt2.h" #include "blas.h" namespace psi { namespace psimrcc { /** * \brief Computes the contribution * \f[ * \mathcal{F}_{ai}(\mu) * + \sum_{e} t_i^e(\mu) \mathcal{F}_{ae}(\mu) * - \sum_{m} t_m^a(\mu) \mathcal{F}_{mi}(\mu) * + \sum_{uv} t_{iu}^{av}(\mu) \mathcal{F}_{uv}(\mu) * + \sum_{UV} t_{iU}^{aV}(\mu) \mathcal{F}_{UV}(\mu) * \f] */ void IDMRPT2::build_t1_ia_amplitudes() { START_TIMER("Building the T1_ia Amplitudes"); wfn_->blas()->solve("t1_eqns[o][v]{u} = fock[o][v]{u}"); wfn_->blas()->solve("t1_eqns[o][v]{u} += t1[o][v]{u} 2@2 F_ae[v][v]{u}"); wfn_->blas()->solve("t1_eqns[o][v]{u} += - F_mi[o][o]{u} 1@1 t1[o][v]{u}"); wfn_->blas()->solve("t1_eqns[o][v]{u} += #12# t2_ovov[aa][ov]{u} 1@1 fock[aa]{u}"); wfn_->blas()->solve("t1_eqns[o][v]{u} += #12# t2_ovOV[ov][AA]{u} 2@1 fock[AA]{u}"); END_TIMER("Building the T1_ia Amplitudes"); } /** * \brief Computes the contribution * \f[ * \mathcal{F}_{AI}(\mu) * + \sum_{E} t_I^E(\mu) \mathcal{F}_{AE}(\mu) * - \sum_{M} t_M^A(\mu) \mathcal{F}_{MI}(\mu) * + \sum_{uv} t_{uI}^{vA}(\mu) \mathcal{F}_{uv}(\mu) * + \sum_{UV} t_{IU}^{AV}(\mu) \mathcal{F}_{UV}(\mu) * \f] */ void IDMRPT2::build_t1_IA_amplitudes() { START_TIMER("Building the T1_IA Amplitudes"); // Closed-shell wfn_->blas()->solve("t1_eqns[O][V]{c} = t1_eqns[o][v]{c}"); // Open-shell wfn_->blas()->solve("t1_eqns[O][V]{o} = fock[O][V]{o}"); wfn_->blas()->solve("t1_eqns[O][V]{o} += t1[O][V]{o} 2@2 F_AE[V][V]{o}"); wfn_->blas()->solve("t1_eqns[O][V]{o} += - F_MI[O][O]{o} 1@1 t1[O][V]{o}"); wfn_->blas()->solve("t1_eqns[O][V]{o} += #12# t2_ovOV[aa][OV]{o} 1@1 fock[aa]{o}"); wfn_->blas()->solve("t1_eqns[O][V]{o} += #12# t2_OVOV[AA][OV]{o} 1@1 fock[AA]{o}"); END_TIMER("Building the T1_IA Amplitudes"); } } // namespace psimrcc } // namespace psi
jgonthier/psi4
psi4/src/psi4/psimrcc/idmrpt2_t1_amps.cc
C++
lgpl-3.0
3,190
// // XmlSchemaWriter.cs - DataSet.WriteXmlSchema() support // // Author: // // Atsushi Enomoto <atsushi@ximian.com> // // Original WriteXml/WriteXmlSchema authors are: // Ville Palo, Alan Tam, Lluis Sanchez and Eran Domb. // // // Copyright (C) 2004-05 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Data; using System.Xml; namespace System.Data { internal class XmlSchemaWriter { const string xmlnsxs = System.Xml.Schema.XmlSchema.Namespace; public static void WriteXmlSchema (DataSet dataset, XmlWriter writer) { WriteXmlSchema (dataset, writer, dataset.Tables, dataset.Relations); } public static void WriteXmlSchema (DataSet dataset, XmlWriter writer, DataTableCollection tables, DataRelationCollection relations) { new XmlSchemaWriter (dataset, writer, tables, relations).WriteSchema (); } internal static void WriteXmlSchema (XmlWriter writer, DataTable[] tables, DataRelation[] relations, string mainDataTable, string dataSetName, CultureInfo locale) { new XmlSchemaWriter (writer, tables, relations, mainDataTable, dataSetName, locale).WriteSchema (); } public XmlSchemaWriter (DataSet dataset, XmlWriter writer, DataTableCollection tables, DataRelationCollection relations) { dataSetName = dataset.DataSetName; dataSetNamespace = dataset.Namespace; #if NET_2_0 dataSetLocale = dataset.LocaleSpecified ? dataset.Locale : null; #else dataSetLocale = dataset.Locale; #endif dataSetProperties = dataset.ExtendedProperties; w = writer; if (tables != null) { this.tables = new DataTable[tables.Count]; for(int i=0;i<tables.Count;i++) this.tables[i] = tables[i]; } if (relations != null) { this.relations = new DataRelation[relations.Count]; for(int i=0;i<relations.Count;i++) this.relations[i] = relations[i]; } } public XmlSchemaWriter (XmlWriter writer, DataTable[] tables, DataRelation[] relations, string mainDataTable, string dataSetName, CultureInfo locale) { w = writer; this.tables = tables; this.relations = relations; this.mainDataTable = mainDataTable; this.dataSetName = dataSetName; this.dataSetLocale = locale; this.dataSetProperties = new PropertyCollection(); if (tables[0].DataSet != null) { dataSetNamespace = tables[0].DataSet.Namespace; #if !NET_2_0 dataSetLocale = tables[0].DataSet.Locale; #endif } else { dataSetNamespace = tables[0].Namespace; #if !NET_2_0 dataSetLocale = tables[0].Locale; #endif } } XmlWriter w; DataTable[] tables; DataRelation[] relations; string mainDataTable; string dataSetName; string dataSetNamespace; PropertyCollection dataSetProperties; CultureInfo dataSetLocale; ArrayList globalTypeTables = new ArrayList (); Hashtable additionalNamespaces = new Hashtable (); ArrayList annotation = new ArrayList (); public string ConstraintPrefix { get { return dataSetNamespace != String.Empty ? XmlConstants.TnsPrefix + ':' : String.Empty; } } // the whole DataSet public void WriteSchema () { ListDictionary names = new ListDictionary (); ListDictionary includes = new ListDictionary (); // Add namespaces used in DataSet components (tables, columns, ...) foreach (DataTable dt in tables) { foreach (DataColumn col in dt.Columns) CheckNamespace (col.Prefix, col.Namespace, names, includes); CheckNamespace (dt.Prefix, dt.Namespace, names, includes); } w.WriteStartElement ("xs", "schema", xmlnsxs); w.WriteAttributeString ("id", XmlHelper.Encode (dataSetName)); if (dataSetNamespace != String.Empty) { w.WriteAttributeString ("targetNamespace", dataSetNamespace); w.WriteAttributeString ( "xmlns", XmlConstants.TnsPrefix, XmlConstants.XmlnsNS, dataSetNamespace); } w.WriteAttributeString ("xmlns", dataSetNamespace); w.WriteAttributeString ("xmlns", "xs", XmlConstants.XmlnsNS, xmlnsxs); w.WriteAttributeString ("xmlns", XmlConstants.MsdataPrefix, XmlConstants.XmlnsNS, XmlConstants.MsdataNamespace); if (CheckExtendedPropertyExists (tables, relations)) w.WriteAttributeString ("xmlns", XmlConstants.MspropPrefix, XmlConstants.XmlnsNS, XmlConstants.MspropNamespace); if (dataSetNamespace != String.Empty) { w.WriteAttributeString ("attributeFormDefault", "qualified"); w.WriteAttributeString ("elementFormDefault", "qualified"); } foreach (string prefix in names.Keys) w.WriteAttributeString ("xmlns", prefix, XmlConstants.XmlnsNS, names [prefix] as string); if (includes.Count > 0) w.WriteComment ("ATTENTION: This schema contains references to other imported schemas"); foreach (string ns in includes.Keys) { w.WriteStartElement ("xs", "import", xmlnsxs); w.WriteAttributeString ("namespace", ns); w.WriteAttributeString ("schemaLocation", includes [ns] as string); w.WriteEndElement (); } foreach (DataTable table in tables) { bool isTopLevel = true; foreach (DataRelation rel in table.ParentRelations) { if (rel.Nested) { isTopLevel = false; break; } } // LAMESPEC: You have a nested relationship but only one table, // write table element first if (!isTopLevel && tables.Length < 2) WriteTableElement (table); } WriteDataSetElement (); w.WriteEndElement (); // xs:schema w.Flush (); } // FIXME: actually there are some cases that this method(ology) // does not apply. private void WriteDataSetElement () { w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteAttributeString ("name", XmlHelper.Encode (dataSetName)); w.WriteAttributeString (XmlConstants.MsdataPrefix, "IsDataSet", XmlConstants.MsdataNamespace, "true"); #if NET_2_0 bool useCurrentLocale = (dataSetLocale == null); if (!useCurrentLocale) #endif { w.WriteAttributeString ( XmlConstants.MsdataPrefix, "Locale", XmlConstants.MsdataNamespace, dataSetLocale.Name); } #if NET_2_0 if(mainDataTable != null && mainDataTable != "") w.WriteAttributeString ( XmlConstants.MsdataPrefix, "MainDataTable", XmlConstants.MsdataNamespace, mainDataTable); if (useCurrentLocale) { w.WriteAttributeString ( XmlConstants.MsdataPrefix, "UseCurrentLocale", XmlConstants.MsdataNamespace, "true"); } #endif AddExtendedPropertyAttributes (dataSetProperties); w.WriteStartElement ("xs", "complexType", xmlnsxs); w.WriteStartElement ("xs", "choice", xmlnsxs); w.WriteAttributeString ("minOccurs", "0"); w.WriteAttributeString ("maxOccurs", "unbounded"); foreach (DataTable table in tables) { bool isTopLevel = true; foreach (DataRelation rel in table.ParentRelations) { if (rel.Nested) { isTopLevel = false; break; } } // If there is a relation but only one table, could be that // we have to add a ref attribute bool addref = false; if (!isTopLevel && tables.Length < 2) { isTopLevel = true; addref = true; } if (isTopLevel) { if (dataSetNamespace != table.Namespace || addref) { // <xs:element ref="X:y" /> w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteStartAttribute ("ref", String.Empty); w.WriteQualifiedName (XmlHelper.Encode (table.TableName), table.Namespace); w.WriteEndAttribute (); w.WriteEndElement (); } else WriteTableElement (table); } } w.WriteEndElement (); // choice w.WriteEndElement (); // complexType WriteConstraints (); // DataSet constraints w.WriteEndElement (); // element if (annotation.Count > 0) { w.WriteStartElement ("xs", "annotation", xmlnsxs); w.WriteStartElement ("xs", "appinfo", xmlnsxs); foreach (object o in annotation) { if (!(o is DataRelation)) continue; WriteDataRelationAnnotation ((DataRelation)o); } w.WriteEndElement (); w.WriteEndElement (); } } private void WriteDataRelationAnnotation (DataRelation rel) { String colnames = String.Empty; w.WriteStartElement (XmlConstants.MsdataPrefix, "Relationship", XmlConstants.MsdataNamespace); w.WriteAttributeString ("name", XmlHelper.Encode (rel.RelationName)); w.WriteAttributeString ( XmlConstants.MsdataPrefix, "parent", XmlConstants.MsdataNamespace, XmlHelper.Encode (rel.ParentTable.TableName)); w.WriteAttributeString ( XmlConstants.MsdataPrefix, "child", XmlConstants.MsdataNamespace, XmlHelper.Encode (rel.ChildTable.TableName)); colnames = String.Empty; foreach (DataColumn col in rel.ParentColumns) colnames += XmlHelper.Encode (col.ColumnName) + " "; w.WriteAttributeString ( XmlConstants.MsdataPrefix, "parentkey", XmlConstants.MsdataNamespace, colnames.TrimEnd ()); colnames = String.Empty; foreach (DataColumn col in rel.ChildColumns) colnames += XmlHelper.Encode (col.ColumnName) + " "; w.WriteAttributeString ( XmlConstants.MsdataPrefix, "childkey", XmlConstants.MsdataNamespace, colnames.TrimEnd ()); w.WriteEndElement (); } private void WriteConstraints () { ArrayList names = new ArrayList (); // add all unique constraints. foreach (DataTable table in tables) { foreach (Constraint c in table.Constraints) { UniqueConstraint u = c as UniqueConstraint; if (u != null) { AddUniqueConstraints (u, names); continue; } ForeignKeyConstraint fk = c as ForeignKeyConstraint; bool haveConstraint = false; if (relations != null) { foreach (DataRelation r in relations) if (r.RelationName == fk.ConstraintName) haveConstraint = true; } if (tables.Length > 1 && fk != null && !haveConstraint) { DataRelation rel = new DataRelation (fk.ConstraintName, fk.RelatedColumns, fk.Columns); AddForeignKeys (rel, names, true); continue; } } } // Add all foriegn key constraints. if (relations != null) foreach (DataRelation rel in relations) { if (rel.ParentKeyConstraint == null || rel.ChildKeyConstraint == null) { annotation.Add (rel); continue; } AddForeignKeys (rel, names,false); } } // Add unique constaraints to the schema. // return hashtable with the names of all XmlSchemaUnique elements we created. private void AddUniqueConstraints (UniqueConstraint uniq, ArrayList names) { // if column of the constraint is hidden do not write the constraint. foreach (DataColumn column in uniq.Columns) if (column.ColumnMapping == MappingType.Hidden) return; // do nothing w.WriteStartElement ("xs", "unique", xmlnsxs); // if constaraint name do not exist in the hashtable we can use it. string name; if (!names.Contains (uniq.ConstraintName)) { name = XmlHelper.Encode (uniq.ConstraintName); w.WriteAttributeString ("name", name); } // otherwise generate new constraint name for the // XmlSchemaUnique element. else { name = XmlHelper.Encode (uniq.Table.TableName) + "_" + XmlHelper.Encode (uniq.ConstraintName); w.WriteAttributeString ("name", name); w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.ConstraintName, XmlConstants.MsdataNamespace, XmlHelper.Encode (uniq.ConstraintName)); } names.Add (name); if (uniq.IsPrimaryKey) { w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.PrimaryKey, XmlConstants.MsdataNamespace, "true"); } AddExtendedPropertyAttributes (uniq.ExtendedProperties); w.WriteStartElement ("xs", "selector", xmlnsxs); w.WriteAttributeString ("xpath", ".//" + ConstraintPrefix + XmlHelper.Encode (uniq.Table.TableName)); w.WriteEndElement (); // selector foreach (DataColumn c in uniq.Columns) { w.WriteStartElement ("xs", "field", xmlnsxs); w.WriteStartAttribute ("xpath", String.Empty); if (c.ColumnMapping == MappingType.Attribute) w.WriteString ("@"); w.WriteString (ConstraintPrefix); w.WriteString (XmlHelper.Encode (c.ColumnName)); w.WriteEndAttribute (); // xpath w.WriteEndElement (); // field } w.WriteEndElement (); // unique } // Add the foriegn keys to the schema. private void AddForeignKeys (DataRelation rel, ArrayList names, bool isConstraintOnly) { // Do nothing if it contains hidden relation foreach (DataColumn col in rel.ParentColumns) if (col.ColumnMapping == MappingType.Hidden) return; foreach (DataColumn col in rel.ChildColumns) if (col.ColumnMapping == MappingType.Hidden) return; w.WriteStartElement ("xs", "keyref", xmlnsxs); w.WriteAttributeString ("name", XmlHelper.Encode (rel.RelationName)); //ForeignKeyConstraint fkConst = rel.ChildKeyConstraint; UniqueConstraint uqConst = null; if (isConstraintOnly) { foreach (Constraint c in rel.ParentTable.Constraints) { uqConst = c as UniqueConstraint; if (uqConst == null) continue; if (uqConst.Columns == rel.ParentColumns) break; } } else uqConst = rel.ParentKeyConstraint; string concatName = XmlHelper.Encode (rel.ParentTable.TableName) + "_" + XmlHelper.Encode (uqConst.ConstraintName); // first try to find the concatenated name. If we didn't find it - use constraint name. if (names.Contains (concatName)) { w.WriteStartAttribute ("refer", String.Empty); w.WriteQualifiedName (concatName, dataSetNamespace); w.WriteEndAttribute (); } else { w.WriteStartAttribute ("refer", String.Empty); w.WriteQualifiedName (XmlHelper.Encode (uqConst.ConstraintName), dataSetNamespace); w.WriteEndAttribute (); } if (isConstraintOnly) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.ConstraintOnly, XmlConstants.MsdataNamespace, "true"); else if (rel.Nested) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.IsNested, XmlConstants.MsdataNamespace, "true"); AddExtendedPropertyAttributes (uqConst.ExtendedProperties); w.WriteStartElement ("xs", "selector", xmlnsxs); w.WriteAttributeString ("xpath", ".//" + ConstraintPrefix + XmlHelper.Encode (rel.ChildTable.TableName)); w.WriteEndElement (); foreach (DataColumn c in rel.ChildColumns) { w.WriteStartElement ("xs", "field", xmlnsxs); w.WriteStartAttribute ("xpath", String.Empty); if (c.ColumnMapping == MappingType.Attribute) w.WriteString ("@"); w.WriteString (ConstraintPrefix); w.WriteString (XmlHelper.Encode (c.ColumnName)); w.WriteEndAttribute (); w.WriteEndElement (); // field } w.WriteEndElement (); // keyref } // ExtendedProperties private bool CheckExtendedPropertyExists ( DataTable[] tables, DataRelation[] relations) { if (dataSetProperties.Count > 0) return true; foreach (DataTable dt in tables) { if (dt.ExtendedProperties.Count > 0) return true; foreach (DataColumn col in dt.Columns) if (col.ExtendedProperties.Count > 0) return true; foreach (Constraint c in dt.Constraints) if (c.ExtendedProperties.Count > 0) return true; } if (relations == null) return false; foreach (DataRelation rel in relations) if (rel.ExtendedProperties.Count > 0) return true; return false; } private void AddExtendedPropertyAttributes (PropertyCollection props) { // add extended properties to xs:element foreach (DictionaryEntry de in props) { w.WriteStartAttribute ( XmlConstants.MspropPrefix, XmlConvert.EncodeName (de.Key.ToString ()), XmlConstants.MspropNamespace); if (de.Value != null) w.WriteString ( DataSet.WriteObjectXml (de.Value)); w.WriteEndAttribute (); } } // Table private void WriteTableElement (DataTable table) { w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteAttributeString ("name", XmlHelper.Encode (table.TableName)); AddExtendedPropertyAttributes (table.ExtendedProperties); WriteTableType (table); w.WriteEndElement (); } private void WriteTableType (DataTable table) { ArrayList elements; ArrayList atts; DataColumn simple; DataSet.SplitColumns (table, out atts, out elements, out simple); w.WriteStartElement ("xs", "complexType", xmlnsxs); if (simple != null) { w.WriteStartElement ("xs", "simpleContent", xmlnsxs); // add column name attribute w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.ColumnName, XmlConstants.MsdataNamespace, XmlHelper.Encode (simple.ColumnName)); // add ordinal attribute w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.Ordinal, XmlConstants.MsdataNamespace, XmlConvert.ToString (simple.Ordinal)); // add extension w.WriteStartElement ("xs", "extension", xmlnsxs); w.WriteStartAttribute ("base", String.Empty); WriteQName (MapType (simple.DataType)); w.WriteEndAttribute (); WriteTableAttributes (atts); w.WriteEndElement (); } else { WriteTableAttributes (atts); bool isNested = false; foreach (DataRelation rel in table.ParentRelations) { if (rel.Nested) { isNested = true; break; } } // When we have a nested relationship and only one table, // could be that we have a reference attribute if (elements.Count > 0 || (isNested && tables.Length < 2)) { w.WriteStartElement ("xs", "sequence", xmlnsxs); foreach (DataColumn col in elements) WriteTableTypeParticles (col); foreach (DataRelation rel in table.ChildRelations) if (rel.Nested) WriteChildRelations (rel); w.WriteEndElement (); } } w.WriteFullEndElement (); // complexType } private void WriteTableTypeParticles (DataColumn col) { w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteAttributeString ("name", XmlHelper.Encode (col.ColumnName)); if (col.ColumnName != col.Caption && col.Caption != String.Empty) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.Caption, XmlConstants.MsdataNamespace, col.Caption); if (col.AutoIncrement == true) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.AutoIncrement, XmlConstants.MsdataNamespace, "true"); if (col.AutoIncrementSeed != 0) { w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.AutoIncrementSeed, XmlConstants.MsdataNamespace, XmlConvert.ToString (col.AutoIncrementSeed)); } if (col.AutoIncrementStep != 1) { w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.AutoIncrementStep, XmlConstants.MsdataNamespace, XmlConvert.ToString (col.AutoIncrementStep)); } if (!DataColumn.GetDefaultValueForType (col.DataType).Equals (col.DefaultValue)) w.WriteAttributeString ("default", DataSet.WriteObjectXml (col.DefaultValue)); if (col.ReadOnly) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.ReadOnly, XmlConstants.MsdataNamespace, "true"); XmlQualifiedName typeQName = null; if (col.MaxLength < 0) { w.WriteStartAttribute ("type", String.Empty); typeQName = MapType (col.DataType); WriteQName (typeQName); w.WriteEndAttribute (); } if (typeQName == XmlConstants.QnString && col.DataType != typeof (string) && col.DataType != typeof (char)) { w.WriteStartAttribute ( XmlConstants.MsdataPrefix, XmlConstants.DataType, XmlConstants.MsdataNamespace); string runtimeName = col.DataType.AssemblyQualifiedName; w.WriteString (runtimeName); w.WriteEndAttribute (); } if (col.AllowDBNull) w.WriteAttributeString ("minOccurs", "0"); //writer.WriteAttributeString (XmlConstants.MsdataPrefix, // XmlConstants.Ordinal, // XmlConstants.MsdataNamespace, // col.Ordinal.ToString ()); AddExtendedPropertyAttributes (col.ExtendedProperties); // Write SimpleType if column have MaxLength if (col.MaxLength > -1) WriteSimpleType (col); w.WriteEndElement (); // sequence } private void WriteChildRelations (DataRelation rel) { // If there is a parent/child relation and only one table, // it would just be a ref element. if (rel.ChildTable.Namespace != dataSetNamespace || tables.Length < 2) { w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteStartAttribute ("ref", String.Empty); w.WriteQualifiedName ( XmlHelper.Encode (rel.ChildTable.TableName), rel.ChildTable.Namespace); w.WriteEndAttribute (); } else { w.WriteStartElement ("xs", "element", xmlnsxs); w.WriteStartAttribute ("name", String.Empty); w.WriteQualifiedName ( XmlHelper.Encode (rel.ChildTable.TableName), rel.ChildTable.Namespace); w.WriteEndAttribute (); w.WriteAttributeString ("minOccurs", "0"); w.WriteAttributeString ("maxOccurs", "unbounded"); globalTypeTables.Add (rel.ChildTable); } // Iff there is a genuine ChildTable and not just a ref, call WriteTableType if (tables.Length > 1) WriteTableType (rel.ChildTable); w.WriteEndElement (); } private void WriteTableAttributes (ArrayList atts) { //Then a list of attributes foreach (DataColumn col in atts) { w.WriteStartElement ("xs", "attribute", xmlnsxs); string name = XmlHelper.Encode (col.ColumnName); if (col.Namespace != String.Empty) { w.WriteAttributeString ("form", "qualified"); string prefix = col.Prefix == String.Empty ? "app" + additionalNamespaces.Count : col.Prefix; name = prefix + ":" + name; // FIXME: Handle prefix mapping correctly. additionalNamespaces [prefix] = col.Namespace; } w.WriteAttributeString ("name", name); AddExtendedPropertyAttributes ( col.ExtendedProperties); if (col.ReadOnly) w.WriteAttributeString ( XmlConstants.MsdataPrefix, XmlConstants.ReadOnly, XmlConstants.MsdataNamespace, "true"); if (col.MaxLength < 0) { // otherwise simpleType is written later w.WriteStartAttribute ("type", String.Empty); WriteQName (MapType (col.DataType)); w.WriteEndAttribute (); } if (!col.AllowDBNull) w.WriteAttributeString ("use", "required"); if (col.DefaultValue != DataColumn.GetDefaultValueForType (col.DataType)) w.WriteAttributeString ("default", DataSet.WriteObjectXml (col.DefaultValue)); if (col.MaxLength > -1) WriteSimpleType (col); w.WriteEndElement (); // attribute } } private void WriteSimpleType (DataColumn col) { w.WriteStartElement ("xs", "simpleType", xmlnsxs); w.WriteStartElement ("xs", "restriction", xmlnsxs); w.WriteStartAttribute ("base", String.Empty); WriteQName (MapType (col.DataType)); w.WriteEndAttribute (); w.WriteStartElement ("xs", "maxLength", xmlnsxs); w.WriteAttributeString ("value", XmlConvert.ToString (col.MaxLength)); w.WriteEndElement (); // maxLength w.WriteEndElement (); // restriction w.WriteEndElement (); // simpleType } private void WriteQName (XmlQualifiedName name) { w.WriteQualifiedName (name.Name, name.Namespace); } private void CheckNamespace (string prefix, string ns, ListDictionary names, ListDictionary includes) { if (ns == String.Empty) return; if (dataSetNamespace != ns) { if ((string)names [prefix] != ns) { for (int i = 1; i < int.MaxValue; i++) { string p = "app" + i; if (names [p] == null) { names.Add (p, ns); HandleExternalNamespace (p, ns, includes); break; } } } } } private void HandleExternalNamespace (string prefix, string ns, ListDictionary includes) { if (includes.Contains (ns)) return; // nothing to do includes.Add (ns, "_" + prefix + ".xsd"); } private /*static*/ XmlQualifiedName MapType (Type type) { switch (Type.GetTypeCode (type)) { case TypeCode.String: return XmlConstants.QnString; case TypeCode.Int16: return XmlConstants.QnShort; case TypeCode.Int32: return XmlConstants.QnInt; case TypeCode.Int64: return XmlConstants.QnLong; case TypeCode.Boolean: return XmlConstants.QnBoolean; case TypeCode.Byte: return XmlConstants.QnUnsignedByte; //case TypeCode.Char: return XmlConstants.QnChar; case TypeCode.DateTime: return XmlConstants.QnDateTime; case TypeCode.Decimal: return XmlConstants.QnDecimal; case TypeCode.Double: return XmlConstants.QnDouble; case TypeCode.SByte: return XmlConstants.QnSbyte; case TypeCode.Single: return XmlConstants.QnFloat; case TypeCode.UInt16: return XmlConstants.QnUnsignedShort; case TypeCode.UInt32: return XmlConstants.QnUnsignedInt; case TypeCode.UInt64: return XmlConstants.QnUnsignedLong; } if (typeof (TimeSpan) == type) return XmlConstants.QnDuration; else if (typeof (System.Uri) == type) return XmlConstants.QnUri; else if (typeof (byte[]) == type) return XmlConstants.QnBase64Binary; else if (typeof (XmlQualifiedName) == type) return XmlConstants.QnXmlQualifiedName; else return XmlConstants.QnString; } } }
edwinspire/VSharp
class/System.Data/System.Data/XmlSchemaWriter.cs
C#
lgpl-3.0
26,773
package org.hy.commons.lang.timer; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.logging.LogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * * @author uwaysoft 魏韶颖 时间:2009年4月20日15:02:58 */ public class TimerTaskProxy extends TimerTask { Logger logger = LoggerFactory.getLogger(TimerTaskProxy.class); private int count; private Timer timer; private int hasExeNum = 0; private TimerTask timerTask; /** * 定时任务代理 调用客户写的子类run方法 * @param subClassName 子类名 * @param count 执行多少次 * @param * timer 定时器 */ public TimerTaskProxy(String subClassName, int count, Timer timer) { super(); this.count = count; this.timer = timer; try { this.timerTask = (TimerTask) Class.forName(subClassName) .newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public void run() { /** * 运用了多态 条件:继承,重写,父类引用指向子类对象 所以调用的是子类的run() */ timerTask.run(); hasExeNum++; if (count == hasExeNum) { timer.cancel(); logger.info("定时任务执行完毕,线程成功终止!"); } } }
hy2708/hy2708-repository
java/commons/commons-lang/src/main/java/org/hy/commons/lang/timer/TimerTaskProxy.java
Java
lgpl-3.0
1,420
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine; use pocketmine\network\protocol\Info; use pocketmine\plugin\PluginBase; use pocketmine\plugin\PluginLoadOrder; use pocketmine\utils\Utils; use pocketmine\utils\VersionString; use raklib\RakLib; /* * Called when a critical exception occurs that the server can't continue past. * Saved to a file or optionally sent to a server (see pocketmine.yml configuration options) */ class CrashDump{ /** @var Server */ private $server; private $fp; private $time; private $data = []; private $encodedData = null; private $path; public function __construct(Server $server){ $this->time = time(); $this->server = $server; if(!is_dir($this->server->getDataPath()) . "CrashDumps") mkdir($this->server->getDataPath() . "CrashDumps"); $this->path = $this->server->getDataPath() . "CrashDumps/" . date("D_M_j-H.i.s-T_Y", $this->time) . ".log"; $this->fp = @fopen($this->path, "wb"); if(!is_resource($this->fp)){ throw new \RuntimeException("Could not create Crash Dump"); } $this->data["time"] = $this->time; $this->addLine($this->server->getName() . " Crash Dump " . date("D M j H:i:s T Y", $this->time)); $this->addLine(); $this->baseCrash(); $this->generalData(); $this->pluginsData(); $this->extraData(); $this->encodeData(); } public function getPath(){ return $this->path; } public function getEncodedData(){ return $this->encodedData; } public function getData(){ return $this->data; } private function encodeData(){ $this->addLine(); $this->addLine("----------------------REPORT THE DATA BELOW THIS LINE-----------------------"); $this->addLine(); $this->addLine("===BEGIN CRASH DUMP==="); $this->encodedData = zlib_encode(json_encode($this->data, JSON_UNESCAPED_SLASHES), ZLIB_ENCODING_DEFLATE, 9); foreach(str_split(base64_encode($this->encodedData), 76) as $line){ $this->addLine($line); } $this->addLine("===END CRASH DUMP==="); } private function pluginsData(){ if(class_exists("pocketmine\\plugin\\PluginManager", false)){ $this->addLine(); $this->addLine("Loaded plugins:"); $this->data["plugins"] = []; foreach($this->server->getPluginManager()->getPlugins() as $p){ $d = $p->getDescription(); $this->data["plugins"][$d->getName()] = [ "name" => $d->getName(), "version" => $d->getVersion(), "authors" => $d->getAuthors(), "api" => $d->getCompatibleApis(), "enabled" => $p->isEnabled(), "depends" => $d->getDepend(), "softDepends" => $d->getSoftDepend(), "main" => $d->getMain(), "load" => $d->getOrder() === PluginLoadOrder::POSTWORLD ? "POSTWORLD" : "STARTUP", "website" => $d->getWebsite() ]; $this->addLine($d->getName() . " " . $d->getVersion() . " by " . implode(", ", $d->getAuthors()) . " for API(s) " . implode(", ", $d->getCompatibleApis())); } } } private function extraData(){ global $arguments; if($this->server->getProperty("auto-report.send-settings", true) !== false){ $this->data["parameters"] = (array) $arguments; $this->data["server.properties"] = @file_get_contents($this->server->getDataPath() . "server.properties"); $this->data["server.properties"] = preg_replace("#^rcon\\.password=(.*)$#m", "rcon.password=******", $this->data["server.properties"]); $this->data["pocketmine.yml"] = @file_get_contents($this->server->getDataPath() . "pocketmine.yml"); $this->data["katana.yml"] = @file_get_contents($this->server->getDataPath() . "katana.yml"); }else{ $this->data["pocketmine.yml"] = ""; $this->data["katana.yml"] = ""; $this->data["server.properties"] = ""; $this->data["parameters"] = []; } $extensions = []; foreach(get_loaded_extensions() as $ext){ $extensions[$ext] = phpversion($ext); } $this->data["extensions"] = $extensions; if($this->server->getProperty("auto-report.send-phpinfo", true) !== false){ ob_start(); phpinfo(); $this->data["phpinfo"] = ob_get_contents(); ob_end_clean(); } } private function baseCrash(){ global $lastExceptionError, $lastError; if(isset($lastExceptionError)){ $error = $lastExceptionError; }else{ $error = (array) error_get_last(); $error["trace"] = @getTrace(3); $errorConversion = [ E_ERROR => "E_ERROR", E_WARNING => "E_WARNING", E_PARSE => "E_PARSE", E_NOTICE => "E_NOTICE", E_CORE_ERROR => "E_CORE_ERROR", E_CORE_WARNING => "E_CORE_WARNING", E_COMPILE_ERROR => "E_COMPILE_ERROR", E_COMPILE_WARNING => "E_COMPILE_WARNING", E_USER_ERROR => "E_USER_ERROR", E_USER_WARNING => "E_USER_WARNING", E_USER_NOTICE => "E_USER_NOTICE", E_STRICT => "E_STRICT", E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED", ]; $error["fullFile"] = $error["file"]; $error["file"] = cleanPath($error["file"]); $error["type"] = isset($errorConversion[$error["type"]]) ? $errorConversion[$error["type"]] : $error["type"]; if(($pos = strpos($error["message"], "\n")) !== false){ $error["message"] = substr($error["message"], 0, $pos); } } if(isset($lastError)){ $this->data["lastError"] = $lastError; } $this->data["error"] = $error; unset($this->data["error"]["fullFile"]); unset($this->data["error"]["trace"]); $this->addLine("Error: " . $error["message"]); $this->addLine("File: " . $error["file"]); $this->addLine("Line: " . $error["line"]); $this->addLine("Type: " . $error["type"]); if(strpos($error["file"], "src/pocketmine/") === false and strpos($error["file"], "src/raklib/") === false and file_exists($error["fullFile"])){ $this->addLine(); $this->addLine("THIS CRASH WAS CAUSED BY A PLUGIN"); $this->data["plugin"] = true; $reflection = new \ReflectionClass(PluginBase::class); $file = $reflection->getProperty("file"); $file->setAccessible(true); foreach($this->server->getPluginManager()->getPlugins() as $plugin){ $filePath = \pocketmine\cleanPath($file->getValue($plugin)); if(strpos($error["file"], $filePath) === 0){ $this->data["plugin"] = $plugin->getName(); $this->addLine("BAD PLUGIN: " . $plugin->getDescription()->getFullName()); break; } } }else{ $this->data["plugin"] = false; } $this->addLine(); $this->addLine("Code:"); $this->data["code"] = []; if($this->server->getProperty("auto-report.send-code", true) !== false){ $file = @file($error["fullFile"], FILE_IGNORE_NEW_LINES); for($l = max(0, $error["line"] - 10); $l < $error["line"] + 10; ++$l){ $this->addLine("[" . ($l + 1) . "] " . @$file[$l]); $this->data["code"][$l + 1] = @$file[$l]; } } $this->addLine(); $this->addLine("Backtrace:"); foreach(($this->data["trace"] = $error["trace"]) as $line){ $this->addLine($line); } $this->addLine(); } private function generalData(){ $version = new VersionString(); $this->data["general"] = []; $this->data["general"]["version"] = $version->get(false); $this->data["general"]["build"] = $version->getBuild(); $this->data["general"]["protocol"] = Info::CURRENT_PROTOCOL; $this->data["general"]["api"] = \pocketmine\API_VERSION; $this->data["general"]["git"] = \pocketmine\GIT_COMMIT; $this->data["general"]["raklib"] = RakLib::VERSION; $this->data["general"]["uname"] = php_uname("a"); $this->data["general"]["php"] = phpversion(); $this->data["general"]["zend"] = zend_version(); $this->data["general"]["php_os"] = PHP_OS; $this->data["general"]["os"] = Utils::getOS(); $this->addLine("Katana version: " . $version->get(false) . " #" . $version->getBuild() . " [Protocol " . Info::CURRENT_PROTOCOL . "; API " . API_VERSION . "]"); $this->addLine("Git commit: " . GIT_COMMIT); $this->addLine("uname -a: " . php_uname("a")); $this->addLine("PHP Version: " . phpversion()); $this->addLine("Zend version: " . zend_version()); $this->addLine("OS : " . PHP_OS . ", " . Utils::getOS()); } public function addLine($line = ""){ fwrite($this->fp, $line . PHP_EOL); } public function add($str){ fwrite($this->fp, $str); } }
Hydreon/Katana
src/pocketmine/CrashDump.php
PHP
lgpl-3.0
8,822
/* * This is a common dao with basic CRUD operations and is not limited to any * persistent layer implementation * * Copyright (C) 2008 Imran M Yousuf (imyousuf@smartitengineering.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package com.smartitengineering.dao.common.queryparam; import java.util.Collection; /** * * @author imyousuf */ public interface CompoundQueryParameter<Template extends Object> extends QueryParameter<Template> { public Collection<QueryParameter> getNestedParameters(); }
imyousuf/smart-dao
smart-dao-queryparam/src/main/java/com/smartitengineering/dao/common/queryparam/CompoundQueryParameter.java
Java
lgpl-3.0
1,217
/* * Copyright (C) 2005-2013 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.module.vti.web.actions; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.alfresco.module.vti.handler.MethodHandler; import org.alfresco.module.vti.web.VtiAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <p>VtiIfHeaderAction is used for merging between client document version * and server document version.</p> * * @author PavelYur */ public class VtiIfHeaderAction extends HttpServlet implements VtiAction { private static final long serialVersionUID = 3119971805600532320L; private final static Log logger = LogFactory.getLog(VtiIfHeaderAction.class); private MethodHandler handler; /** * <p> * MethodHandler setter * </p> * @param handler {@link org.alfresco.module.vti.handler.MethodHandler} */ public void setHandler(MethodHandler handler) { this.handler = handler; } /** * <p>Getting server version of document for merging.</p> * * @param request HTTP request * @param response HTTP response */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.handler.existResource(req, resp); } /** * <p>Saving of client version of document while merging.</p> * * @param request HTTP request * @param response HTTP response */ @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.handler.putResource(req, resp); } /** * <p>Merge between client document version and server document version.</p> * * @param request HTTP request * @param response HTTP response */ public void execute(HttpServletRequest request, HttpServletResponse response) { try { service(request, response); } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Action IO exception", e); } } catch (ServletException e) { if (logger.isDebugEnabled()) { logger.debug("Action execution exception", e); } } } }
loftuxab/community-edition-old
modules/sharepoint/amp/source/java/org/alfresco/module/vti/web/actions/VtiIfHeaderAction.java
Java
lgpl-3.0
3,337
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 12.10Release // Tag = $Name$ //////////////////////////////////////////////////////////////////////////////// package com.garmin.fit; public class SdmProfileMesg extends Mesg { protected static final Mesg sdmProfileMesg; static { // sdm_profile sdmProfileMesg = new Mesg("sdm_profile", MesgNum.SDM_PROFILE); sdmProfileMesg.addField(new Field("message_index", 254, 132, 1, 0, "", false)); sdmProfileMesg.addField(new Field("enabled", 0, 0, 1, 0, "", false)); sdmProfileMesg.addField(new Field("sdm_ant_id", 1, 139, 1, 0, "", false)); sdmProfileMesg.addField(new Field("sdm_cal_factor", 2, 132, 10, 0, "%", false)); sdmProfileMesg.addField(new Field("odometer", 3, 134, 100, 0, "m", false)); sdmProfileMesg.addField(new Field("speed_source", 4, 0, 1, 0, "", false)); sdmProfileMesg.addField(new Field("sdm_ant_id_trans_type", 5, 10, 1, 0, "", false)); sdmProfileMesg.addField(new Field("odometer_rollover", 7, 2, 1, 0, "", false)); } public SdmProfileMesg() { super(Factory.createMesg(MesgNum.SDM_PROFILE)); } public SdmProfileMesg(final Mesg mesg) { super(mesg); } /** * Get message_index field * * @return message_index */ public Integer getMessageIndex() { return getFieldIntegerValue(254, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set message_index field * * @param messageIndex */ public void setMessageIndex(Integer messageIndex) { setFieldValue(254, 0, messageIndex, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get enabled field * * @return enabled */ public Bool getEnabled() { Short value = getFieldShortValue(0, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); if (value == null) return null; return Bool.getByValue(value); } /** * Set enabled field * * @param enabled */ public void setEnabled(Bool enabled) { setFieldValue(0, 0, enabled.value, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get sdm_ant_id field * * @return sdm_ant_id */ public Integer getSdmAntId() { return getFieldIntegerValue(1, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set sdm_ant_id field * * @param sdmAntId */ public void setSdmAntId(Integer sdmAntId) { setFieldValue(1, 0, sdmAntId, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get sdm_cal_factor field * Units: % * * @return sdm_cal_factor */ public Float getSdmCalFactor() { return getFieldFloatValue(2, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set sdm_cal_factor field * Units: % * * @param sdmCalFactor */ public void setSdmCalFactor(Float sdmCalFactor) { setFieldValue(2, 0, sdmCalFactor, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get odometer field * Units: m * * @return odometer */ public Float getOdometer() { return getFieldFloatValue(3, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set odometer field * Units: m * * @param odometer */ public void setOdometer(Float odometer) { setFieldValue(3, 0, odometer, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get speed_source field * Comment: Use footpod for speed source instead of GPS * * @return speed_source */ public Bool getSpeedSource() { Short value = getFieldShortValue(4, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); if (value == null) return null; return Bool.getByValue(value); } /** * Set speed_source field * Comment: Use footpod for speed source instead of GPS * * @param speedSource */ public void setSpeedSource(Bool speedSource) { setFieldValue(4, 0, speedSource.value, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get sdm_ant_id_trans_type field * * @return sdm_ant_id_trans_type */ public Short getSdmAntIdTransType() { return getFieldShortValue(5, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set sdm_ant_id_trans_type field * * @param sdmAntIdTransType */ public void setSdmAntIdTransType(Short sdmAntIdTransType) { setFieldValue(5, 0, sdmAntIdTransType, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Get odometer_rollover field * Comment: Rollover counter that can be used to extend the odometer * * @return odometer_rollover */ public Short getOdometerRollover() { return getFieldShortValue(7, 0, Fit.SUBFIELD_INDEX_MAIN_FIELD); } /** * Set odometer_rollover field * Comment: Rollover counter that can be used to extend the odometer * * @param odometerRollover */ public void setOdometerRollover(Short odometerRollover) { setFieldValue(7, 0, odometerRollover, Fit.SUBFIELD_INDEX_MAIN_FIELD); } }
saschaiseli/opentrainingcenter_e4
com.garmin.fit/src/com/garmin/fit/SdmProfileMesg.java
Java
lgpl-3.0
5,938
/* ========================================================================= * This file is part of NITRO * ========================================================================= * * (C) Copyright 2004 - 2017, MDA Information Systems LLC * * NITRO is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, If not, * see <http://www.gnu.org/licenses/>. * */ #include <stdlib.h> #include "nitf/NITFBufferList.hpp" #undef min #undef max namespace nitf { NITFBuffer::NITFBuffer(const void* data, size_t numBytes) noexcept : mData(data), mNumBytes(numBytes) { } size_t NITFBufferList::getTotalNumBytes() const noexcept { size_t numBytes(0); for (const auto& buffer : mBuffers) { numBytes += buffer.mNumBytes; } return numBytes; } size_t NITFBufferList::getNumBlocks(size_t blockSize) const { if (blockSize == 0) { throw except::Exception(Ctxt("Block size must be positive")); } return getTotalNumBytes() / blockSize; } size_t NITFBufferList::getNumBytesInBlock( size_t blockSize, size_t blockIdx) const { const size_t numBlocks(getNumBlocks(blockSize)); if (blockIdx >= numBlocks) { std::ostringstream ostr; ostr << "Block index " << blockIdx << " is out of bounds - only " << numBlocks << " blocks with a block size of " << blockSize; throw except::Exception(Ctxt(ostr.str())); } const size_t numBytes = (blockIdx == numBlocks - 1) ? getTotalNumBytes() - (numBlocks - 1) * blockSize : blockSize; return numBytes; } template<typename T> const void* getBlock_(const std::vector<NITFBuffer>& mBuffers, size_t blockSize, size_t blockIdx, std::vector<T>& scratch, const size_t numBytes) { const size_t startByte = blockIdx * blockSize; size_t byteCount(0); for (size_t ii = 0; ii < mBuffers.size(); ++ii) { const NITFBuffer& buffer(mBuffers[ii]); if (byteCount + buffer.mNumBytes >= startByte) { // We found our first buffer const size_t numBytesToSkip = startByte - byteCount; const size_t numBytesLeftInBuffer = buffer.mNumBytes - numBytesToSkip; const auto startPtr = static_cast<const T*>(buffer.mData) + numBytesToSkip; if (numBytesLeftInBuffer >= numBytes) { // We have contiguous memory in this buffer - we don't need to // copy anything return startPtr; } else { // The bytes we want span 2+ buffers - we'll use scratch space // and copy in the bytes we want to that scratch.resize(numBytes); size_t numBytesCopied(0); memcpy(scratch.data(), startPtr, numBytesLeftInBuffer); numBytesCopied += numBytesLeftInBuffer; for (size_t jj = ii + 1; jj < mBuffers.size(); ++jj) { const NITFBuffer& curBuffer(mBuffers[jj]); const size_t numBytesToCopy = std::min(curBuffer.mNumBytes, numBytes - numBytesCopied); memcpy(&scratch[numBytesCopied], curBuffer.mData, numBytesToCopy); numBytesCopied += numBytesToCopy; if (numBytesCopied == numBytes) { break; } } return scratch.data(); } } byteCount += buffer.mNumBytes; } // Should not be possible to get here return nullptr; } const void* NITFBufferList::getBlock(size_t blockSize, size_t blockIdx, std::vector<sys::byte>& scratch, size_t& numBytes) const { numBytes = getNumBytesInBlock(blockSize, blockIdx); return getBlock_(mBuffers, blockSize, blockIdx, scratch, numBytes); } const void* NITFBufferList::getBlock(size_t blockSize, size_t blockIdx, std::vector<std::byte>& scratch, size_t& numBytes) const { numBytes = getNumBytesInBlock(blockSize, blockIdx); return getBlock_(mBuffers, blockSize, blockIdx, scratch, numBytes); } }
mdaus/nitro
modules/c++/nitf/source/NITFBufferList.cpp
C++
lgpl-3.0
5,423
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IDataModel.cs" company="Copyright © 2014 Tekla Corporation. Tekla is a Trimble Company"> // Copyright (C) 2014 [Jorge Costa, Jorge.Costa@tekla.com] // </copyright> // -------------------------------------------------------------------------------------------------------------------- // This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -------------------------------------------------------------------------------------------------------------------- namespace VSSonarExtensionUi.Model.Helpers { using System.ComponentModel; using SonarRestService.Types; using SonarRestService; /// <summary> /// The DataModel interface. /// </summary> public interface IDataModel { #region Public Methods and Operators /// <summary> /// The process changes. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="propertyChangedEventArgs"> /// The property changed event args. /// </param> void ProcessChanges(object sender, PropertyChangedEventArgs propertyChangedEventArgs); #endregion } }
TeklaCorp/VSSonarQubeExtension
VSSonarExtensionUi/Model/Helpers/IDataModel.cs
C#
lgpl-3.0
2,003
/* This source file is part of KBEngine For the latest info, see http://www.kbengine.org/ Copyright (c) 2008-2012 KBEngine. KBEngine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. KBEngine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with KBEngine. If not, see <http://www.gnu.org/licenses/>. */ #include "server/kbemain.hpp" #include "cellappmgr.hpp" #include "machine/machine_interface.hpp" #define DEFINE_IN_INTERFACE #include "machine/machine_interface.hpp" #undef DEFINE_IN_INTERFACE #include "baseappmgr/baseappmgr_interface.hpp" #define DEFINE_IN_INTERFACE #include "baseappmgr/baseappmgr_interface.hpp" #undef DEFINE_IN_INTERFACE #include "cellapp/cellapp_interface.hpp" #define DEFINE_IN_INTERFACE #include "cellapp/cellapp_interface.hpp" #undef DEFINE_IN_INTERFACE #include "baseapp/baseapp_interface.hpp" #define DEFINE_IN_INTERFACE #include "baseapp/baseapp_interface.hpp" #undef DEFINE_IN_INTERFACE #include "dbmgr/dbmgr_interface.hpp" #define DEFINE_IN_INTERFACE #include "dbmgr/dbmgr_interface.hpp" #undef DEFINE_IN_INTERFACE #include "loginapp/loginapp_interface.hpp" #define DEFINE_IN_INTERFACE #include "loginapp/loginapp_interface.hpp" #undef DEFINE_IN_INTERFACE #include "resourcemgr/resourcemgr_interface.hpp" #define DEFINE_IN_INTERFACE #include "resourcemgr/resourcemgr_interface.hpp" #undef DEFINE_IN_INTERFACE #include "tools/message_log/messagelog_interface.hpp" #define DEFINE_IN_INTERFACE #include "tools/message_log/messagelog_interface.hpp" #undef DEFINE_IN_INTERFACE #include "tools/bots/bots_interface.hpp" #define DEFINE_IN_INTERFACE #include "tools/bots/bots_interface.hpp" #undef DEFINE_IN_INTERFACE #include "tools/billing_system/billingsystem_interface.hpp" #define DEFINE_IN_INTERFACE #include "tools/billing_system/billingsystem_interface.hpp" using namespace KBEngine; int KBENGINE_MAIN(int argc, char* argv[]) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getCellAppMgr(); return kbeMainT<Cellappmgr>(argc, argv, CELLAPPMGR_TYPE, -1, -1, "", 0, info.internalInterface); }
LaoZhongGu/kbengine
kbe/src/server/cellappmgr/main.cpp
C++
lgpl-3.0
2,561