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
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2021 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "localEulerDdtScheme.H" #include "surfaceInterpolate.H" #include "fvMatrices.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type> const volScalarField& localEulerDdtScheme<Type>::localRDeltaT() const { return localEulerDdt::localRDeltaT(mesh()); } template<class Type> const surfaceScalarField& localEulerDdtScheme<Type>::localRDeltaTf() const { return localEulerDdt::localRDeltaTf(mesh()); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const dimensioned<Type>& dt ) { const word ddtName("ddt(" + dt.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, mesh(), dimensioned<Type> ( "0", dt.dimensions()/dimTime, Zero ), calculatedFvPatchField<Type>::typeName ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*(vf - vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const dimensionedScalar& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*rho*(vf - vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT*(rho*vf - rho.oldTime()*vf.oldTime()) ) ); } template<class Type> tmp<GeometricField<Type, fvPatchField, volMesh>> localEulerDdtScheme<Type>::fvcDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { const volScalarField& rDeltaT = localRDeltaT(); const word ddtName("ddt("+alpha.name()+','+rho.name()+','+vf.name()+')'); return tmp<GeometricField<Type, fvPatchField, volMesh>> ( GeometricField<Type, fvPatchField, volMesh>::New ( ddtName, rDeltaT *( alpha*rho*vf - alpha.oldTime()*rho.oldTime()*vf.oldTime() ) ) ); } template<class Type> tmp<GeometricField<Type, fvsPatchField, surfaceMesh>> localEulerDdtScheme<Type>::fvcDdt ( const GeometricField<Type, fvsPatchField, surfaceMesh>& sf ) { const surfaceScalarField& rDeltaT = localRDeltaTf(); const word ddtName("ddt("+sf.name()+')'); return GeometricField<Type, fvsPatchField, surfaceMesh>::New ( ddtName, rDeltaT*(sf - sf.oldTime()) ); } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*mesh().Vsc(); fvm.source() = rDeltaT*vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const dimensionedScalar& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*rho.value()*mesh().Vsc(); fvm.source() = rDeltaT*rho.value()*vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*rho.primitiveField()*mesh().Vsc(); fvm.source() = rDeltaT *rho.oldTime().primitiveField() *vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } template<class Type> tmp<fvMatrix<Type>> localEulerDdtScheme<Type>::fvmDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& vf ) { tmp<fvMatrix<Type>> tfvm ( new fvMatrix<Type> ( vf, alpha.dimensions()*rho.dimensions()*vf.dimensions()*dimVol/dimTime ) ); fvMatrix<Type>& fvm = tfvm.ref(); const scalarField& rDeltaT = localRDeltaT(); fvm.diag() = rDeltaT*alpha.primitiveField()*rho.primitiveField()*mesh().Vsc(); fvm.source() = rDeltaT *alpha.oldTime().primitiveField() *rho.oldTime().primitiveField() *vf.oldTime().primitiveField()*mesh().Vsc(); return tfvm; } /* // Courant number limited formulation template<class Type> tmp<surfaceScalarField> localEulerDdtScheme<Type>::fvcDdtPhiCoeff ( const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi, const fluxFieldType& phiCorr ) { // Courant number limited formulation tmp<surfaceScalarField> tddtCouplingCoeff = scalar(1) - min ( mag(phiCorr)*mesh().deltaCoeffs() /(fvc::interpolate(localRDeltaT())*mesh().magSf()), scalar(1) ); surfaceScalarField& ddtCouplingCoeff = tddtCouplingCoeff.ref(); surfaceScalarField::Boundary& ccbf = ddtCouplingCoeff.boundaryFieldRef(); forAll(U.boundaryField(), patchi) { if ( U.boundaryField()[patchi].fixesValue() || isA<cyclicAMIFvPatch>(mesh().boundary()[patchi]) ) { ccbf[patchi] = 0.0; } } if (debug > 1) { InfoInFunction << "ddtCouplingCoeff mean max min = " << gAverage(ddtCouplingCoeff.primitiveField()) << " " << gMax(ddtCouplingCoeff.primitiveField()) << " " << gMin(ddtCouplingCoeff.primitiveField()) << endl; } return tddtCouplingCoeff; } */ template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtUfCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr ( phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(U.oldTime(), phiUf0, phiCorr) *rDeltaT*phiCorr ) ); } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtPhiCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(U.oldTime(), phi.oldTime(), phiCorr) *rDeltaT*phiCorr ) ); } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtUfCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); if ( U.dimensions() == dimVelocity && Uf.dimensions() == dimDensity*dimVelocity ) { GeometricField<Type, fvPatchField, volMesh> rhoU0 ( rho.oldTime()*U.oldTime() ); fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr(phiUf0 - fvc::dotInterpolate(mesh().Sf(), rhoU0)); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff(rhoU0, phiUf0, phiCorr, rho.oldTime()) *rDeltaT*phiCorr ) ); } else if ( U.dimensions() == dimDensity*dimVelocity && Uf.dimensions() == dimDensity*dimVelocity ) { fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime()); fluxFieldType phiCorr ( phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + Uf.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( U.oldTime(), phiUf0, phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else { FatalErrorInFunction << "dimensions of Uf are not correct" << abort(FatalError); return fluxFieldType::null(); } } template<class Type> tmp<typename localEulerDdtScheme<Type>::fluxFieldType> localEulerDdtScheme<Type>::fvcDdtPhiCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ) { const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT())); if ( U.dimensions() == dimVelocity && phi.dimensions() == rho.dimensions()*dimFlux ) { GeometricField<Type, fvPatchField, volMesh> rhoU0 ( rho.oldTime()*U.oldTime() ); fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), rhoU0) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( rhoU0, phi.oldTime(), phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else if ( U.dimensions() == rho.dimensions()*dimVelocity && phi.dimensions() == rho.dimensions()*dimFlux ) { fluxFieldType phiCorr ( phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime()) ); return tmp<fluxFieldType> ( new fluxFieldType ( IOobject ( "ddtCorr(" + rho.name() + ',' + U.name() + ',' + phi.name() + ')', mesh().time().timeName(), mesh() ), this->fvcDdtPhiCoeff ( U.oldTime(), phi.oldTime(), phiCorr, rho.oldTime() )*rDeltaT*phiCorr ) ); } else { FatalErrorInFunction << "dimensions of phi are not correct" << abort(FatalError); return fluxFieldType::null(); } } template<class Type> tmp<surfaceScalarField> localEulerDdtScheme<Type>::meshPhi ( const GeometricField<Type, fvPatchField, volMesh>& ) { return surfaceScalarField::New ( "meshPhi", mesh(), dimensionedScalar(dimVolume/dimTime, 0) ); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // ************************************************************************* //
OpenFOAM/OpenFOAM-dev
src/finiteVolume/finiteVolume/ddtSchemes/localEulerDdtScheme/localEulerDdtScheme.C
C++
gpl-3.0
15,508
package org.emdev.ui.uimanager; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.view.View; import android.view.Window; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.emdev.BaseDroidApp; @TargetApi(11) public class UIManager3x implements IUIManager { private static final String SYS_UI_CLS = "com.android.systemui.SystemUIService"; private static final String SYS_UI_PKG = "com.android.systemui"; private static final ComponentName SYS_UI = new ComponentName(SYS_UI_PKG, SYS_UI_CLS); private static final String SU_PATH1 = "/system/bin/su"; private static final String SU_PATH2 = "/system/xbin/su"; private static final String AM_PATH = "/system/bin/am"; private static final Map<ComponentName, Data> data = new HashMap<ComponentName, Data>() { /** * */ private static final long serialVersionUID = -6627308913610357179L; @Override public Data get(final Object key) { Data existing = super.get(key); if (existing == null) { existing = new Data(); put((ComponentName) key, existing); } return existing; } }; @Override public void setTitleVisible(final Activity activity, final boolean visible, final boolean firstTime) { if (firstTime) { try { final Window window = activity.getWindow(); window.requestFeature(Window.FEATURE_ACTION_BAR); window.requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); activity.setProgressBarIndeterminate(true); activity.setProgressBarIndeterminateVisibility(true); window.setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 1); } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } try { if (visible) { activity.getActionBar().show(); } else { activity.getActionBar().hide(); } data.get(activity.getComponentName()).titleVisible = visible; } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } @Override public boolean isTitleVisible(final Activity activity) { return data.get(activity.getComponentName()).titleVisible; } @Override public void setProgressSpinnerVisible(Activity activity, boolean visible) { activity.setProgressBarIndeterminateVisibility(visible); activity.getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, visible ? 1 : 0); } @Override public void setFullScreenMode(final Activity activity, final View view, final boolean fullScreen) { data.get(activity.getComponentName()).fullScreen = fullScreen; if (fullScreen) { stopSystemUI(activity); } else { startSystemUI(activity); } } @Override public void openOptionsMenu(final Activity activity, final View view) { activity.openOptionsMenu(); } @Override public void invalidateOptionsMenu(final Activity activity) { activity.invalidateOptionsMenu(); } @Override public void onMenuOpened(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onMenuClosed(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onPause(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onResume(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onDestroy(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public boolean isTabletUi(final Activity activity) { return true; } protected void startSystemUI(final Activity activity) { if (isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(false, activity, AM_PATH, "startservice", "-n", SYS_UI.flattenToString()); } protected void stopSystemUI(final Activity activity) { if (!isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(true); return; } final String su = getSuPath(); if (su == null) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(true, activity, su, "-c", "service call activity 79 s16 " + SYS_UI_PKG); } protected boolean isSystemUIRunning() { final Context ctx = BaseDroidApp.context; final ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> rsiList = am.getRunningServices(1000); for (final RunningServiceInfo rsi : rsiList) { LCTX.d("Service: " + rsi.service); if (SYS_UI.equals(rsi.service)) { LCTX.e("System UI service found"); return true; } } return false; } protected void exec(final boolean expected, final Activity activity, final String... as) { (new Thread(new Runnable() { @Override public void run() { try { final boolean result = execImpl(as); data.get(activity.getComponentName()).fullScreenState.set(result ? expected : !expected); } catch (final Throwable th) { LCTX.e("Changing full screen mode failed: " + th.getCause()); data.get(activity.getComponentName()).fullScreenState.set(!expected); } } })).start(); } private boolean execImpl(final String... as) { try { LCTX.d("Execute: " + Arrays.toString(as)); final Process process = Runtime.getRuntime().exec(as); final InputStreamReader r = new InputStreamReader(process.getInputStream()); final StringWriter w = new StringWriter(); final char ac[] = new char[8192]; int i = 0; do { i = r.read(ac); if (i > 0) { w.write(ac, 0, i); } } while (i != -1); r.close(); process.waitFor(); final int exitValue = process.exitValue(); final String text = w.toString(); LCTX.d("Result code: " + exitValue); LCTX.d("Output:\n" + text); return 0 == exitValue; } catch (final IOException e) { throw new IllegalStateException(e); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } private static String getSuPath() { final File su1 = new File(SU_PATH1); if (su1.exists() && su1.isFile() && su1.canExecute()) { return SU_PATH1; } final File su2 = new File(SU_PATH2); if (su2.exists() && su2.isFile() && su2.canExecute()) { return SU_PATH2; } return null; } private static class Data { boolean fullScreen = false; boolean titleVisible = true; final AtomicBoolean fullScreenState = new AtomicBoolean(); } }
bonisamber/bookreader
Application/src/main/java/org/emdev/ui/uimanager/UIManager3x.java
Java
gpl-3.0
8,692
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare 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. Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_warfare.common.vehicles.types; import net.minecraft.block.Block; import net.minecraft.item.Item; import shadowmage.ancient_warfare.common.config.Config; import shadowmage.ancient_warfare.common.item.ItemLoader; import shadowmage.ancient_warfare.common.registry.ArmorRegistry; import shadowmage.ancient_warfare.common.registry.VehicleUpgradeRegistry; import shadowmage.ancient_warfare.common.research.ResearchGoal; import shadowmage.ancient_warfare.common.utils.ItemStackWrapperCrafting; import shadowmage.ancient_warfare.common.vehicles.VehicleBase; import shadowmage.ancient_warfare.common.vehicles.VehicleMovementType; import shadowmage.ancient_warfare.common.vehicles.VehicleVarHelpers.BallistaVarHelper; import shadowmage.ancient_warfare.common.vehicles.helpers.VehicleFiringVarsHelper; import shadowmage.ancient_warfare.common.vehicles.materials.VehicleMaterial; import shadowmage.ancient_warfare.common.vehicles.missiles.Ammo; public class VehicleTypeBoatBallista extends VehicleType { /** * @param typeNum */ public VehicleTypeBoatBallista(int typeNum) { super(typeNum); this.configName = "boat_ballista"; this.vehicleMaterial = VehicleMaterial.materialWood; this.materialCount = 5; this.movementType = VehicleMovementType.WATER; this.maxMissileWeight = 2.f; this.validAmmoTypes.add(Ammo.ammoBallistaBolt); this.validAmmoTypes.add(Ammo.ammoBallistaBoltFlame); this.validAmmoTypes.add(Ammo.ammoBallistaBoltExplosive); this.validAmmoTypes.add(Ammo.ammoBallistaBoltIron); this.ammoBySoldierRank.put(0, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(1, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(2, Ammo.ammoBallistaBoltFlame); this.validUpgrades.add(VehicleUpgradeRegistry.speedUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchDownUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchUpUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchExtUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.powerUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.reloadUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.aimUpgrade); this.validArmors.add(ArmorRegistry.armorStone); this.validArmors.add(ArmorRegistry.armorObsidian); this.validArmors.add(ArmorRegistry.armorIron); this.armorBaySize = 3; this.upgradeBaySize = 3; this.ammoBaySize = 6; this.storageBaySize = 0; this.addNeededResearchForMaterials(); this.addNeededResearch(0, ResearchGoal.vehicleTorsion1); this.addNeededResearch(1, ResearchGoal.vehicleTorsion2); this.addNeededResearch(2, ResearchGoal.vehicleTorsion3); this.addNeededResearch(3, ResearchGoal.vehicleTorsion4); this.addNeededResearch(4, ResearchGoal.vehicleTorsion5); this.addNeededResearch(0, ResearchGoal.vehicleMobility1); this.addNeededResearch(1, ResearchGoal.vehicleMobility2); this.addNeededResearch(2, ResearchGoal.vehicleMobility3); this.addNeededResearch(3, ResearchGoal.vehicleMobility4); this.addNeededResearch(4, ResearchGoal.vehicleMobility5); this.addNeededResearch(0, ResearchGoal.upgradeMechanics1); this.addNeededResearch(1, ResearchGoal.upgradeMechanics2); this.addNeededResearch(2, ResearchGoal.upgradeMechanics3); this.addNeededResearch(3, ResearchGoal.upgradeMechanics4); this.addNeededResearch(4, ResearchGoal.upgradeMechanics5); this.additionalMaterials.add(new ItemStackWrapperCrafting(Item.silk, 8, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.torsionUnit, 2, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.equipmentBay, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.mobilityUnit, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(Block.cactus, 2, false, false)); this.width = 2.7f; this.height = 1.4f; this.baseStrafeSpeed = 2.f; this.baseForwardSpeed = 6.2f*0.05f; this.turretForwardsOffset = 23*0.0625f; this.turretVerticalOffset = 1.325f; this.accuracy = 0.98f; this.basePitchMax = 15; this.basePitchMin = -15; this.baseMissileVelocityMax = 42.f;//stand versions should have higher velocity, as should fixed version--i.e. mobile turret should have the worst of all versions this.riderForwardsOffset = -1.0f ; this.riderVerticalOffset = 0.7f; this.shouldRiderSit = true; this.isMountable = true; this.isDrivable = true;//adjust based on isMobile or not this.isCombatEngine = true; this.canAdjustPitch = true; this.canAdjustPower = false; this.canAdjustYaw = true; this.turretRotationMax=360.f;//adjust based on mobile/stand fixed (0), stand fixed(90'), or mobile or stand turret (360) this.displayName = "item.vehicleSpawner.18"; this.displayTooltip.add("item.vehicleSpawner.tooltip.torsion"); this.displayTooltip.add("item.vehicleSpawner.tooltip.boat"); this.displayTooltip.add("item.vehicleSpawner.tooltip.fullturret"); } @Override public String getTextureForMaterialLevel(int level) { switch(level) { case 0: return Config.texturePath + "models/boatBallista1.png"; case 1: return Config.texturePath + "models/boatBallista2.png"; case 2: return Config.texturePath + "models/boatBallista3.png"; case 3: return Config.texturePath + "models/boatBallista4.png"; case 4: return Config.texturePath + "models/boatBallista5.png"; default: return Config.texturePath + "models/boatBallista1.png"; } } @Override public VehicleFiringVarsHelper getFiringVarsHelper(VehicleBase veh) { return new BallistaVarHelper(veh); } }
shadowmage45/AncientWarfare
AncientWarfare/src/shadowmage/ancient_warfare/common/vehicles/types/VehicleTypeBoatBallista.java
Java
gpl-3.0
6,768
<?php $element = $variables['element']; // Special handling for form elements. if (isset($element['#array_parents'])) { // Assign an html ID. if (!isset($element['#attributes']['id'])) { $element['#attributes']['id'] = $element['#id']; } // Add the 'form-wrapper' class. $element['#attributes']['class'][] = 'form-wrapper'; } print '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>'; ?>
sistemi-territoriali/StatPortalOpenData
sp-odata/sites/all/modules/spodata/metadata/theme/metadata_tree_filter.tpl.php
PHP
gpl-3.0
462
#pragma strict var playerFinalScore: int; var Users: List.< GameObject >; var userData: GameObject[]; var maxPlayers: int; var gameManager: GameObject; var currentPlayer: int; var currentName: String; function Awake () { //var users :GameObject = GameObject.Find("_UserControllerFB"); userData = GameObject.FindGameObjectsWithTag("Player"); } function Start() { gameManager = GameObject.Find("__GameManager"); NotificationCenter.DefaultCenter().AddObserver(this, "PlayerChanger"); } function Update () { if(Users.Count>0) playerFinalScore = Users[0].GetComponent(_GameManager).playerFinalScore; } function PlayerChanger() { currentPlayer++; for(var i: int; i<Users.Count; i++) { if(i!=currentPlayer)Users[i].SetActive(false); else Users[i].SetActive(true); } print("Change Player"); if(currentPlayer>maxPlayers) currentPlayer=0; } function OnLevelWasLoaded(level: int) { maxPlayers = userData.Length; gameManager = GameObject.Find("__GameManager"); for(var i: int; i< userData.Length; i++) { if(i!=0)Users[i].SetActive(false); Users[i].name = userData[i].name; currentName = Users[0].name; Users[i].transform.parent = gameManager.transform; } }
RomanKorchmenko/BowlingFX
BowlingFX/Assets/ScoreTransfer.js
JavaScript
gpl-3.0
1,210
package com.andyadc.concurrency.latch; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; /** * @author andaicheng * @version 2017/3/10 */ public class LatchDemo_1 { public static void main(String[] args) throws Exception { int num = 10; //发令枪只只响一次 CountDownLatch begin = new CountDownLatch(1); //参与跑步人数 CountDownLatch end = new CountDownLatch(num); ExecutorService es = Executors.newFixedThreadPool(num); //记录跑步成绩 List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < num; i++) { futures.add(es.submit(new Runner(begin, end))); } //预备 TimeUnit.SECONDS.sleep(10); //发令枪响 begin.countDown(); //等待跑者跑完 end.await(); int sum = 0; for (Future<Integer> f : futures) { sum += f.get(); } System.out.println("平均分数: " + (float) (sum / num)); } } class Runner implements Callable<Integer> { //开始信号 private CountDownLatch begin; //结束信号 private CountDownLatch end; public Runner(CountDownLatch begin, CountDownLatch end) { this.begin = begin; this.end = end; } @Override public Integer call() throws Exception { //跑步成绩 int score = new Random().nextInt(10); //等待发令枪响 begin.await(); TimeUnit.SECONDS.sleep(score); //跑步结束 end.countDown(); System.out.println("score:" + score); return score; } }
andyadc/java-study
concurrency-study/src/main/java/com/andyadc/concurrency/latch/LatchDemo_1.java
Java
gpl-3.0
1,769
package com.infamous.performance.activities; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.infamous.performance.R; import com.infamous.performance.util.ActivityThemeChangeInterface; import com.infamous.performance.util.Constants; import com.infamous.performance.util.Helpers; /** * Created by h0rn3t on 09.02.2014. * http://forum.xda-developers.com/member.php?u=4674443 */ public class checkSU extends Activity implements Constants, ActivityThemeChangeInterface { private boolean mIsLightTheme; private ProgressBar wait; private TextView info; private ImageView attn; SharedPreferences mPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setTheme(); setContentView(R.layout.check_su); wait=(ProgressBar) findViewById(R.id.wait); info=(TextView) findViewById(R.id.info); attn=(ImageView) findViewById(R.id.attn); if(mPreferences.getBoolean("booting",false)) { info.setText(getString(R.string.boot_wait)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else { new TestSU().execute(); } } private class TestSU extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { SystemClock.sleep(1000); final Boolean canSu = Helpers.checkSu(); final Boolean canBb = Helpers.binExist("busybox")!=null; if (canSu && canBb) return "ok"; else return "nok"; } @Override protected void onPostExecute(String result) { if(result.equals("nok")){ //mPreferences.edit().putBoolean("firstrun", true).commit(); info.setText(getString(R.string.su_failed_su_or_busybox)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else{ //mPreferences.edit().putBoolean("firstrun", false).commit(); Intent returnIntent = new Intent(); returnIntent.putExtra("r",result); setResult(RESULT_OK,returnIntent); finish(); } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } @Override public boolean isThemeChanged() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); return is_light_theme != mIsLightTheme; } @Override public void setTheme() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); mIsLightTheme = is_light_theme; setTheme(is_light_theme ? R.style.Theme_Light : R.style.Theme_Dark); } @Override public void onResume() { super.onResume(); } }
InfamousProductions/Infamous_Performance
src/com/infamous/performance/activities/checkSU.java
Java
gpl-3.0
3,396
/* * Copyright (C) 2011 The Android Open Source Project * * 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. */ #define LOG_TAG "Posix" #include "AsynchronousCloseMonitor.h" #include "cutils/log.h" #include "ExecStrings.h" #include "JNIHelp.h" #include "JniConstants.h" #include "JniException.h" #include "NetworkUtilities.h" #include "Portability.h" #include "readlink.h" #include "../../bionic/libc/dns/include/resolv_netid.h" // For android_getaddrinfofornet. #include "ScopedBytes.h" #include "ScopedLocalRef.h" #include "ScopedPrimitiveArray.h" #include "ScopedUtfChars.h" #include "toStringArray.h" #include "UniquePtr.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <netdb.h> #include <netinet/in.h> #include <poll.h> #include <pwd.h> #include <signal.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #ifndef __APPLE__ #include <sys/prctl.h> #endif #include <sys/socket.h> #include <sys/stat.h> #ifdef __APPLE__ #include <sys/statvfs.h> #endif #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/utsname.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> #ifndef __unused #define __unused __attribute__((__unused__)) #endif #define TO_JAVA_STRING(NAME, EXP) \ jstring NAME = env->NewStringUTF(EXP); \ if (NAME == NULL) return NULL; struct addrinfo_deleter { void operator()(addrinfo* p) const { if (p != NULL) { // bionic's freeaddrinfo(3) crashes when passed NULL. freeaddrinfo(p); } } }; /** * Used to retry networking system calls that can be interrupted with a signal. Unlike * TEMP_FAILURE_RETRY, this also handles the case where * AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal a close() or * Thread.interrupt(). Other signals that result in an EINTR result are ignored and the system call * is retried. * * Returns the result of the system call though a Java exception will be pending if the result is * -1: a SocketException if signaled via AsynchronousCloseMonitor, or ErrnoException for other * failures. */ #define NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \ return_type _rc = -1; \ do { \ bool _wasSignaled; \ int _syscallErrno; \ { \ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \ AsynchronousCloseMonitor _monitor(_fd); \ _rc = syscall_name(_fd, __VA_ARGS__); \ _syscallErrno = errno; \ _wasSignaled = _monitor.wasSignaled(); \ } \ if (_wasSignaled) { \ jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \ _rc = -1; \ break; \ } \ if (_rc == -1 && _syscallErrno != EINTR) { \ /* TODO: with a format string we could show the arguments too, like strace(1). */ \ throwErrnoException(jni_env, # syscall_name); \ break; \ } \ } while (_rc == -1); /* _syscallErrno == EINTR && !_wasSignaled */ \ _rc; }) /** * Used to retry system calls that can be interrupted with a signal. Unlike TEMP_FAILURE_RETRY, this * also handles the case where AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal * a close() or Thread.interrupt(). Other signals that result in an EINTR result are ignored and the * system call is retried. * * Returns the result of the system call though a Java exception will be pending if the result is * -1: an IOException if the file descriptor is already closed, a InterruptedIOException if signaled * via AsynchronousCloseMonitor, or ErrnoException for other failures. */ #define IO_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \ return_type _rc = -1; \ do { \ bool _wasSignaled; \ int _syscallErrno; \ { \ int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \ AsynchronousCloseMonitor _monitor(_fd); \ _rc = syscall_name(_fd, __VA_ARGS__); \ _syscallErrno = errno; \ _wasSignaled = _monitor.wasSignaled(); \ } \ if (_wasSignaled) { \ jniThrowException(jni_env, "java/io/InterruptedIOException", # syscall_name " interrupted"); \ _rc = -1; \ break; \ } \ if (_rc == -1 && _syscallErrno != EINTR) { \ /* TODO: with a format string we could show the arguments too, like strace(1). */ \ throwErrnoException(jni_env, # syscall_name); \ break; \ } \ } while (_rc == -1); /* && _syscallErrno == EINTR && !_wasSignaled */ \ _rc; }) static void throwException(JNIEnv* env, jclass exceptionClass, jmethodID ctor3, jmethodID ctor2, const char* functionName, int error) { jthrowable cause = NULL; if (env->ExceptionCheck()) { cause = env->ExceptionOccurred(); env->ExceptionClear(); } ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName)); if (detailMessage.get() == NULL) { // Not really much we can do here. We're probably dead in the water, // but let's try to stumble on... env->ExceptionClear(); } jobject exception; if (cause != NULL) { exception = env->NewObject(exceptionClass, ctor3, detailMessage.get(), error, cause); } else { exception = env->NewObject(exceptionClass, ctor2, detailMessage.get(), error); } env->Throw(reinterpret_cast<jthrowable>(exception)); } static void throwErrnoException(JNIEnv* env, const char* functionName) { int error = errno; static jmethodID ctor3 = env->GetMethodID(JniConstants::errnoExceptionClass, "<init>", "(Ljava/lang/String;ILjava/lang/Throwable;)V"); static jmethodID ctor2 = env->GetMethodID(JniConstants::errnoExceptionClass, "<init>", "(Ljava/lang/String;I)V"); throwException(env, JniConstants::errnoExceptionClass, ctor3, ctor2, functionName, error); } static void throwGaiException(JNIEnv* env, const char* functionName, int error) { // Cache the methods ids before we throw, so we don't call GetMethodID with a pending exception. static jmethodID ctor3 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>", "(Ljava/lang/String;ILjava/lang/Throwable;)V"); static jmethodID ctor2 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>", "(Ljava/lang/String;I)V"); if (errno != 0) { // EAI_SYSTEM should mean "look at errno instead", but both glibc and bionic seem to // mess this up. In particular, if you don't have INTERNET permission, errno will be EACCES // but you'll get EAI_NONAME or EAI_NODATA. So we want our GaiException to have a // potentially-relevant ErrnoException as its cause even if error != EAI_SYSTEM. // http://code.google.com/p/android/issues/detail?id=15722 throwErrnoException(env, functionName); // Deliberately fall through to throw another exception... } throwException(env, JniConstants::gaiExceptionClass, ctor3, ctor2, functionName, error); } template <typename rc_t> static rc_t throwIfMinusOne(JNIEnv* env, const char* name, rc_t rc) { if (rc == rc_t(-1)) { throwErrnoException(env, name); } return rc; } template <typename ScopedT> class IoVec { public: IoVec(JNIEnv* env, size_t bufferCount) : mEnv(env), mBufferCount(bufferCount) { } bool init(jobjectArray javaBuffers, jintArray javaOffsets, jintArray javaByteCounts) { // We can't delete our local references until after the I/O, so make sure we have room. if (mEnv->PushLocalFrame(mBufferCount + 16) < 0) { return false; } ScopedIntArrayRO offsets(mEnv, javaOffsets); if (offsets.get() == NULL) { return false; } ScopedIntArrayRO byteCounts(mEnv, javaByteCounts); if (byteCounts.get() == NULL) { return false; } // TODO: Linux actually has a 1024 buffer limit. glibc works around this, and we should too. // TODO: you can query the limit at runtime with sysconf(_SC_IOV_MAX). for (size_t i = 0; i < mBufferCount; ++i) { jobject buffer = mEnv->GetObjectArrayElement(javaBuffers, i); // We keep this local ref. mScopedBuffers.push_back(new ScopedT(mEnv, buffer)); jbyte* ptr = const_cast<jbyte*>(mScopedBuffers.back()->get()); if (ptr == NULL) { return false; } struct iovec iov; iov.iov_base = reinterpret_cast<void*>(ptr + offsets[i]); iov.iov_len = byteCounts[i]; mIoVec.push_back(iov); } return true; } ~IoVec() { for (size_t i = 0; i < mScopedBuffers.size(); ++i) { delete mScopedBuffers[i]; } mEnv->PopLocalFrame(NULL); } iovec* get() { return &mIoVec[0]; } size_t size() { return mBufferCount; } private: JNIEnv* mEnv; size_t mBufferCount; std::vector<iovec> mIoVec; std::vector<ScopedT*> mScopedBuffers; }; static jobject makeSocketAddress(JNIEnv* env, const sockaddr_storage& ss) { jint port; jobject inetAddress = sockaddrToInetAddress(env, ss, &port); if (inetAddress == NULL) { return NULL; } static jmethodID ctor = env->GetMethodID(JniConstants::inetSocketAddressClass, "<init>", "(Ljava/net/InetAddress;I)V"); return env->NewObject(JniConstants::inetSocketAddressClass, ctor, inetAddress, port); } static jobject makeStructPasswd(JNIEnv* env, const struct passwd& pw) { TO_JAVA_STRING(pw_name, pw.pw_name); TO_JAVA_STRING(pw_dir, pw.pw_dir); TO_JAVA_STRING(pw_shell, pw.pw_shell); static jmethodID ctor = env->GetMethodID(JniConstants::structPasswdClass, "<init>", "(Ljava/lang/String;IILjava/lang/String;Ljava/lang/String;)V"); return env->NewObject(JniConstants::structPasswdClass, ctor, pw_name, static_cast<jint>(pw.pw_uid), static_cast<jint>(pw.pw_gid), pw_dir, pw_shell); } static jobject makeStructStat(JNIEnv* env, const struct stat& sb) { static jmethodID ctor = env->GetMethodID(JniConstants::structStatClass, "<init>", "(JJIJIIJJJJJJJ)V"); return env->NewObject(JniConstants::structStatClass, ctor, static_cast<jlong>(sb.st_dev), static_cast<jlong>(sb.st_ino), static_cast<jint>(sb.st_mode), static_cast<jlong>(sb.st_nlink), static_cast<jint>(sb.st_uid), static_cast<jint>(sb.st_gid), static_cast<jlong>(sb.st_rdev), static_cast<jlong>(sb.st_size), static_cast<jlong>(sb.st_atime), static_cast<jlong>(sb.st_mtime), static_cast<jlong>(sb.st_ctime), static_cast<jlong>(sb.st_blksize), static_cast<jlong>(sb.st_blocks)); } static jobject makeStructStatVfs(JNIEnv* env, const struct statvfs& sb) { #if defined(__APPLE__) // Mac OS has no f_namelen field in struct statfs. jlong max_name_length = 255; // __DARWIN_MAXNAMLEN #else jlong max_name_length = static_cast<jlong>(sb.f_namemax); #endif static jmethodID ctor = env->GetMethodID(JniConstants::structStatVfsClass, "<init>", "(JJJJJJJJJJJ)V"); return env->NewObject(JniConstants::structStatVfsClass, ctor, static_cast<jlong>(sb.f_bsize), static_cast<jlong>(sb.f_frsize), static_cast<jlong>(sb.f_blocks), static_cast<jlong>(sb.f_bfree), static_cast<jlong>(sb.f_bavail), static_cast<jlong>(sb.f_files), static_cast<jlong>(sb.f_ffree), static_cast<jlong>(sb.f_favail), static_cast<jlong>(sb.f_fsid), static_cast<jlong>(sb.f_flag), max_name_length); } static jobject makeStructLinger(JNIEnv* env, const struct linger& l) { static jmethodID ctor = env->GetMethodID(JniConstants::structLingerClass, "<init>", "(II)V"); return env->NewObject(JniConstants::structLingerClass, ctor, l.l_onoff, l.l_linger); } static jobject makeStructTimeval(JNIEnv* env, const struct timeval& tv) { static jmethodID ctor = env->GetMethodID(JniConstants::structTimevalClass, "<init>", "(JJ)V"); return env->NewObject(JniConstants::structTimevalClass, ctor, static_cast<jlong>(tv.tv_sec), static_cast<jlong>(tv.tv_usec)); } static jobject makeStructUcred(JNIEnv* env, const struct ucred& u __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "unimplemented support for ucred on a Mac"); return NULL; #else static jmethodID ctor = env->GetMethodID(JniConstants::structUcredClass, "<init>", "(III)V"); return env->NewObject(JniConstants::structUcredClass, ctor, u.pid, u.uid, u.gid); #endif } static jobject makeStructUtsname(JNIEnv* env, const struct utsname& buf) { TO_JAVA_STRING(sysname, buf.sysname); TO_JAVA_STRING(nodename, buf.nodename); TO_JAVA_STRING(release, buf.release); TO_JAVA_STRING(version, buf.version); TO_JAVA_STRING(machine, buf.machine); static jmethodID ctor = env->GetMethodID(JniConstants::structUtsnameClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); return env->NewObject(JniConstants::structUtsnameClass, ctor, sysname, nodename, release, version, machine); }; static bool fillIfreq(JNIEnv* env, jstring javaInterfaceName, struct ifreq& req) { ScopedUtfChars interfaceName(env, javaInterfaceName); if (interfaceName.c_str() == NULL) { return false; } memset(&req, 0, sizeof(req)); strncpy(req.ifr_name, interfaceName.c_str(), sizeof(req.ifr_name)); req.ifr_name[sizeof(req.ifr_name) - 1] = '\0'; return true; } static bool fillInetSocketAddress(JNIEnv* env, jint rc, jobject javaInetSocketAddress, const sockaddr_storage& ss) { if (rc == -1 || javaInetSocketAddress == NULL) { return true; } // Fill out the passed-in InetSocketAddress with the sender's IP address and port number. jint port; jobject sender = sockaddrToInetAddress(env, ss, &port); if (sender == NULL) { return false; } static jfieldID addressFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "addr", "Ljava/net/InetAddress;"); static jfieldID portFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "port", "I"); env->SetObjectField(javaInetSocketAddress, addressFid, sender); env->SetIntField(javaInetSocketAddress, portFid, port); return true; } static jobject doStat(JNIEnv* env, jstring javaPath, bool isLstat) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } struct stat sb; int rc = isLstat ? TEMP_FAILURE_RETRY(lstat(path.c_str(), &sb)) : TEMP_FAILURE_RETRY(stat(path.c_str(), &sb)); if (rc == -1) { throwErrnoException(env, isLstat ? "lstat" : "stat"); return NULL; } return makeStructStat(env, sb); } static jobject doGetSockName(JNIEnv* env, jobject javaFd, bool is_sockname) { int fd = jniGetFDFromFileDescriptor(env, javaFd); sockaddr_storage ss; sockaddr* sa = reinterpret_cast<sockaddr*>(&ss); socklen_t byteCount = sizeof(ss); memset(&ss, 0, byteCount); int rc = is_sockname ? TEMP_FAILURE_RETRY(getsockname(fd, sa, &byteCount)) : TEMP_FAILURE_RETRY(getpeername(fd, sa, &byteCount)); if (rc == -1) { throwErrnoException(env, is_sockname ? "getsockname" : "getpeername"); return NULL; } return makeSocketAddress(env, ss); } class Passwd { public: Passwd(JNIEnv* env) : mEnv(env), mResult(NULL) { mBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX); mBuffer.reset(new char[mBufferSize]); } jobject getpwnam(const char* name) { return process("getpwnam_r", getpwnam_r(name, &mPwd, mBuffer.get(), mBufferSize, &mResult)); } jobject getpwuid(uid_t uid) { return process("getpwuid_r", getpwuid_r(uid, &mPwd, mBuffer.get(), mBufferSize, &mResult)); } struct passwd* get() { return mResult; } private: jobject process(const char* syscall, int error) { if (mResult == NULL) { errno = error; throwErrnoException(mEnv, syscall); return NULL; } return makeStructPasswd(mEnv, *mResult); } JNIEnv* mEnv; UniquePtr<char[]> mBuffer; size_t mBufferSize; struct passwd mPwd; struct passwd* mResult; }; static jobject Posix_accept(JNIEnv* env, jobject, jobject javaFd, jobject javaInetSocketAddress) { sockaddr_storage ss; socklen_t sl = sizeof(ss); memset(&ss, 0, sizeof(ss)); sockaddr* peer = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL; socklen_t* peerLength = (javaInetSocketAddress != NULL) ? &sl : 0; jint clientFd = NET_FAILURE_RETRY(env, int, accept, javaFd, peer, peerLength); if (clientFd == -1 || !fillInetSocketAddress(env, clientFd, javaInetSocketAddress, ss)) { close(clientFd); return NULL; } return (clientFd != -1) ? jniCreateFileDescriptor(env, clientFd) : NULL; } static jboolean Posix_access(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return JNI_FALSE; } int rc = TEMP_FAILURE_RETRY(access(path.c_str(), mode)); if (rc == -1) { throwErrnoException(env, "access"); } return (rc == 0); } static void Posix_bind(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) { return; } const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss); // We don't need the return value because we'll already have thrown. (void) NET_FAILURE_RETRY(env, int, bind, javaFd, sa, sa_len); } static void Posix_chmod(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "chmod", TEMP_FAILURE_RETRY(chmod(path.c_str(), mode))); } static void Posix_chown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "chown", TEMP_FAILURE_RETRY(chown(path.c_str(), uid, gid))); } static void Posix_close(JNIEnv* env, jobject, jobject javaFd) { // Get the FileDescriptor's 'fd' field and clear it. // We need to do this before we can throw an IOException (http://b/3222087). int fd = jniGetFDFromFileDescriptor(env, javaFd); jniSetFileDescriptorOfFD(env, javaFd, -1); // Even if close(2) fails with EINTR, the fd will have been closed. // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd. // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html throwIfMinusOne(env, "close", close(fd)); } static void Posix_connect(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) { return; } const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss); // We don't need the return value because we'll already have thrown. (void) NET_FAILURE_RETRY(env, int, connect, javaFd, sa, sa_len); } static jobject Posix_dup(JNIEnv* env, jobject, jobject javaOldFd) { int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd); int newFd = throwIfMinusOne(env, "dup", TEMP_FAILURE_RETRY(dup(oldFd))); return (newFd != -1) ? jniCreateFileDescriptor(env, newFd) : NULL; } static jobject Posix_dup2(JNIEnv* env, jobject, jobject javaOldFd, jint newFd) { int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd); int fd = throwIfMinusOne(env, "dup2", TEMP_FAILURE_RETRY(dup2(oldFd, newFd))); return (fd != -1) ? jniCreateFileDescriptor(env, fd) : NULL; } static jobjectArray Posix_environ(JNIEnv* env, jobject) { extern char** environ; // Standard, but not in any header file. return toStringArray(env, environ); } static void Posix_execve(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv, jobjectArray javaEnvp) { ScopedUtfChars path(env, javaFilename); if (path.c_str() == NULL) { return; } ExecStrings argv(env, javaArgv); ExecStrings envp(env, javaEnvp); execve(path.c_str(), argv.get(), envp.get()); throwErrnoException(env, "execve"); } static void Posix_execv(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv) { ScopedUtfChars path(env, javaFilename); if (path.c_str() == NULL) { return; } ExecStrings argv(env, javaArgv); execv(path.c_str(), argv.get()); throwErrnoException(env, "execv"); } static void Posix_fchmod(JNIEnv* env, jobject, jobject javaFd, jint mode) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fchmod", TEMP_FAILURE_RETRY(fchmod(fd, mode))); } static void Posix_fchown(JNIEnv* env, jobject, jobject javaFd, jint uid, jint gid) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fchown", TEMP_FAILURE_RETRY(fchown(fd, uid, gid))); } static jint Posix_fcntlVoid(JNIEnv* env, jobject, jobject javaFd, jint cmd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd))); } static jint Posix_fcntlLong(JNIEnv* env, jobject, jobject javaFd, jint cmd, jlong arg) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd, arg))); } static jint Posix_fcntlFlock(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaFlock) { static jfieldID typeFid = env->GetFieldID(JniConstants::structFlockClass, "l_type", "S"); static jfieldID whenceFid = env->GetFieldID(JniConstants::structFlockClass, "l_whence", "S"); static jfieldID startFid = env->GetFieldID(JniConstants::structFlockClass, "l_start", "J"); static jfieldID lenFid = env->GetFieldID(JniConstants::structFlockClass, "l_len", "J"); static jfieldID pidFid = env->GetFieldID(JniConstants::structFlockClass, "l_pid", "I"); struct flock64 lock; memset(&lock, 0, sizeof(lock)); lock.l_type = env->GetShortField(javaFlock, typeFid); lock.l_whence = env->GetShortField(javaFlock, whenceFid); lock.l_start = env->GetLongField(javaFlock, startFid); lock.l_len = env->GetLongField(javaFlock, lenFid); lock.l_pid = env->GetIntField(javaFlock, pidFid); int rc = IO_FAILURE_RETRY(env, int, fcntl, javaFd, cmd, &lock); if (rc != -1) { env->SetShortField(javaFlock, typeFid, lock.l_type); env->SetShortField(javaFlock, whenceFid, lock.l_whence); env->SetLongField(javaFlock, startFid, lock.l_start); env->SetLongField(javaFlock, lenFid, lock.l_len); env->SetIntField(javaFlock, pidFid, lock.l_pid); } return rc; } static void Posix_fdatasync(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fdatasync", TEMP_FAILURE_RETRY(fdatasync(fd))); } static jobject Posix_fstat(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct stat sb; int rc = TEMP_FAILURE_RETRY(fstat(fd, &sb)); if (rc == -1) { throwErrnoException(env, "fstat"); return NULL; } return makeStructStat(env, sb); } static jobject Posix_fstatvfs(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct statvfs sb; int rc = TEMP_FAILURE_RETRY(fstatvfs(fd, &sb)); if (rc == -1) { throwErrnoException(env, "fstatvfs"); return NULL; } return makeStructStatVfs(env, sb); } static void Posix_fsync(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "fsync", TEMP_FAILURE_RETRY(fsync(fd))); } static void Posix_ftruncate(JNIEnv* env, jobject, jobject javaFd, jlong length) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "ftruncate", TEMP_FAILURE_RETRY(ftruncate64(fd, length))); } static jstring Posix_gai_strerror(JNIEnv* env, jobject, jint error) { return env->NewStringUTF(gai_strerror(error)); } static jobjectArray Posix_android_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jobject javaHints, jint netId) { ScopedUtfChars node(env, javaNode); if (node.c_str() == NULL) { return NULL; } static jfieldID flagsFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_flags", "I"); static jfieldID familyFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_family", "I"); static jfieldID socktypeFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_socktype", "I"); static jfieldID protocolFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_protocol", "I"); addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = env->GetIntField(javaHints, flagsFid); hints.ai_family = env->GetIntField(javaHints, familyFid); hints.ai_socktype = env->GetIntField(javaHints, socktypeFid); hints.ai_protocol = env->GetIntField(javaHints, protocolFid); addrinfo* addressList = NULL; errno = 0; int rc = android_getaddrinfofornet(node.c_str(), NULL, &hints, netId, 0, &addressList); UniquePtr<addrinfo, addrinfo_deleter> addressListDeleter(addressList); if (rc != 0) { throwGaiException(env, "android_getaddrinfo", rc); return NULL; } // Count results so we know how to size the output array. int addressCount = 0; for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) { if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) { ++addressCount; } else { ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family); } } if (addressCount == 0) { return NULL; } // Prepare output array. jobjectArray result = env->NewObjectArray(addressCount, JniConstants::inetAddressClass, NULL); if (result == NULL) { return NULL; } // Examine returned addresses one by one, save them in the output array. int index = 0; for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) { if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) { // Unknown address family. Skip this address. ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family); continue; } // Convert each IP address into a Java byte array. sockaddr_storage& address = *reinterpret_cast<sockaddr_storage*>(ai->ai_addr); ScopedLocalRef<jobject> inetAddress(env, sockaddrToInetAddress(env, address, NULL)); if (inetAddress.get() == NULL) { return NULL; } env->SetObjectArrayElement(result, index, inetAddress.get()); ++index; } return result; } static jint Posix_getegid(JNIEnv*, jobject) { return getegid(); } static jint Posix_geteuid(JNIEnv*, jobject) { return geteuid(); } static jint Posix_getgid(JNIEnv*, jobject) { return getgid(); } static jstring Posix_getenv(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } return env->NewStringUTF(getenv(name.c_str())); } static jstring Posix_getnameinfo(JNIEnv* env, jobject, jobject javaAddress, jint flags) { sockaddr_storage ss; socklen_t sa_len; if (!inetAddressToSockaddrVerbatim(env, javaAddress, 0, ss, sa_len)) { return NULL; } char buf[NI_MAXHOST]; // NI_MAXHOST is longer than INET6_ADDRSTRLEN. errno = 0; int rc = getnameinfo(reinterpret_cast<sockaddr*>(&ss), sa_len, buf, sizeof(buf), NULL, 0, flags); if (rc != 0) { throwGaiException(env, "getnameinfo", rc); return NULL; } return env->NewStringUTF(buf); } static jobject Posix_getpeername(JNIEnv* env, jobject, jobject javaFd) { return doGetSockName(env, javaFd, false); } static jint Posix_getpid(JNIEnv*, jobject) { return getpid(); } static jint Posix_getppid(JNIEnv*, jobject) { return getppid(); } static jobject Posix_getpwnam(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } return Passwd(env).getpwnam(name.c_str()); } static jobject Posix_getpwuid(JNIEnv* env, jobject, jint uid) { return Passwd(env).getpwuid(uid); } static jobject Posix_getsockname(JNIEnv* env, jobject, jobject javaFd) { return doGetSockName(env, javaFd, true); } static jint Posix_getsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); u_char result = 0; socklen_t size = sizeof(result); throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size))); return result; } static jobject Posix_getsockoptInAddr(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); sockaddr_storage ss; memset(&ss, 0, sizeof(ss)); ss.ss_family = AF_INET; // This is only for the IPv4-only IP_MULTICAST_IF. sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(&ss); socklen_t size = sizeof(sa->sin_addr); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &sa->sin_addr, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return sockaddrToInetAddress(env, ss, NULL); } static jint Posix_getsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); jint result = 0; socklen_t size = sizeof(result); throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size))); return result; } static jobject Posix_getsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct linger l; socklen_t size = sizeof(l); memset(&l, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &l, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructLinger(env, l); } static jobject Posix_getsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct timeval tv; socklen_t size = sizeof(tv); memset(&tv, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &tv, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructTimeval(env, tv); } static jobject Posix_getsockoptUcred(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) { int fd = jniGetFDFromFileDescriptor(env, javaFd); struct ucred u; socklen_t size = sizeof(u); memset(&u, 0, size); int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &u, &size)); if (rc == -1) { throwErrnoException(env, "getsockopt"); return NULL; } return makeStructUcred(env, u); } static jint Posix_gettid(JNIEnv* env __unused, jobject) { #if defined(__APPLE__) uint64_t owner; int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6 if (rc != 0) { throwErrnoException(env, "gettid"); return 0; } return static_cast<jint>(owner); #else // Neither bionic nor glibc exposes gettid(2). return syscall(__NR_gettid); #endif } static jint Posix_getuid(JNIEnv*, jobject) { return getuid(); } static jstring Posix_if_indextoname(JNIEnv* env, jobject, jint index) { char buf[IF_NAMESIZE]; char* name = if_indextoname(index, buf); // if_indextoname(3) returns NULL on failure, which will come out of NewStringUTF unscathed. // There's no useful information in errno, so we don't bother throwing. Callers can null-check. return env->NewStringUTF(name); } static jobject Posix_inet_pton(JNIEnv* env, jobject, jint family, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return NULL; } sockaddr_storage ss; memset(&ss, 0, sizeof(ss)); // sockaddr_in and sockaddr_in6 are at the same address, so we can use either here. void* dst = &reinterpret_cast<sockaddr_in*>(&ss)->sin_addr; if (inet_pton(family, name.c_str(), dst) != 1) { return NULL; } ss.ss_family = family; return sockaddrToInetAddress(env, ss, NULL); } static jobject Posix_ioctlInetAddress(JNIEnv* env, jobject, jobject javaFd, jint cmd, jstring javaInterfaceName) { struct ifreq req; if (!fillIfreq(env, javaInterfaceName, req)) { return NULL; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &req))); if (rc == -1) { return NULL; } return sockaddrToInetAddress(env, reinterpret_cast<sockaddr_storage&>(req.ifr_addr), NULL); } static jint Posix_ioctlInt(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaArg) { // This is complicated because ioctls may return their result by updating their argument // or via their return value, so we need to support both. int fd = jniGetFDFromFileDescriptor(env, javaFd); static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I"); jint arg = env->GetIntField(javaArg, valueFid); int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &arg))); if (!env->ExceptionCheck()) { env->SetIntField(javaArg, valueFid, arg); } return rc; } static jboolean Posix_isatty(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return TEMP_FAILURE_RETRY(isatty(fd)) == 1; } static void Posix_kill(JNIEnv* env, jobject, jint pid, jint sig) { throwIfMinusOne(env, "kill", TEMP_FAILURE_RETRY(kill(pid, sig))); } static void Posix_lchown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "lchown", TEMP_FAILURE_RETRY(lchown(path.c_str(), uid, gid))); } static void Posix_link(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "link", TEMP_FAILURE_RETRY(link(oldPath.c_str(), newPath.c_str()))); } static void Posix_listen(JNIEnv* env, jobject, jobject javaFd, jint backlog) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "listen", TEMP_FAILURE_RETRY(listen(fd, backlog))); } static jlong Posix_lseek(JNIEnv* env, jobject, jobject javaFd, jlong offset, jint whence) { int fd = jniGetFDFromFileDescriptor(env, javaFd); return throwIfMinusOne(env, "lseek", TEMP_FAILURE_RETRY(lseek64(fd, offset, whence))); } static jobject Posix_lstat(JNIEnv* env, jobject, jstring javaPath) { return doStat(env, javaPath, true); } static void Posix_mincore(JNIEnv* env, jobject, jlong address, jlong byteCount, jbyteArray javaVector) { ScopedByteArrayRW vector(env, javaVector); if (vector.get() == NULL) { return; } void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); unsigned char* vec = reinterpret_cast<unsigned char*>(vector.get()); throwIfMinusOne(env, "mincore", TEMP_FAILURE_RETRY(mincore(ptr, byteCount, vec))); } static void Posix_mkdir(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "mkdir", TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode))); } static void Posix_mkfifo(JNIEnv* env, jobject, jstring javaPath, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "mkfifo", TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode))); } static void Posix_mlock(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "mlock", TEMP_FAILURE_RETRY(mlock(ptr, byteCount))); } static jlong Posix_mmap(JNIEnv* env, jobject, jlong address, jlong byteCount, jint prot, jint flags, jobject javaFd, jlong offset) { int fd = jniGetFDFromFileDescriptor(env, javaFd); void* suggestedPtr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); void* ptr = mmap(suggestedPtr, byteCount, prot, flags, fd, offset); if (ptr == MAP_FAILED) { throwErrnoException(env, "mmap"); } return static_cast<jlong>(reinterpret_cast<uintptr_t>(ptr)); } static void Posix_msync(JNIEnv* env, jobject, jlong address, jlong byteCount, jint flags) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "msync", TEMP_FAILURE_RETRY(msync(ptr, byteCount, flags))); } static void Posix_munlock(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "munlock", TEMP_FAILURE_RETRY(munlock(ptr, byteCount))); } static void Posix_munmap(JNIEnv* env, jobject, jlong address, jlong byteCount) { void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address)); throwIfMinusOne(env, "munmap", TEMP_FAILURE_RETRY(munmap(ptr, byteCount))); } static jobject Posix_open(JNIEnv* env, jobject, jstring javaPath, jint flags, jint mode) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } int fd = throwIfMinusOne(env, "open", TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode))); return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL; } static jobjectArray Posix_pipe(JNIEnv* env, jobject) { int fds[2]; throwIfMinusOne(env, "pipe", TEMP_FAILURE_RETRY(pipe(&fds[0]))); jobjectArray result = env->NewObjectArray(2, JniConstants::fileDescriptorClass, NULL); if (result == NULL) { return NULL; } for (int i = 0; i < 2; ++i) { ScopedLocalRef<jobject> fd(env, jniCreateFileDescriptor(env, fds[i])); if (fd.get() == NULL) { return NULL; } env->SetObjectArrayElement(result, i, fd.get()); if (env->ExceptionCheck()) { return NULL; } } return result; } static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint timeoutMs) { static jfieldID fdFid = env->GetFieldID(JniConstants::structPollfdClass, "fd", "Ljava/io/FileDescriptor;"); static jfieldID eventsFid = env->GetFieldID(JniConstants::structPollfdClass, "events", "S"); static jfieldID reventsFid = env->GetFieldID(JniConstants::structPollfdClass, "revents", "S"); // Turn the Java android.system.StructPollfd[] into a C++ struct pollfd[]. size_t arrayLength = env->GetArrayLength(javaStructs); UniquePtr<struct pollfd[]> fds(new struct pollfd[arrayLength]); memset(fds.get(), 0, sizeof(struct pollfd) * arrayLength); size_t count = 0; // Some trailing array elements may be irrelevant. (See below.) for (size_t i = 0; i < arrayLength; ++i) { ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i)); if (javaStruct.get() == NULL) { break; // We allow trailing nulls in the array for caller convenience. } ScopedLocalRef<jobject> javaFd(env, env->GetObjectField(javaStruct.get(), fdFid)); if (javaFd.get() == NULL) { break; // We also allow callers to just clear the fd field (this is what Selector does). } fds[count].fd = jniGetFDFromFileDescriptor(env, javaFd.get()); fds[count].events = env->GetShortField(javaStruct.get(), eventsFid); ++count; } std::vector<AsynchronousCloseMonitor*> monitors; for (size_t i = 0; i < count; ++i) { monitors.push_back(new AsynchronousCloseMonitor(fds[i].fd)); } int rc = poll(fds.get(), count, timeoutMs); for (size_t i = 0; i < monitors.size(); ++i) { delete monitors[i]; } if (rc == -1) { throwErrnoException(env, "poll"); return -1; } // Update the revents fields in the Java android.system.StructPollfd[]. for (size_t i = 0; i < count; ++i) { ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i)); if (javaStruct.get() == NULL) { return -1; } env->SetShortField(javaStruct.get(), reventsFid, fds[i].revents); } return rc; } static void Posix_posix_fallocate(JNIEnv* env, jobject, jobject javaFd __unused, jlong offset __unused, jlong length __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "fallocate doesn't exist on a Mac"); #else int fd = jniGetFDFromFileDescriptor(env, javaFd); errno = TEMP_FAILURE_RETRY(posix_fallocate64(fd, offset, length)); if (errno != 0) { throwErrnoException(env, "posix_fallocate"); } #endif } static jint Posix_prctl(JNIEnv* env, jobject, jint option __unused, jlong arg2 __unused, jlong arg3 __unused, jlong arg4 __unused, jlong arg5 __unused) { #ifdef __APPLE__ jniThrowException(env, "java/lang/UnsupportedOperationException", "prctl doesn't exist on a Mac"); return 0; #else int result = prctl(static_cast<int>(option), static_cast<unsigned long>(arg2), static_cast<unsigned long>(arg3), static_cast<unsigned long>(arg4), static_cast<unsigned long>(arg5)); return throwIfMinusOne(env, "prctl", result); #endif } static jint Posix_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, pread64, javaFd, bytes.get() + byteOffset, byteCount, offset); } static jint Posix_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount, jlong offset) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, pwrite64, javaFd, bytes.get() + byteOffset, byteCount, offset); } static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, read, javaFd, bytes.get() + byteOffset, byteCount); } static jstring Posix_readlink(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } std::string result; if (!readlink(path.c_str(), result)) { throwErrnoException(env, "readlink"); return NULL; } return env->NewStringUTF(result.c_str()); } static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) { IoVec<ScopedBytesRW> ioVec(env, env->GetArrayLength(buffers)); if (!ioVec.init(buffers, offsets, byteCounts)) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, readv, javaFd, ioVec.get(), ioVec.size()); } static jint Posix_recvfromBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetSocketAddress) { ScopedBytesRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } sockaddr_storage ss; socklen_t sl = sizeof(ss); memset(&ss, 0, sizeof(ss)); sockaddr* from = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL; socklen_t* fromLength = (javaInetSocketAddress != NULL) ? &sl : 0; jint recvCount = NET_FAILURE_RETRY(env, ssize_t, recvfrom, javaFd, bytes.get() + byteOffset, byteCount, flags, from, fromLength); fillInetSocketAddress(env, recvCount, javaInetSocketAddress, ss); return recvCount; } static void Posix_remove(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return; } throwIfMinusOne(env, "remove", TEMP_FAILURE_RETRY(remove(path.c_str()))); } static void Posix_rename(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "rename", TEMP_FAILURE_RETRY(rename(oldPath.c_str(), newPath.c_str()))); } static jlong Posix_sendfile(JNIEnv* env, jobject, jobject javaOutFd, jobject javaInFd, jobject javaOffset, jlong byteCount) { int outFd = jniGetFDFromFileDescriptor(env, javaOutFd); int inFd = jniGetFDFromFileDescriptor(env, javaInFd); static jfieldID valueFid = env->GetFieldID(JniConstants::mutableLongClass, "value", "J"); off_t offset = 0; off_t* offsetPtr = NULL; if (javaOffset != NULL) { // TODO: fix bionic so we can have a 64-bit off_t! offset = env->GetLongField(javaOffset, valueFid); offsetPtr = &offset; } jlong result = throwIfMinusOne(env, "sendfile", TEMP_FAILURE_RETRY(sendfile(outFd, inFd, offsetPtr, byteCount))); if (javaOffset != NULL) { env->SetLongField(javaOffset, valueFid, offset); } return result; } static jint Posix_sendtoBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetAddress, jint port) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } sockaddr_storage ss; socklen_t sa_len = 0; if (javaInetAddress != NULL && !inetAddressToSockaddr(env, javaInetAddress, port, ss, sa_len)) { return -1; } const sockaddr* to = (javaInetAddress != NULL) ? reinterpret_cast<const sockaddr*>(&ss) : NULL; return NET_FAILURE_RETRY(env, ssize_t, sendto, javaFd, bytes.get() + byteOffset, byteCount, flags, to, sa_len); } static void Posix_setegid(JNIEnv* env, jobject, jint egid) { throwIfMinusOne(env, "setegid", TEMP_FAILURE_RETRY(setegid(egid))); } static void Posix_setenv(JNIEnv* env, jobject, jstring javaName, jstring javaValue, jboolean overwrite) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return; } ScopedUtfChars value(env, javaValue); if (value.c_str() == NULL) { return; } throwIfMinusOne(env, "setenv", setenv(name.c_str(), value.c_str(), overwrite)); } static void Posix_seteuid(JNIEnv* env, jobject, jint euid) { throwIfMinusOne(env, "seteuid", TEMP_FAILURE_RETRY(seteuid(euid))); } static void Posix_setgid(JNIEnv* env, jobject, jint gid) { throwIfMinusOne(env, "setgid", TEMP_FAILURE_RETRY(setgid(gid))); } static jint Posix_setsid(JNIEnv* env, jobject) { return throwIfMinusOne(env, "setsid", TEMP_FAILURE_RETRY(setsid())); } static void Posix_setsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { int fd = jniGetFDFromFileDescriptor(env, javaFd); u_char byte = value; throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &byte, sizeof(byte)))); } static void Posix_setsockoptIfreq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jstring javaInterfaceName) { struct ifreq req; if (!fillIfreq(env, javaInterfaceName, req)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)))); } static void Posix_setsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED < 1070 // Mac OS didn't support modern multicast APIs until 10.7. static void Posix_setsockoptIpMreqn(JNIEnv*, jobject, jobject, jint, jint, jint) { abort(); } static void Posix_setsockoptGroupReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); } static void Posix_setsockoptGroupSourceReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); } #else static void Posix_setsockoptIpMreqn(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) { ip_mreqn req; memset(&req, 0, sizeof(req)); req.imr_ifindex = value; int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)))); } static void Posix_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupReq) { struct group_req req; memset(&req, 0, sizeof(req)); static jfieldID grInterfaceFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_interface", "I"); req.gr_interface = env->GetIntField(javaGroupReq, grInterfaceFid); // Get the IPv4 or IPv6 multicast address to join or leave. static jfieldID grGroupFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_group", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupReq, grGroupFid)); socklen_t sa_len; if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gr_group, sa_len)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))); if (rc == -1 && errno == EINVAL) { // Maybe we're a 32-bit binary talking to a 64-bit kernel? // glibc doesn't automatically handle this. // http://sourceware.org/bugzilla/show_bug.cgi?id=12080 struct group_req64 { uint32_t gr_interface; uint32_t my_padding; sockaddr_storage gr_group; }; group_req64 req64; req64.gr_interface = req.gr_interface; memcpy(&req64.gr_group, &req.gr_group, sizeof(req.gr_group)); rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64))); } throwIfMinusOne(env, "setsockopt", rc); } static void Posix_setsockoptGroupSourceReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupSourceReq) { socklen_t sa_len; struct group_source_req req; memset(&req, 0, sizeof(req)); static jfieldID gsrInterfaceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_interface", "I"); req.gsr_interface = env->GetIntField(javaGroupSourceReq, gsrInterfaceFid); // Get the IPv4 or IPv6 multicast address to join or leave. static jfieldID gsrGroupFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_group", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupSourceReq, gsrGroupFid)); if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gsr_group, sa_len)) { return; } // Get the IPv4 or IPv6 multicast address to add to the filter. static jfieldID gsrSourceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_source", "Ljava/net/InetAddress;"); ScopedLocalRef<jobject> javaSource(env, env->GetObjectField(javaGroupSourceReq, gsrSourceFid)); if (!inetAddressToSockaddrVerbatim(env, javaSource.get(), 0, req.gsr_source, sa_len)) { return; } int fd = jniGetFDFromFileDescriptor(env, javaFd); int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))); if (rc == -1 && errno == EINVAL) { // Maybe we're a 32-bit binary talking to a 64-bit kernel? // glibc doesn't automatically handle this. // http://sourceware.org/bugzilla/show_bug.cgi?id=12080 struct group_source_req64 { uint32_t gsr_interface; uint32_t my_padding; sockaddr_storage gsr_group; sockaddr_storage gsr_source; }; group_source_req64 req64; req64.gsr_interface = req.gsr_interface; memcpy(&req64.gsr_group, &req.gsr_group, sizeof(req.gsr_group)); memcpy(&req64.gsr_source, &req.gsr_source, sizeof(req.gsr_source)); rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64))); } throwIfMinusOne(env, "setsockopt", rc); } #endif static void Posix_setsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaLinger) { static jfieldID lOnoffFid = env->GetFieldID(JniConstants::structLingerClass, "l_onoff", "I"); static jfieldID lLingerFid = env->GetFieldID(JniConstants::structLingerClass, "l_linger", "I"); int fd = jniGetFDFromFileDescriptor(env, javaFd); struct linger value; value.l_onoff = env->GetIntField(javaLinger, lOnoffFid); value.l_linger = env->GetIntField(javaLinger, lLingerFid); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } static void Posix_setsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaTimeval) { static jfieldID tvSecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_sec", "J"); static jfieldID tvUsecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_usec", "J"); int fd = jniGetFDFromFileDescriptor(env, javaFd); struct timeval value; value.tv_sec = env->GetLongField(javaTimeval, tvSecFid); value.tv_usec = env->GetLongField(javaTimeval, tvUsecFid); throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value)))); } static void Posix_setuid(JNIEnv* env, jobject, jint uid) { throwIfMinusOne(env, "setuid", TEMP_FAILURE_RETRY(setuid(uid))); } static void Posix_shutdown(JNIEnv* env, jobject, jobject javaFd, jint how) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "shutdown", TEMP_FAILURE_RETRY(shutdown(fd, how))); } static jobject Posix_socket(JNIEnv* env, jobject, jint domain, jint type, jint protocol) { int fd = throwIfMinusOne(env, "socket", TEMP_FAILURE_RETRY(socket(domain, type, protocol))); return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL; } static void Posix_socketpair(JNIEnv* env, jobject, jint domain, jint type, jint protocol, jobject javaFd1, jobject javaFd2) { int fds[2]; int rc = throwIfMinusOne(env, "socketpair", TEMP_FAILURE_RETRY(socketpair(domain, type, protocol, fds))); if (rc != -1) { jniSetFileDescriptorOfFD(env, javaFd1, fds[0]); jniSetFileDescriptorOfFD(env, javaFd2, fds[1]); } } static jobject Posix_stat(JNIEnv* env, jobject, jstring javaPath) { return doStat(env, javaPath, false); } static jobject Posix_statvfs(JNIEnv* env, jobject, jstring javaPath) { ScopedUtfChars path(env, javaPath); if (path.c_str() == NULL) { return NULL; } struct statvfs sb; int rc = TEMP_FAILURE_RETRY(statvfs(path.c_str(), &sb)); if (rc == -1) { throwErrnoException(env, "statvfs"); return NULL; } return makeStructStatVfs(env, sb); } static jstring Posix_strerror(JNIEnv* env, jobject, jint errnum) { char buffer[BUFSIZ]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return env->NewStringUTF(message); } static jstring Posix_strsignal(JNIEnv* env, jobject, jint signal) { return env->NewStringUTF(strsignal(signal)); } static void Posix_symlink(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) { ScopedUtfChars oldPath(env, javaOldPath); if (oldPath.c_str() == NULL) { return; } ScopedUtfChars newPath(env, javaNewPath); if (newPath.c_str() == NULL) { return; } throwIfMinusOne(env, "symlink", TEMP_FAILURE_RETRY(symlink(oldPath.c_str(), newPath.c_str()))); } static jlong Posix_sysconf(JNIEnv* env, jobject, jint name) { // Since -1 is a valid result from sysconf(3), detecting failure is a little more awkward. errno = 0; long result = sysconf(name); if (result == -1L && errno == EINVAL) { throwErrnoException(env, "sysconf"); } return result; } static void Posix_tcdrain(JNIEnv* env, jobject, jobject javaFd) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "tcdrain", TEMP_FAILURE_RETRY(tcdrain(fd))); } static void Posix_tcsendbreak(JNIEnv* env, jobject, jobject javaFd, jint duration) { int fd = jniGetFDFromFileDescriptor(env, javaFd); throwIfMinusOne(env, "tcsendbreak", TEMP_FAILURE_RETRY(tcsendbreak(fd, duration))); } static jint Posix_umaskImpl(JNIEnv*, jobject, jint mask) { return umask(mask); } static jobject Posix_uname(JNIEnv* env, jobject) { struct utsname buf; if (TEMP_FAILURE_RETRY(uname(&buf)) == -1) { return NULL; // Can't happen. } return makeStructUtsname(env, buf); } static void Posix_unsetenv(JNIEnv* env, jobject, jstring javaName) { ScopedUtfChars name(env, javaName); if (name.c_str() == NULL) { return; } throwIfMinusOne(env, "unsetenv", unsetenv(name.c_str())); } static jint Posix_waitpid(JNIEnv* env, jobject, jint pid, jobject javaStatus, jint options) { int status; int rc = throwIfMinusOne(env, "waitpid", TEMP_FAILURE_RETRY(waitpid(pid, &status, options))); if (rc != -1) { static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I"); env->SetIntField(javaStatus, valueFid, status); } return rc; } static jint Posix_writeBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount) { ScopedBytesRO bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, write, javaFd, bytes.get() + byteOffset, byteCount); } static jint Posix_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) { IoVec<ScopedBytesRO> ioVec(env, env->GetArrayLength(buffers)); if (!ioVec.init(buffers, offsets, byteCounts)) { return -1; } return IO_FAILURE_RETRY(env, ssize_t, writev, javaFd, ioVec.get(), ioVec.size()); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Posix, accept, "(Ljava/io/FileDescriptor;Ljava/net/InetSocketAddress;)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, access, "(Ljava/lang/String;I)Z"), NATIVE_METHOD(Posix, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"), NATIVE_METHOD(Posix, chmod, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, chown, "(Ljava/lang/String;II)V"), NATIVE_METHOD(Posix, close, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, connect, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"), NATIVE_METHOD(Posix, dup, "(Ljava/io/FileDescriptor;)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, dup2, "(Ljava/io/FileDescriptor;I)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, environ, "()[Ljava/lang/String;"), NATIVE_METHOD(Posix, execv, "(Ljava/lang/String;[Ljava/lang/String;)V"), NATIVE_METHOD(Posix, execve, "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V"), NATIVE_METHOD(Posix, fchmod, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, fchown, "(Ljava/io/FileDescriptor;II)V"), NATIVE_METHOD(Posix, fcntlVoid, "(Ljava/io/FileDescriptor;I)I"), NATIVE_METHOD(Posix, fcntlLong, "(Ljava/io/FileDescriptor;IJ)I"), NATIVE_METHOD(Posix, fcntlFlock, "(Ljava/io/FileDescriptor;ILandroid/system/StructFlock;)I"), NATIVE_METHOD(Posix, fdatasync, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, fstat, "(Ljava/io/FileDescriptor;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, fstatvfs, "(Ljava/io/FileDescriptor;)Landroid/system/StructStatVfs;"), NATIVE_METHOD(Posix, fsync, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, ftruncate, "(Ljava/io/FileDescriptor;J)V"), NATIVE_METHOD(Posix, gai_strerror, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, getegid, "()I"), NATIVE_METHOD(Posix, geteuid, "()I"), NATIVE_METHOD(Posix, getgid, "()I"), NATIVE_METHOD(Posix, getenv, "(Ljava/lang/String;)Ljava/lang/String;"), NATIVE_METHOD(Posix, getnameinfo, "(Ljava/net/InetAddress;I)Ljava/lang/String;"), NATIVE_METHOD(Posix, getpeername, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"), NATIVE_METHOD(Posix, getpid, "()I"), NATIVE_METHOD(Posix, getppid, "()I"), NATIVE_METHOD(Posix, getpwnam, "(Ljava/lang/String;)Landroid/system/StructPasswd;"), NATIVE_METHOD(Posix, getpwuid, "(I)Landroid/system/StructPasswd;"), NATIVE_METHOD(Posix, getsockname, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"), NATIVE_METHOD(Posix, getsockoptByte, "(Ljava/io/FileDescriptor;II)I"), NATIVE_METHOD(Posix, getsockoptInAddr, "(Ljava/io/FileDescriptor;II)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, getsockoptInt, "(Ljava/io/FileDescriptor;II)I"), NATIVE_METHOD(Posix, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Landroid/system/StructLinger;"), NATIVE_METHOD(Posix, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Landroid/system/StructTimeval;"), NATIVE_METHOD(Posix, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Landroid/system/StructUcred;"), NATIVE_METHOD(Posix, gettid, "()I"), NATIVE_METHOD(Posix, getuid, "()I"), NATIVE_METHOD(Posix, if_indextoname, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, inet_pton, "(ILjava/lang/String;)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, ioctlInetAddress, "(Ljava/io/FileDescriptor;ILjava/lang/String;)Ljava/net/InetAddress;"), NATIVE_METHOD(Posix, ioctlInt, "(Ljava/io/FileDescriptor;ILandroid/util/MutableInt;)I"), NATIVE_METHOD(Posix, isatty, "(Ljava/io/FileDescriptor;)Z"), NATIVE_METHOD(Posix, kill, "(II)V"), NATIVE_METHOD(Posix, lchown, "(Ljava/lang/String;II)V"), NATIVE_METHOD(Posix, link, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, listen, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, lseek, "(Ljava/io/FileDescriptor;JI)J"), NATIVE_METHOD(Posix, lstat, "(Ljava/lang/String;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, mincore, "(JJ[B)V"), NATIVE_METHOD(Posix, mkdir, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, mkfifo, "(Ljava/lang/String;I)V"), NATIVE_METHOD(Posix, mlock, "(JJ)V"), NATIVE_METHOD(Posix, mmap, "(JJIILjava/io/FileDescriptor;J)J"), NATIVE_METHOD(Posix, msync, "(JJI)V"), NATIVE_METHOD(Posix, munlock, "(JJ)V"), NATIVE_METHOD(Posix, munmap, "(JJ)V"), NATIVE_METHOD(Posix, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, pipe, "()[Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, poll, "([Landroid/system/StructPollfd;I)I"), NATIVE_METHOD(Posix, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"), NATIVE_METHOD(Posix, prctl, "(IJJJJ)I"), NATIVE_METHOD(Posix, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"), NATIVE_METHOD(Posix, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"), NATIVE_METHOD(Posix, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"), NATIVE_METHOD(Posix, readlink, "(Ljava/lang/String;)Ljava/lang/String;"), NATIVE_METHOD(Posix, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"), NATIVE_METHOD(Posix, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"), NATIVE_METHOD(Posix, remove, "(Ljava/lang/String;)V"), NATIVE_METHOD(Posix, rename, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Landroid/util/MutableLong;J)J"), NATIVE_METHOD(Posix, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetAddress;I)I"), NATIVE_METHOD(Posix, setegid, "(I)V"), NATIVE_METHOD(Posix, setenv, "(Ljava/lang/String;Ljava/lang/String;Z)V"), NATIVE_METHOD(Posix, seteuid, "(I)V"), NATIVE_METHOD(Posix, setgid, "(I)V"), NATIVE_METHOD(Posix, setsid, "()I"), NATIVE_METHOD(Posix, setsockoptByte, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptIfreq, "(Ljava/io/FileDescriptor;IILjava/lang/String;)V"), NATIVE_METHOD(Posix, setsockoptInt, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptIpMreqn, "(Ljava/io/FileDescriptor;III)V"), NATIVE_METHOD(Posix, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupReq;)V"), NATIVE_METHOD(Posix, setsockoptGroupSourceReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupSourceReq;)V"), NATIVE_METHOD(Posix, setsockoptLinger, "(Ljava/io/FileDescriptor;IILandroid/system/StructLinger;)V"), NATIVE_METHOD(Posix, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILandroid/system/StructTimeval;)V"), NATIVE_METHOD(Posix, setuid, "(I)V"), NATIVE_METHOD(Posix, shutdown, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, socket, "(III)Ljava/io/FileDescriptor;"), NATIVE_METHOD(Posix, socketpair, "(IIILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, stat, "(Ljava/lang/String;)Landroid/system/StructStat;"), NATIVE_METHOD(Posix, statvfs, "(Ljava/lang/String;)Landroid/system/StructStatVfs;"), NATIVE_METHOD(Posix, strerror, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, strsignal, "(I)Ljava/lang/String;"), NATIVE_METHOD(Posix, symlink, "(Ljava/lang/String;Ljava/lang/String;)V"), NATIVE_METHOD(Posix, sysconf, "(I)J"), NATIVE_METHOD(Posix, tcdrain, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(Posix, tcsendbreak, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(Posix, umaskImpl, "(I)I"), NATIVE_METHOD(Posix, uname, "()Landroid/system/StructUtsname;"), NATIVE_METHOD(Posix, unsetenv, "(Ljava/lang/String;)V"), NATIVE_METHOD(Posix, waitpid, "(ILandroid/util/MutableInt;I)I"), NATIVE_METHOD(Posix, writeBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"), NATIVE_METHOD(Posix, writev, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"), }; void register_libcore_io_Posix(JNIEnv* env) { jniRegisterNativeMethods(env, "libcore/io/Posix", gMethods, NELEM(gMethods)); }
s20121035/rk3288_android5.1_repo
libcore/luni/src/main/native/libcore_io_Posix.cpp
C++
gpl-3.0
68,241
// Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package MJDecompiler; import java.io.IOException; // Referenced classes of package MJDecompiler: // bm, bf, bh, bj, // bc final class as extends CpField { as(ClazzInputStream bc, ClassFile bj1) throws IOException { super(bc, bj1); } final void writeBytecode(ByteCodeOutput bf1) throws IOException { bf1.writeByte(9); bf1.writeUshort(super.b); bf1.writeUshort(super.o); } final String type() { return super.a.getConstant(super.o).type(); } final String a(ClassFile bj1) { return "FieldRef(" + super.b + ":" + bj1.getConstant(super.b).a(bj1) + ", " + super.o + ":" + bj1.getConstant(super.o).a(bj1) + ")"; } }
ghostgzt/STX
src/MJDecompiler/as.java
Java
gpl-3.0
839
package com.zalthrion.zylroth.handler; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class KeyHandler { @SideOnly(Side.CLIENT) public static KeyBinding openSummonGui; public static void init() { openSummonGui = new KeyBinding("key.zylroth:summongui", Keyboard.KEY_Z, "key.categories.zylroth"); ClientRegistry.registerKeyBinding(openSummonGui); } }
Zalthrion/Zyl-Roth
src/main/java/com/zalthrion/zylroth/handler/KeyHandler.java
Java
gpl-3.0
533
/* * Copyright (c) 2014 Ian Bondoc * * This file is part of Jen8583 * * Jen8583 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. * * Jen8583 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/>. * */ package org.chiknrice.iso.codec; import org.chiknrice.iso.config.ComponentDef.Encoding; import java.nio.ByteBuffer; /** * The main contract for a codec used across encoding and decoding of message components. Each field/component of the * ISO message would have its own instance of codec which contains the definition of how the value should be * encoded/decoded. The codec should be designed to be thread safe as the instance would live throughout the life of the * IsoMessageDef. Any issues encountered during encoding/decoding should be throwing a CodecException. Any issues * encountered during codec configuration/construction the constructor should throw a ConfigException. A ConfigException * should generally happen during startup while CodecException happens when the Codec is being used. * * @author <a href="mailto:chiknrice@gmail.com">Ian Bondoc</a> */ public interface Codec<T> { /** * The implementation should define how the value T should be decoded from the ByteBuffer provided. The * implementation could either decode the value from a certain number of bytes or consume the whole ByteBuffer. * * @param buf * @return the decoded value */ T decode(ByteBuffer buf); /** * The implementation should define how the value T should be encoded to the ByteBuffer provided. The ByteBuffer * assumes the value would be encoded from the current position. * * @param buf * @param value the value to be encoded */ void encode(ByteBuffer buf, T value); /** * Defines how the value should be encoded/decoded. * * @return the encoding defined for the value. */ Encoding getEncoding(); }
chiknrice/jen8583
src/main/java/org/chiknrice/iso/codec/Codec.java
Java
gpl-3.0
2,477
#!/usr/bin/env python # # Copyright 2011 Facebook # # 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. """Miscellaneous network utility code.""" from __future__ import absolute_import, division, print_function, with_statement import errno import os import re import socket import ssl import stat from lib.tornado.concurrent import dummy_executor, run_on_executor from lib.tornado.ioloop import IOLoop from lib.tornado.platform.auto import set_close_exec from lib.tornado.util import Configurable def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None): """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. """ sockets = [] if address == "": address = None if not socket.has_ipv6 and family == socket.AF_UNSPEC: # Python can be compiled with --disable-ipv6, which causes # operations on AF_INET6 sockets to fail, but does not # automatically exclude those results from getaddrinfo # results. # http://bugs.python.org/issue16208 family = socket.AF_INET if flags is None: flags = socket.AI_PASSIVE for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags)): af, socktype, proto, canonname, sockaddr = res sock = socket.socket(af, socktype, proto) set_close_exec(sock.fileno()) if os.name != 'nt': sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if af == socket.AF_INET6: # On linux, ipv6 sockets accept ipv4 too by default, # but this makes it impossible to bind to both # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, # separate sockets *must* be used to listen for both ipv4 # and ipv6. For consistency, always disable ipv4 on our # ipv6 sockets and use a separate ipv4 socket when needed. # # Python 2.x on windows doesn't have IPPROTO_IPV6. if hasattr(socket, "IPPROTO_IPV6"): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) sock.setblocking(0) sock.bind(sockaddr) sock.listen(backlog) sockets.append(sock) return sockets if hasattr(socket, 'AF_UNIX'): def bind_unix_socket(file, mode=0o600, backlog=128): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`) """ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) set_close_exec(sock.fileno()) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file) except OSError as err: if err.errno != errno.ENOENT: raise else: if stat.S_ISSOCK(st.st_mode): os.remove(file) else: raise ValueError("File %s exists and is not a socket", file) sock.bind(file) os.chmod(file, mode) sock.listen(backlog) return sock def add_accept_handler(sock, callback, io_loop=None): """Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. """ if io_loop is None: io_loop = IOLoop.current() def accept_handler(fd, events): while True: try: connection, address = sock.accept() except socket.error as e: if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return raise callback(connection, address) io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ) def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True class Resolver(Configurable): """Configurable asynchronous DNS resolver interface. By default, a blocking implementation is used (which simply calls `socket.getaddrinfo`). An alternative implementation can be chosen with the `Resolver.configure <.Configurable.configure>` class method:: Resolver.configure('tornado.netutil.ThreadedResolver') The implementations of this interface included with Tornado are * `tornado.netutil.BlockingResolver` * `tornado.netutil.ThreadedResolver` * `tornado.netutil.OverrideResolver` * `tornado.platform.twisted.TwistedResolver` * `tornado.platform.caresresolver.CaresResolver` """ @classmethod def configurable_base(cls): return Resolver @classmethod def configurable_default(cls): return BlockingResolver def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None): """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. """ raise NotImplementedError() class ExecutorResolver(Resolver): def initialize(self, io_loop=None, executor=None): self.io_loop = io_loop or IOLoop.current() self.executor = executor or dummy_executor @run_on_executor def resolve(self, host, port, family=socket.AF_UNSPEC): addrinfo = socket.getaddrinfo(host, port, family) results = [] for family, socktype, proto, canonname, address in addrinfo: results.append((family, address)) return results class BlockingResolver(ExecutorResolver): """Default `Resolver` implementation, using `socket.getaddrinfo`. The `.IOLoop` will be blocked during the resolution, although the callback will not be run until the next `.IOLoop` iteration. """ def initialize(self, io_loop=None): super(BlockingResolver, self).initialize(io_loop=io_loop) class ThreadedResolver(ExecutorResolver): """Multithreaded non-blocking `Resolver` implementation. Requires the `concurrent.futures` package to be installed (available in the standard library since Python 3.2, installable with ``pip install futures`` in older versions). The thread pool size can be configured with:: Resolver.configure('tornado.netutil.ThreadedResolver', num_threads=10) """ def initialize(self, io_loop=None, num_threads=10): from concurrent.futures import ThreadPoolExecutor super(ThreadedResolver, self).initialize( io_loop=io_loop, executor=ThreadPoolExecutor(num_threads)) class OverrideResolver(Resolver): """Wraps a resolver with a mapping of overrides. This can be used to make local DNS changes (e.g. for testing) without modifying system-wide settings. The mapping can contain either host strings or host-port pairs. """ def initialize(self, resolver, mapping): self.resolver = resolver self.mapping = mapping def resolve(self, host, port, *args, **kwargs): if (host, port) in self.mapping: host, port = self.mapping[(host, port)] elif host in self.mapping: host = self.mapping[host] return self.resolver.resolve(host, port, *args, **kwargs) # These are the keyword arguments to ssl.wrap_socket that must be translated # to their SSLContext equivalents (the other arguments are still passed # to SSLContext.wrap_socket). _SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile', 'cert_reqs', 'ca_certs', 'ciphers']) def ssl_options_to_context(ssl_options): """Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN. """ if isinstance(ssl_options, dict): assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options if (not hasattr(ssl, 'SSLContext') or isinstance(ssl_options, ssl.SSLContext)): return ssl_options context = ssl.SSLContext( ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23)) if 'certfile' in ssl_options: context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) if 'cert_reqs' in ssl_options: context.verify_mode = ssl_options['cert_reqs'] if 'ca_certs' in ssl_options: context.load_verify_locations(ssl_options['ca_certs']) if 'ciphers' in ssl_options: context.set_ciphers(ssl_options['ciphers']) return context def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs): """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either a dictionary (as accepted by `ssl_options_to_context`) or an `ssl.SSLContext` object. Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext): if server_hostname is not None and getattr(ssl, 'HAS_SNI'): # Python doesn't have server-side SNI support so we can't # really unittest this, but it can be manually tested with # python3.2 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs) else: return ssl.wrap_socket(socket, **dict(context, **kwargs)) if hasattr(ssl, 'match_hostname'): # python 3.2+ ssl_match_hostname = ssl.match_hostname SSLCertificateError = ssl.CertificateError else: # match_hostname was added to the standard library ssl module in python 3.2. # The following code was backported for older releases and copied from # https://bitbucket.org/brandon/backports.ssl_match_hostname class SSLCertificateError(ValueError): pass def _dnsname_to_pat(dn): pats = [] for frag in dn.split(r'.'): if frag == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') else: # Otherwise, '*' matches any dotless fragment. frag = re.escape(frag) pats.append(frag.replace(r'\*', '[^.]*')) return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) def ssl_match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules are mostly followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value) if not san: # The subject is only checked when subjectAltName is empty for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise SSLCertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise SSLCertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise SSLCertificateError("no appropriate commonName or " "subjectAltName fields were found")
mountainpenguin/BySH
server/lib/tornado/netutil.py
Python
gpl-3.0
15,081
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MiniQuick.Events { public class BaseEvent : IEvent { private int _MaxRetryCount = 3; private TimeSpan _timeinterval = TimeSpan.FromMilliseconds(1000); public string CommandId { get; set; } public int RetryCount { get { return this._MaxRetryCount; } } public TimeSpan Timeinterval { get { return this._timeinterval; } } } }
fzf003/MiniQuick
MiniQuick/Events/BaseEvent.cs
C#
gpl-3.0
606
/************************************************************************ Copyright 2008 Mark Pictor This file is part of RS274NGC. RS274NGC 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. RS274NGC 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 RS274NGC. If not, see <http://www.gnu.org/licenses/>. This software is based on software that was produced by the National Institute of Standards and Technology (NIST). ************************************************************************/ #include "stdafx.h" extern CANON_TOOL_TABLE _tools[]; /* in canon.cc */ extern int _tool_max; /* in canon.cc */ extern char _parameter_file_name[100]; /* in canon.cc */ FILE * _outfile; /* where to print, set in main */ /* This file contains the source code for an emulation of using the six-axis rs274 interpreter from the EMC system. */ /*********************************************************************/ /* report_error Returned Value: none Side effects: an error message is printed on stderr Called by: interpret_from_file interpret_from_keyboard main This 1. calls rs274ngc_error_text to get the text of the error message whose code is error_code and prints the message, 2. calls rs274ngc_line_text to get the text of the line on which the error occurred and prints the text, and 3. if print_stack is on, repeatedly calls rs274ngc_stack_name to get the names of the functions on the function call stack and prints the names. The first function named is the one that sent the error message. */ void report_error( /* ARGUMENTS */ int error_code, /* the code number of the error message */ int print_stack) /* print stack if ON, otherwise not */ { char buffer[RS274NGC_TEXT_SIZE]; int k; rs274ngc_error_text(error_code, buffer, sizeof(buffer), 5); /* for coverage of code */ rs274ngc_error_text(error_code, buffer, sizeof(buffer), RS274NGC_TEXT_SIZE); fprintf(stderr, "%s\n", ((buffer[0] IS 0) ? "Unknown error, bad error code" : buffer)); rs274ngc_line_text(buffer, RS274NGC_TEXT_SIZE); fprintf(stderr, "%s\n", buffer); if (print_stack IS ON) { for (k SET_TO 0; ; k++) { rs274ngc_stack_name(k, buffer, RS274NGC_TEXT_SIZE); if (buffer[0] ISNT 0) fprintf(stderr, "%s\n", buffer); else break; } } } /***********************************************************************/ /* interpret_from_keyboard Returned Value: int (0) Side effects: Lines of NC code entered by the user are interpreted. Called by: interpret_from_file main This prompts the user to enter a line of rs274 code. When the user hits <enter> at the end of the line, the line is executed. Then the user is prompted to enter another line. Any canonical commands resulting from executing the line are printed on the monitor (stdout). If there is an error in reading or executing the line, an error message is printed on the monitor (stderr). To exit, the user must enter "quit" (followed by a carriage return). */ int interpret_from_keyboard( /* ARGUMENTS */ int block_delete, /* switch which is ON or OFF */ int print_stack) /* option which is ON or OFF */ { char line[RS274NGC_TEXT_SIZE]; int status; for(; ;) { printf("READ => "); fgets(line, sizeof(line), stdin); if (strcmp (line, "quit") IS 0) return 0; status SET_TO rs274ngc_read(line); if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON)); else if (status IS RS274NGC_ENDFILE); else if ((status ISNT RS274NGC_EXECUTE_FINISH) AND (status ISNT RS274NGC_OK)) report_error(status, print_stack); else { status SET_TO rs274ngc_execute(); if ((status IS RS274NGC_EXIT) OR (status IS RS274NGC_EXECUTE_FINISH)); else if (status ISNT RS274NGC_OK) report_error(status, print_stack); } } } /*********************************************************************/ /* interpret_from_file Returned Value: int (0 or 1) If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. rs274ngc_read returns something other than RS274NGC_OK or RS274NGC_EXECUTE_FINISH, no_stop is off, and the user elects not to continue. 2. rs274ngc_execute returns something other than RS274NGC_OK, EXIT, or RS274NGC_EXECUTE_FINISH, no_stop is off, and the user elects not to continue. Side Effects: An open NC-program file is interpreted. Called By: main This emulates the way the EMC system uses the interpreter. If the do_next argument is 1, this goes into MDI mode if an error is found. In that mode, the user may (1) enter code or (2) enter "quit" to get out of MDI. Once out of MDI, this asks the user whether to continue interpreting the file. If the do_next argument is 0, an error does not stop interpretation. If the do_next argument is 2, an error stops interpretation. */ int interpret_from_file( /* ARGUMENTS */ int do_next, /* what to do if error */ int block_delete, /* switch which is ON or OFF */ int print_stack) /* option which is ON or OFF */ { int status; char line[RS274NGC_TEXT_SIZE]; for(; ;) { status SET_TO rs274ngc_read(NULL); if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON)) continue; else if (status IS RS274NGC_ENDFILE) break; if ((status ISNT RS274NGC_OK) AND // should not be EXIT (status ISNT RS274NGC_EXECUTE_FINISH)) { report_error(status, print_stack); if ((status IS NCE_FILE_ENDED_WITH_NO_PERCENT_SIGN) OR (do_next IS 2)) /* 2 means stop */ { status SET_TO 1; break; } else if (do_next IS 1) /* 1 means MDI */ { fprintf(stderr, "starting MDI\n"); interpret_from_keyboard(block_delete, print_stack); fprintf(stderr, "continue program? y/n =>"); fgets(line, sizeof(line), stdin); if (line[0] ISNT 'y') { status SET_TO 1; break; } else continue; } else /* if do_next IS 0 -- 0 means continue */ continue; } status SET_TO rs274ngc_execute(); if ((status ISNT RS274NGC_OK) AND (status ISNT RS274NGC_EXIT) AND (status ISNT RS274NGC_EXECUTE_FINISH)) { report_error(status, print_stack); status SET_TO 1; if (do_next IS 1) /* 1 means MDI */ { fprintf(stderr, "starting MDI\n"); interpret_from_keyboard(block_delete, print_stack); fprintf(stderr, "continue program? y/n =>"); fgets(line,sizeof(line), stdin); if (line[0] ISNT 'y') break; } else if (do_next IS 2) /* 2 means stop */ break; } else if (status IS RS274NGC_EXIT) break; } return ((status IS 1) ? 1 : 0); } /************************************************************************/ /* read_tool_file Returned Value: int If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. The file named by the user cannot be opened. 2. No blank line is found. 3. A line of data cannot be read. 4. A tool slot number is less than 1 or >= _tool_max Side Effects: Values in the tool table of the machine setup are changed, as specified in the file. Called By: main Tool File Format ----------------- Everything above the first blank line is read and ignored, so any sort of header material may be used. Everything after the first blank line should be data. Each line of data should have four or more items separated by white space. The four required items are slot, tool id, tool length offset, and tool diameter. Other items might be the holder id and tool description, but these are optional and will not be read. Here is a sample line: 20 1419 4.299 1.0 1 inch carbide end mill The tool_table is indexed by slot number. */ int read_tool_file( /* ARGUMENTS */ char * file_name) /* name of tool file */ { FILE * tool_file_port; char buffer[1000]; int slot; int tool_id; double offset; double diameter; if (file_name[0] IS 0) /* ask for name if given name is empty string */ { fprintf(stderr, "name of tool file => "); fgets(buffer, sizeof(buffer), stdin); fopen_s(&tool_file_port,buffer, "r"); } else fopen_s(&tool_file_port,file_name, "r"); if (tool_file_port IS NULL) { fprintf(stderr, "Cannot open %s\n", ((file_name[0] IS 0) ? buffer : file_name)); return 1; } for(;;) /* read and discard header, checking for blank line */ { if (fgets(buffer, 1000, tool_file_port) IS NULL) { fprintf(stderr, "Bad tool file format\n"); return 1; } else if (buffer[0] IS '\n') break; } for (slot SET_TO 0; slot <= _tool_max; slot++)/* initialize */ { _tools[slot].id SET_TO -1; _tools[slot].length SET_TO 0; _tools[slot].diameter SET_TO 0; } for (; (fgets(buffer, 1000, tool_file_port) ISNT NULL); ) { if (sscanf_s(buffer, "%d %d %lf %lf", &slot, &tool_id, &offset, &diameter) < 4) { fprintf(stderr, "Bad input line \"%s\" in tool file\n", buffer); return 1; } if ((slot < 0) OR (slot > _tool_max)) /* zero and max both OK */ { fprintf(stderr, "Out of range tool slot number %d\n", slot); return 1; } _tools[slot].id SET_TO tool_id; _tools[slot].length SET_TO offset; _tools[slot].diameter SET_TO diameter; } fclose(tool_file_port); return 0; } /************************************************************************/ /* designate_parameter_file Returned Value: int If any of the following errors occur, this returns 1. Otherwise, it returns 0. 1. The file named by the user cannot be opened. Side Effects: The name of a parameter file given by the user is put in the file_name string. Called By: main */ int designate_parameter_file(char * file_name, size_t length) { FILE * test_port; unsigned int ilength; ilength = (int)length; fprintf(stderr, "name of parameter file => "); fgets(file_name, ilength, stdin); fopen_s(&test_port,file_name, "r"); if (test_port IS NULL) { fprintf(stderr, "Cannot open %s\n", file_name); return 1; } fclose(test_port); return 0; } /************************************************************************/ /* adjust_error_handling Returned Value: int (0) Side Effects: The values of print_stack and do_next are set. Called By: main This function allows the user to set one or two aspects of error handling. By default the driver does not print the function stack in case of error. This function always allows the user to turn stack printing on if it is off or to turn stack printing off if it is on. When interpreting from the keyboard, the driver always goes ahead if there is an error. When interpreting from a file, the default behavior is to stop in case of an error. If the user is interpreting from a file (indicated by args being 2 or 3), this lets the user change what it does on an error. If the user has not asked for output to a file (indicated by args being 2), the user can choose any of three behaviors in case of an error (1) continue, (2) stop, (3) go into MDI mode. This function allows the user to cycle among the three. If the user has asked for output to a file (indicated by args being 3), the user can choose any of two behaviors in case of an error (1) continue, (2) stop. This function allows the user to toggle between the two. */ int adjust_error_handling( int args, int * print_stack, int * do_next) { char buffer[80]; int choice; for(;;) { fprintf(stderr, "enter a number:\n"); fprintf(stderr, "1 = done with error handling\n"); fprintf(stderr, "2 = %sprint stack on error\n", ((*print_stack IS ON) ? "do not " : "")); if (args IS 3) { if (*do_next IS 0) /* 0 means continue */ fprintf(stderr, "3 = stop on error (do not continue)\n"); else /* if do_next IS 2 -- 2 means stopping on error */ fprintf(stderr, "3 = continue on error (do not stop)\n"); } else if (args IS 2) { if (*do_next IS 0) /* 0 means continue */ fprintf(stderr, "3 = mdi on error (do not continue or stop)\n"); else if (*do_next IS 1) /* 1 means MDI */ fprintf(stderr, "3 = stop on error (do not mdi or continue)\n"); else /* if do_next IS 2 -- 2 means stopping on error */ fprintf(stderr, "3 = continue on error (do not stop or mdi)\n"); } fprintf(stderr, "enter choice => "); fgets(buffer, sizeof(buffer), stdin); if (sscanf_s(buffer, "%d", &choice) ISNT 1) continue; if (choice IS 1) break; else if (choice IS 2) *print_stack SET_TO ((*print_stack IS OFF) ? ON : OFF); else if ((choice IS 3) AND (args IS 3)) *do_next SET_TO ((*do_next IS 0) ? 2 : 0); else if ((choice IS 3) AND (args IS 2)) *do_next SET_TO ((*do_next IS 2) ? 0 : (*do_next + 1)); } return 0; } /************************************************************************/ /* main The executable exits with either 0 (under all conditions not listed below) or 1 (under the following conditions): 1. A fatal error occurs while interpreting from a file. 2. Read_tool_file fails. 3. An error occurs in rs274ngc_init. *********************************************************************** Here are three ways in which the rs274abc executable may be called. Any other sort of call to the executable will cause an error message to be printed and the interpreter will not run. Other executables may be called similarly. 1. If the rs274abc stand-alone executable is called with no arguments, input is taken from the keyboard, and an error in the input does not cause the rs274abc executable to exit. EXAMPLE: 1A. To interpret from the keyboard, enter: rs274abc *********************************************************************** 2. If the executable is called with one argument, the argument is taken to be the name of an NC file and the file is interpreted as described in the documentation of interpret_from_file. EXAMPLES: 2A. To interpret the file "cds.abc" and read the results on the screen, enter: rs274abc cds.abc 2B. To interpret the file "cds.abc" and print the results in the file "cds.prim", enter: rs274abc cds.abc > cds.prim *********************************************************************** Whichever way the executable is called, this gives the user several choices before interpretation starts 1 = start interpreting 2 = choose parameter file 3 = read tool file ... 4 = turn block delete switch ON 5 = adjust error handling... Interpretation starts when option 1 is chosen. Until that happens, the user is repeatedly given the five choices listed above. Item 4 toggles between "turn block delete switch ON" and "turn block delete switch OFF". See documentation of adjust_error_handling regarding what option 5 does. User instructions are printed to stderr (with fprintf) so that output can be redirected to a file. When output is redirected and user instructions are printed to stdout (with printf), the instructions get redirected and the user does not see them. */ int main (int argc, char ** argv) { int status; int choice; int do_next; /* 0=continue, 1=mdi, 2=stop */ int block_delete; char buffer[80]; int tool_flag; int gees[RS274NGC_ACTIVE_G_CODES]; int ems[RS274NGC_ACTIVE_M_CODES]; double sets[RS274NGC_ACTIVE_SETTINGS]; char default_name[] SET_TO "rs274ngc.var"; int print_stack; if (argc > 3) { fprintf(stderr, "Usage \"%s\"\n", argv[0]); fprintf(stderr, " or \"%s <input file>\"\n", argv[0]); fprintf(stderr, " or \"%s <input file> <output file>\"\n", argv[0]); exit(1); } do_next SET_TO 2; /* 2=stop */ block_delete SET_TO OFF; print_stack SET_TO OFF; tool_flag SET_TO 0; strcpy_s(_parameter_file_name, sizeof(_parameter_file_name), default_name); _outfile SET_TO stdout; /* may be reset below */ for(; ;) { fprintf(stderr, "enter a number:\n"); fprintf(stderr, "1 = start interpreting\n"); fprintf(stderr, "2 = choose parameter file ...\n"); fprintf(stderr, "3 = read tool file ...\n"); fprintf(stderr, "4 = turn block delete switch %s\n", ((block_delete IS OFF) ? "ON" : "OFF")); fprintf(stderr, "5 = adjust error handling...\n"); fprintf(stderr, "enter choice => "); fgets(buffer, sizeof(buffer), stdin); if (sscanf_s(buffer,"%d", &choice) ISNT 1) continue; if (choice IS 1) break; else if (choice IS 2) { if (designate_parameter_file(_parameter_file_name,sizeof(_parameter_file_name)) ISNT 0) exit(1); } else if (choice IS 3) { if (read_tool_file("") ISNT 0) exit(1); tool_flag SET_TO 1; } else if (choice IS 4) block_delete SET_TO ((block_delete IS OFF) ? ON : OFF); else if (choice IS 5) adjust_error_handling(argc, &print_stack, &do_next); } fprintf(stderr, "executing\n"); if (tool_flag IS 0) { if (read_tool_file("rs274ngc.tool_default") ISNT 0) exit(1); } if (argc IS 3) { fopen_s(&_outfile ,argv[2], "w"); if (_outfile IS NULL) { fprintf(stderr, "could not open output file %s\n", argv[2]); exit(1); } } if ((status SET_TO rs274ngc_init()) ISNT RS274NGC_OK) { report_error(status, print_stack); exit(1); } if (argc IS 1) status SET_TO interpret_from_keyboard(block_delete, print_stack); else /* if (argc IS 2 or argc IS 3) */ { status SET_TO rs274ngc_open(argv[1]); if (status ISNT RS274NGC_OK) /* do not need to close since not open */ { report_error(status, print_stack); exit(1); } status SET_TO interpret_from_file(do_next, block_delete, print_stack); rs274ngc_file_name(buffer, 5); /* called to exercise the function */ rs274ngc_file_name(buffer, 79); /* called to exercise the function */ rs274ngc_close(); } rs274ngc_line_length(); /* called to exercise the function */ rs274ngc_sequence_number(); /* called to exercise the function */ rs274ngc_active_g_codes(gees); /* called to exercise the function */ rs274ngc_active_m_codes(ems); /* called to exercise the function */ rs274ngc_active_settings(sets); /* called to exercise the function */ rs274ngc_exit(); /* saves parameters */ exit(status); } /***********************************************************************/
charlie-x/rs274ngc
rs274ngc/driver.cpp
C++
gpl-3.0
21,770
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com) * * SharpNEAT 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. * * SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using Redzen.Numerics; using SharpNeat.Utility; namespace SharpNeat.Network { /// <summary> /// Gaussian activation function. Output range is 0 to 1, that is, the tails of the gaussian /// distribution curve tend towards 0 as abs(x) -> Infinity and the gaussian's peak is at x = 0. /// </summary> public class RbfGaussian : IActivationFunction { /// <summary> /// Default instance provided as a public static field. /// </summary> public static readonly IActivationFunction __DefaultInstance = new RbfGaussian(0.1, 0.1); double _auxArgsMutationSigmaCenter; double _auxArgsMutationSigmaRadius; #region Constructor /// <summary> /// Construct with the specified radial basis function auxiliary arguments. /// </summary> /// <param name="auxArgsMutationSigmaCenter">Radial basis function center.</param> /// <param name="auxArgsMutationSigmaRadius">Radial basis function radius.</param> public RbfGaussian(double auxArgsMutationSigmaCenter, double auxArgsMutationSigmaRadius) { _auxArgsMutationSigmaCenter = auxArgsMutationSigmaCenter; _auxArgsMutationSigmaRadius = auxArgsMutationSigmaRadius; } #endregion /// <summary> /// Gets the unique ID of the function. Stored in network XML to identify which function a network or neuron /// is using. /// </summary> public string FunctionId { get { return this.GetType().Name; } } /// <summary> /// Gets a human readable string representation of the function. E.g 'y=1/x'. /// </summary> public string FunctionString { get { return "y = e^(-((x-center)*epsilon)^2)"; } } /// <summary> /// Gets a human readable verbose description of the activation function. /// </summary> public string FunctionDescription { get { return "Gaussian.\r\nEffective yrange->[0,1]"; } } /// <summary> /// Gets a flag that indicates if the activation function accepts auxiliary arguments. /// </summary> public bool AcceptsAuxArgs { get { return true; } } /// <summary> /// Calculates the output value for the specified input value and activation function auxiliary arguments. /// </summary> public double Calculate(double x, double[] auxArgs) { // auxArgs[0] - RBF center. // auxArgs[1] - RBF gaussian epsilon. double d = (x-auxArgs[0]) * Math.Sqrt(auxArgs[1]) * 4.0; return Math.Exp(-(d*d)); } /// <summary> /// Calculates the output value for the specified input value and activation function auxiliary arguments. /// This single precision overload of Calculate() will be used in neural network code /// that has been specifically written to use floats instead of doubles. /// </summary> public float Calculate(float x, float[] auxArgs) { // auxArgs[0] - RBF center. // auxArgs[1] - RBF gaussian epsilon. float d = (x-auxArgs[0]) * (float)Math.Sqrt(auxArgs[1]) * 4f; return (float)Math.Exp(-(d*d)); } /// <summary> /// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly /// added nodes (from an 'add neuron' mutation). /// </summary> public double[] GetRandomAuxArgs(XorShiftRandom rng, double connectionWeightRange) { double[] auxArgs = new double[2]; auxArgs[0] = (rng.NextDouble()-0.5) * 2.0; auxArgs[1] = rng.NextDouble(); return auxArgs; } /// <summary> /// Genetic mutation for auxiliary argument data. /// </summary> public void MutateAuxArgs(double[] auxArgs, XorShiftRandom rng, ZigguratGaussianSampler gaussianSampler, double connectionWeightRange) { // Mutate center. // Add gaussian ditribution sample and clamp result to +-connectionWeightRange. double tmp = auxArgs[0] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaCenter); if(tmp < -connectionWeightRange) { auxArgs[0] = -connectionWeightRange; } else if(tmp > connectionWeightRange) { auxArgs[0] = connectionWeightRange; } else { auxArgs[0] = tmp; } // Mutate radius. // Add gaussian ditribution sample and clamp result to [0,1] tmp = auxArgs[1] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaRadius); if(tmp < 0.0) { auxArgs[1] = 0.0; } else if(tmp > 1.0) { auxArgs[1] = 1.0; } else { auxArgs[1] = tmp; } } } }
BLueders/ENTM_CSharpPort
src/SharpNeatLib/Network/ActivationFunctions/RadialBasis/RbfGaussian.cs
C#
gpl-3.0
5,987
//////////////////////////////////////////////////////// // // GEM - Graphics Environment for Multimedia // // Implementation file // // Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at // zmoelnig@iem.kug.ac.at // For information on usage and redistribution, and for a DISCLAIMER // * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS" // // this file has been generated... //////////////////////////////////////////////////////// #include "GEMglTexParameteri.h" CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexParameteri , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT); ///////////////////////////////////////////////////////// // // GEMglViewport // ///////////////////////////////////////////////////////// // Constructor // GEMglTexParameteri :: GEMglTexParameteri (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) : target(static_cast<GLenum>(arg0)), pname(static_cast<GLenum>(arg1)), param(static_cast<GLint>(arg2)) { m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("target")); m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("pname")); m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("param")); } ///////////////////////////////////////////////////////// // Destructor // GEMglTexParameteri :: ~GEMglTexParameteri () { inlet_free(m_inlet[0]); inlet_free(m_inlet[1]); inlet_free(m_inlet[2]); } ///////////////////////////////////////////////////////// // Render // void GEMglTexParameteri :: render(GemState *state) { glTexParameteri (target, pname, param); } ///////////////////////////////////////////////////////// // Variables // void GEMglTexParameteri :: targetMess (t_float arg1) { // FUN target = static_cast<GLenum>(arg1); setModified(); } void GEMglTexParameteri :: pnameMess (t_float arg1) { // FUN pname = static_cast<GLenum>(arg1); setModified(); } void GEMglTexParameteri :: paramMess (t_float arg1) { // FUN param = static_cast<GLint>(arg1); setModified(); } ///////////////////////////////////////////////////////// // static member functions // void GEMglTexParameteri :: obj_setupCallback(t_class *classPtr) { class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::targetMessCallback), gensym("target"), A_DEFFLOAT, A_NULL); class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::pnameMessCallback), gensym("pname"), A_DEFFLOAT, A_NULL); class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::paramMessCallback), gensym("param"), A_DEFFLOAT, A_NULL); }; void GEMglTexParameteri :: targetMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->targetMess ( static_cast<t_float>(arg0)); } void GEMglTexParameteri :: pnameMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->pnameMess ( static_cast<t_float>(arg0)); } void GEMglTexParameteri :: paramMessCallback (void* data, t_floatarg arg0){ GetMyClass(data)->paramMess ( static_cast<t_float>(arg0)); }
rvega/morphasynth
vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglTexParameteri.cpp
C++
gpl-3.0
3,043
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Linq.Expressions; namespace BusinessLogic.Repositories { public class Repository<T> : IRepository<T> where T : class { private readonly DbContext _context; private readonly DbSet<T> _dbSet; public Repository(DbContext context) { this._context = context; this._dbSet = context.Set<T>(); } public virtual void Add(T entity) { this._dbSet.Add(entity); this._context.SaveChanges(); } public virtual void Delete(int id, string userID) { var entry = this._dbSet.Find(id); this._dbSet.Remove(entry); this._context.SaveChanges(); } public IQueryable<T> GetAll() { return this._dbSet.AsQueryable(); } public T GetByID(int? id, string userID) { return this._dbSet.Find(id); } public void Edit(T entity) { this._context.Set<T>().AddOrUpdate(entity); this._context.SaveChanges(); } public void Edit(List<T> entities) { foreach (var entity in entities) Edit(entity); } public int GetCount() { return this._dbSet.Count(); } private IEnumerable<T> Find(Expression<Func<T, bool>> predicate) { return this._dbSet.Where(predicate); } } }
dsilva609/Project-Cinderella
BusinessLogic/Repositories/Repository.cs
C#
gpl-3.0
1,282
// pythonFlu - Python wrapping for OpenFOAM C++ API // Copyright (C) 2010- Alexey Petrov // Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) // // 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/>. // // See http://sourceforge.net/projects/pythonflu // // Author : Alexey PETROV //--------------------------------------------------------------------------- #ifndef no_tmp_typemap_GeometricFields_hpp #define no_tmp_typemap_GeometricFields_hpp //--------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/fields/tmp/tmp.i" %import "Foam/ext/common/ext_tmp.hxx" //--------------------------------------------------------------------------- %define NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Type, TPatchField, TMesh ) %typecheck( SWIG_TYPECHECK_POINTER ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *ptr; int res_T = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), 0 ); int res_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); int res_ext_tmpT = SWIG_ConvertPtr( $input, (void **) &ptr, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ), 0 ); $1 = SWIG_CheckState( res_T ) || SWIG_CheckState( res_tmpT ) || SWIG_CheckState( res_ext_tmpT ); } %typemap( in ) Foam::GeometricField< Type, TPatchField, TMesh >& { void *argp = 0; int res = 0; res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::GeometricField< Type, TPatchField, TMesh > * ), %convertptr_flags ); if ( SWIG_IsOK( res )&& argp ){ Foam::GeometricField< Type, TPatchField, TMesh > * res = %reinterpret_cast( argp, Foam::GeometricField< Type, TPatchField, TMesh >* ); $1 = res; } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { res = SWIG_ConvertPtr( $input, &argp, $descriptor( Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > >* ), %convertptr_flags ); if ( SWIG_IsOK( res ) && argp ) { Foam::ext_tmp<Foam::GeometricField< Type, TPatchField, TMesh> >* tmp_res =%reinterpret_cast( argp, Foam::ext_tmp< Foam::GeometricField< Type, TPatchField, TMesh > > * ); $1 = tmp_res->operator->(); } else { %argument_fail( res, "$type", $symname, $argnum ); } } } } %enddef //--------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvPatchField, Foam::volMesh ); //---------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //---------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //----------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/symmTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SymmTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //------------------------------------------------------------------------------ %import "Foam/src/OpenFOAM/primitives/sphericalTensor.i" %include "Foam/src/finiteVolume/volMesh.hpp" %include "Foam/src/finiteVolume/fields/fvPatchFields/fvPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::SphericalTensor< Foam::scalar >, Foam::fvPatchField, Foam::volMesh ); //------------------------------------------------------------------------------ %import "Foam/src/OpenFOAM/primitives/scalar.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::scalar, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/vector.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Vector< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- %import "Foam/src/OpenFOAM/primitives/tensor.i" %include "Foam/src/finiteVolume/surfaceMesh.hpp" %include "Foam/src/finiteVolume/fields/fvsPatchFields/fvsPatchField.cpp" NO_TMP_TYPEMAP_GEOMETRIC_FIELD( Foam::Tensor< Foam::scalar >, Foam::fvsPatchField, Foam::surfaceMesh ); //------------------------------------------------------------------------------- #endif
ivan7farre/PyFreeFOAM
Foam/src/OpenFOAM/fields/GeometricFields/no_tmp_typemap_GeometricFields.hpp
C++
gpl-3.0
6,243
namespace Tsu.Voltmeters.Appa { partial class Multimeter109NControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { this.Disconnect(); if (disposing && (components != null)) { com2usb.Dispose(); components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
romul/Measurement-Studio
APPA_Multimeter/Multimeter109nControl.Designer.cs
C#
gpl-3.0
1,142
package ru.trolsoft.utils.files; import ru.trolsoft.utils.StrUtils; import java.io.*; import java.util.Random; /** * Created on 07/02/17. */ public class IntelHexWriter { private final Writer writer; /** * */ private int segmentAddress = 0; public IntelHexWriter(Writer writer) { if (writer instanceof BufferedWriter) { this.writer = writer; } else { this.writer = new BufferedWriter(writer); } } // public IntelHexWriter(String fileName) throws IOException { // this(new FileWriter(fileName)); // } public void addData(int offset, byte data[], int bytesPerLine) throws IOException { if (data.length == 0) { return; } //System.out.println("::" + data.length); byte buf[] = new byte[bytesPerLine]; int pos = 0; int bytesToAdd = data.length; while (bytesToAdd > 0) { if (offset % bytesPerLine != 0) { // can be true for first line if offset doesn't aligned buf = new byte[bytesPerLine - offset % bytesPerLine]; } else if (bytesToAdd < bytesPerLine) { // last line buf = new byte[bytesToAdd]; } else if (buf.length != bytesPerLine) { buf = new byte[bytesPerLine]; } System.arraycopy(data, pos, buf, 0, buf.length); // Goto next segment if no more space available in current if (offset + buf.length - 1 > segmentAddress + 0xffff) { int nextSegment = ((offset + bytesPerLine) >> 4) << 4; addSegmentRecord(nextSegment); segmentAddress = nextSegment; } addDataRecord(offset & 0xffff, buf); bytesToAdd -= buf.length; offset += buf.length; pos += buf.length; } } private void addSegmentRecord(int offset) throws IOException { int paragraph = offset >> 4; int hi = (paragraph >> 8) & 0xff; int lo = paragraph & 0xff; int crc = 2 + 2 + hi + lo; crc = (-crc) & 0xff; String rec = ":02000002" + hex(hi) + hex(lo) + hex(crc); write(rec); // 02 0000 02 10 00 EC //:02 0000 04 00 01 F9 } private void addEofRecord() throws IOException { write(":00000001FF"); } private void write(String s) throws IOException { writer.write(s); //writer.write(0x0d); writer.write(0x0a); } private void addDataRecord(int offset, byte[] data) throws IOException { int hi = (offset >> 8) & 0xff; int lo = offset & 0xff; int crc = data.length + hi + lo; String rec = ":" + hex(data.length) + hex(hi) + hex(lo) + "00"; for (byte d : data) { rec += hex(d); crc += d; } crc = (-crc) & 0xff; rec += hex(crc); write(rec); } private static String hex(int b) { return StrUtils.byteToHexStr((byte)b); } public void done() throws IOException { addEofRecord(); writer.flush(); } public static void main(String ... args) throws IOException { IntelHexWriter w = new IntelHexWriter(new OutputStreamWriter(System.out)); // w.addDataRecord(0x0190, new byte[] {0x56, 0x45, 0x52, 0x53, 0x49, 0x4F, 0x4E, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x41, // 0x54, 0x0D, 0x0A}); byte[] data = new byte[Math.abs(new Random().nextInt() % 1024)]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i % 0xff); } w.addData(0x10000 - 0x100, data, 16); w.done(); } }
trol73/avr-bootloader
software/java/src/ru/trolsoft/utils/files/IntelHexWriter.java
Java
gpl-3.0
3,697
<?php /** * @package omeka * @subpackage solr-search * @copyright 2012 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ class SolrSearch_AdminController extends Omeka_Controller_AbstractActionController { /** * Display the "Server Configuration" form. */ public function serverAction() { $form = new SolrSearch_Form_Server(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } } // Are the current parameters valid? if (SolrSearch_Helpers_Index::pingSolrServer()) { // Notify valid connection. $this->_helper->flashMessenger( __('Solr connection is valid.'), 'success' ); } // Notify invalid connection. else $this->_helper->flashMessenger( __('Solr connection is invalid.'), 'error' ); $this->view->form = $form; } /** * Display the "Collection Configuration" form. * * @return void * @author Eric Rochester <erochest@virginia.edu> **/ public function collectionsAction() { if ($this->_request->isPost()) { $this->_updateCollections($this->_request->getPost()); } $this->view->form = $this->_collectionsForm(); } /** * Retourne l'état actuel de l'indexation Solr en JSON */ public function getIndexStatusAction() { $this->view->status = SolrSearch_Helpers_Index::getStatusViaHandler(); } /** * This updates the excluded collections. * * @param array $post The post data to update from. * @return void * @author Eric Rochester <erochest@virginia.edu> **/ protected function _updateCollections($post) { $etable = $this->_helper->db->getTable('SolrSearchExclude'); $etable->query("DELETE FROM {$etable->getTableName()};"); $c = 0; if (isset($post['solrexclude'])) { foreach ($post['solrexclude'] as $exc) { $exclude = new SolrSearchExclude(); $exclude->collection_id = $exc; $exclude->save(); $c += 1; } } $this->_helper->_flashMessenger("$c collection(s) excluded."); } /** * This returns the form for the collections. * * @return Zend_Form * @author Eric Rochester <erochest@virginia.edu> **/ protected function _collectionsForm() { $ctable = $this->_helper->db->getTable('Collection'); $collections = $ctable->findBy(array('public' => 1)); $form = new Zend_Form(); $form->setAction(url('solr-search/collections'))->setMethod('post'); $collbox = new Zend_Form_Element_MultiCheckbox('solrexclude'); $form->addElement($collbox); foreach ($collections as $c) { $title = metadata($c, array('Dublin Core', 'Title')); $collbox->addMultiOption("{$c->id}", $title); } $etable = $this->_helper->db->getTable('SolrSearchExclude'); $excludes = array(); foreach ($etable->findAll() as $exclude) { $excludes[] = "{$exclude->collection_id}"; } $collbox->setValue($excludes); $form->addElement('submit', 'Exclude'); return $form; } /** * Display the "Field Configuration" form. */ public function fieldsAction() { // Get the facet mapping table. $fieldTable = $this->_helper->db->getTable('SolrSearchField'); // If the form was submitted. if ($this->_request->isPost()) { // Gather the POST arguments. $post = $this->_request->getPost(); // Save the facets. foreach ($post['facets'] as $name => $data) { // Were "Is Indexed?" and "Is Facet?" checked? $indexed = array_key_exists('is_indexed', $data) ? 1 : 0; $faceted = array_key_exists('is_facet', $data) ? 1 : 0; // Load the facet mapping. $facet = $fieldTable->findBySlug($name); // Apply the updated values. $facet->label = $data['label']; $facet->is_indexed = $indexed; $facet->is_facet = $faceted; $facet->save(); } // Flash success. $this->_helper->flashMessenger( __('Fields successfully updated! Be sure to reindex.'), 'success' ); } // Assign the facet groups. $this->view->groups = $fieldTable->groupByElementSet(); } /** * Display the "Results Configuration" form. */ public function resultsAction() { $form = new SolrSearch_Form_Results(); // If a valid form was submitted. if ($this->_request->isPost() && $form->isValid($_POST)) { // Set the options. foreach ($form->getValues() as $option => $value) { set_option($option, $value); } // Flash success. $this->_helper->flashMessenger( __('Highlighting options successfully saved!'), 'success' ); } $this->view->form = $form; } /** * Display the "Index Items" form. */ public function reindexAction() { $form = new SolrSearch_Form_Reindex(); if ($this->_request->isPost()) { try { // Clear and reindex. Zend_Registry::get('job_dispatcher')->sendLongRunning( 'SolrSearch_Job_Reindex' ); } catch (Exception $err) { } } $totalDocumentCount = $this->_helper->db->getTable('NewspaperReaderDocuments')->count(); $this->view->form = $form; $this->view->totalDocumentCount = $totalDocumentCount; } }
moobee/omeka-newspaper-reader
SolrSearch/controllers/AdminController.php
PHP
gpl-3.0
6,232
import re import traceback from urllib.parse import quote from requests.utils import dict_from_cookiejar from sickchill import logger from sickchill.helper.common import convert_size, try_int from sickchill.oldbeard import tvcache from sickchill.oldbeard.bs4_parser import BS4Parser from sickchill.providers.torrent.TorrentProvider import TorrentProvider class Provider(TorrentProvider): def __init__(self): super().__init__("Pretome") self.username = None self.password = None self.pin = None self.minseed = 0 self.minleech = 0 self.urls = { "base_url": "https://pretome.info", "login": "https://pretome.info/takelogin.php", "detail": "https://pretome.info/details.php?id=%s", "search": "https://pretome.info/browse.php?search=%s%s", "download": "https://pretome.info/download.php/%s/%s.torrent", } self.url = self.urls["base_url"] self.categories = "&st=1&cat%5B%5D=7" self.proper_strings = ["PROPER", "REPACK"] self.cache = tvcache.TVCache(self) def _check_auth(self): if not self.username or not self.password or not self.pin: logger.warning("Invalid username or password or pin. Check your settings") return True def login(self): if any(dict_from_cookiejar(self.session.cookies).values()): return True login_params = {"username": self.username, "password": self.password, "login_pin": self.pin} response = self.get_url(self.urls["login"], post_data=login_params, returns="text") if not response: logger.warning("Unable to connect to provider") return False if re.search("Username or password incorrect", response): logger.warning("Invalid username or password. Check your settings") return False return True def search(self, search_params, age=0, ep_obj=None): results = [] if not self.login(): return results for mode in search_params: items = [] logger.debug(_("Search Mode: {mode}".format(mode=mode))) for search_string in search_params[mode]: if mode != "RSS": logger.debug(_("Search String: {search_string}".format(search_string=search_string))) search_url = self.urls["search"] % (quote(search_string), self.categories) data = self.get_url(search_url, returns="text") if not data: continue try: with BS4Parser(data, "html5lib") as html: # Continue only if one Release is found empty = html.find("h2", text="No .torrents fit this filter criteria") if empty: logger.debug("Data returned from provider does not contain any torrents") continue torrent_table = html.find("table", style="border: none; width: 100%;") if not torrent_table: logger.exception("Could not find table of torrents") continue torrent_rows = torrent_table("tr", class_="browse") for result in torrent_rows: cells = result("td") size = None link = cells[1].find("a", style="font-size: 1.25em; font-weight: bold;") torrent_id = link["href"].replace("details.php?id=", "") try: if link.get("title", ""): title = link["title"] else: title = link.contents[0] download_url = self.urls["download"] % (torrent_id, link.contents[0]) seeders = int(cells[9].contents[0]) leechers = int(cells[10].contents[0]) # Need size for failed downloads handling if size is None: torrent_size = cells[7].text size = convert_size(torrent_size) or -1 except (AttributeError, TypeError): continue if not all([title, download_url]): continue # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: if mode != "RSS": logger.debug( "Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format( title, seeders, leechers ) ) continue item = {"title": title, "link": download_url, "size": size, "seeders": seeders, "leechers": leechers, "hash": ""} if mode != "RSS": logger.debug("Found result: {0} with {1} seeders and {2} leechers".format(title, seeders, leechers)) items.append(item) except Exception: logger.exception("Failed parsing provider. Traceback: {0}".format(traceback.format_exc())) # For each search mode sort all the items by seeders if available items.sort(key=lambda d: try_int(d.get("seeders", 0)), reverse=True) results += items return results
h3llrais3r/SickRage
sickchill/oldbeard/providers/pretome.py
Python
gpl-3.0
5,958
/* * Copyright (c) 2010 The University of Reading * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University of Reading, nor the names of the * authors or contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.ac.rdg.resc.edal.coverage.domain; import java.util.List; import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * A geospatial/temporal domain: defines the set of points for which a {@link DiscreteCoverage} * is defined. The domain is comprised of a set of unique domain objects in a * defined order. The domain therefore has the semantics of both a {@link Set} * and a {@link List} of domain objects. * @param <DO> The type of the domain object * @author Jon */ public interface Domain<DO> { /** * Gets the coordinate reference system to which objects in this domain are * referenced. Returns null if the domain objects cannot be referenced * to an external coordinate reference system. * @return the coordinate reference system to which objects in this domain are * referenced, or null if the domain objects are not externally referenced. */ public CoordinateReferenceSystem getCoordinateReferenceSystem(); /** * Returns the {@link List} of domain objects that comprise this domain. * @todo There may be issues for large grids if the number of domain objects * is greater than Integer.MAX_VALUE, as the size of this list will be recorded * incorrectly. This will only happen for very large domains (e.g. large grids). */ public List<DO> getDomainObjects(); /** * <p>Returns the number of domain objects in the domain.</p> * <p>This is a long integer because grids can grow very large, beyond the * range of a 4-byte integer.</p> */ public long size(); }
nansencenter/GreenSeasADC-portlet
docroot/WEB-INF/src/uk/ac/rdg/resc/edal/coverage/domain/Domain.java
Java
gpl-3.0
3,145
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisGovernanceDAO; import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisGovernanceManager; import org.cgiar.ccafs.marlo.data.model.ReportSynthesisGovernance; import java.util.List; import javax.inject.Inject; import javax.inject.Named; /** * @author CCAFS */ @Named public class ReportSynthesisGovernanceManagerImpl implements ReportSynthesisGovernanceManager { private ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO; // Managers @Inject public ReportSynthesisGovernanceManagerImpl(ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO) { this.reportSynthesisGovernanceDAO = reportSynthesisGovernanceDAO; } @Override public void deleteReportSynthesisGovernance(long reportSynthesisGovernanceId) { reportSynthesisGovernanceDAO.deleteReportSynthesisGovernance(reportSynthesisGovernanceId); } @Override public boolean existReportSynthesisGovernance(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.existReportSynthesisGovernance(reportSynthesisGovernanceID); } @Override public List<ReportSynthesisGovernance> findAll() { return reportSynthesisGovernanceDAO.findAll(); } @Override public ReportSynthesisGovernance getReportSynthesisGovernanceById(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.find(reportSynthesisGovernanceID); } @Override public ReportSynthesisGovernance saveReportSynthesisGovernance(ReportSynthesisGovernance reportSynthesisGovernance) { return reportSynthesisGovernanceDAO.save(reportSynthesisGovernance); } }
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ReportSynthesisGovernanceManagerImpl.java
Java
gpl-3.0
2,612
/*jshint expr:true */ describe("Services: Core System Messages", function() { beforeEach(module("risevision.core.systemmessages")); beforeEach(module(function ($provide) { //stub services $provide.service("$q", function() {return Q;}); $provide.value("userState", { isRiseVisionUser: function () {return true; } }); })); it("should exist", function() { inject(function(getCoreSystemMessages) { expect(getCoreSystemMessages).be.defined; }); }); });
Rise-Vision/ng-core-api-client
test/unit/svc-system-messages-spec.js
JavaScript
gpl-3.0
499
// Copyright ©2015 The gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/lapack" ) // Dlasr applies a sequence of plane rotations to the m×n matrix A. This series // of plane rotations is implicitly represented by a matrix P. P is multiplied // by a depending on the value of side -- A = P * A if side == lapack.Left, // A = A * P^T if side == lapack.Right. // //The exact value of P depends on the value of pivot, but in all cases P is // implicitly represented by a series of 2×2 rotation matrices. The entries of // rotation matrix k are defined by s[k] and c[k] // R(k) = [ c[k] s[k]] // [-s[k] s[k]] // If direct == lapack.Forward, the rotation matrices are applied as // P = P(z-1) * ... * P(2) * P(1), while if direct == lapack.Backward they are // applied as P = P(1) * P(2) * ... * P(n). // // pivot defines the mapping of the elements in R(k) to P(k). // If pivot == lapack.Variable, the rotation is performed for the (k, k+1) plane. // P(k) = [1 ] // [ ... ] // [ 1 ] // [ c[k] s[k] ] // [ -s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // if pivot == lapack.Top, the rotation is performed for the (1, k+1) plane, // P(k) = [c[k] s[k] ] // [ 1 ] // [ ... ] // [ 1 ] // [-s[k] c[k] ] // [ 1 ] // [ ... ] // [ 1] // and if pivot == lapack.Bottom, the rotation is performed for the (k, z) plane. // P(k) = [1 ] // [ ... ] // [ 1 ] // [ c[k] s[k]] // [ 1 ] // [ ... ] // [ 1 ] // [ -s[k] c[k]] // s and c have length m - 1 if side == blas.Left, and n - 1 if side == blas.Right. // // Dlasr is an internal routine. It is exported for testing purposes. func (impl Implementation) Dlasr(side blas.Side, pivot lapack.Pivot, direct lapack.Direct, m, n int, c, s, a []float64, lda int) { checkMatrix(m, n, a, lda) if side != blas.Left && side != blas.Right { panic(badSide) } if pivot != lapack.Variable && pivot != lapack.Top && pivot != lapack.Bottom { panic(badPivot) } if direct != lapack.Forward && direct != lapack.Backward { panic(badDirect) } if side == blas.Left { if len(c) < m-1 { panic(badSlice) } if len(s) < m-1 { panic(badSlice) } } else { if len(c) < n-1 { panic(badSlice) } if len(s) < n-1 { panic(badSlice) } } if m == 0 || n == 0 { return } if side == blas.Left { if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp2 := a[j*lda+i] tmp := a[(j+1)*lda+i] a[(j+1)*lda+i] = ctmp*tmp - stmp*tmp2 a[j*lda+i] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < m; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } return } for j := m - 1; j >= 1; j-- { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[i] a[j*lda+i] = ctmp*tmp - stmp*tmp2 a[i] = stmp*tmp + ctmp*tmp2 } } } } } return } if direct == lapack.Forward { for j := 0; j < m-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } for j := m - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < n; i++ { tmp := a[j*lda+i] tmp2 := a[(m-1)*lda+i] a[j*lda+i] = stmp*tmp2 + ctmp*tmp a[(m-1)*lda+i] = ctmp*tmp2 - stmp*tmp } } } return } if pivot == lapack.Variable { if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j+1] tmp2 := a[i*lda+j] a[i*lda+j+1] = ctmp*tmp - stmp*tmp2 a[i*lda+j] = stmp*tmp + ctmp*tmp2 } } } return } else if pivot == lapack.Top { if direct == lapack.Forward { for j := 1; j < n; j++ { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } for j := n - 1; j >= 1; j-- { ctmp := c[j-1] stmp := s[j-1] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda] a[i*lda+j] = ctmp*tmp - stmp*tmp2 a[i*lda] = stmp*tmp + ctmp*tmp2 } } } return } if direct == lapack.Forward { for j := 0; j < n-1; j++ { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } return } for j := n - 2; j >= 0; j-- { ctmp := c[j] stmp := s[j] if ctmp != 1 || stmp != 0 { for i := 0; i < m; i++ { tmp := a[i*lda+j] tmp2 := a[i*lda+n-1] a[i*lda+j] = stmp*tmp2 + ctmp*tmp a[i*lda+n-1] = ctmp*tmp2 - stmp*tmp } } } }
pts-eduardoacuna/pachy-learning
vendor/gonum.org/v1/gonum/lapack/gonum/dlasr.go
GO
gpl-3.0
6,827
# -*- encoding: UTF-8 -*- import re import sys import os import traceback from ..ibdawg import IBDAWG from ..echo import echo from . import gc_options __all__ = [ "lang", "locales", "pkg", "name", "version", "author", \ "load", "parse", "getDictionary", \ "setOptions", "getOptions", "getOptionsLabels", "resetOptions", \ "ignoreRule", "resetIgnoreRules" ] __version__ = u"${version}" lang = u"${lang}" locales = ${loc} pkg = u"${implname}" name = u"${name}" version = u"${version}" author = u"${author}" # commons regexes _zEndOfSentence = re.compile(u'([.?!:;…][ .?!… »”")]*|.$)') _zBeginOfParagraph = re.compile(u"^\W*") _zEndOfParagraph = re.compile(u"\W*$") _zNextWord = re.compile(u" +(\w[\w-]*)") _zPrevWord = re.compile(u"(\w[\w-]*) +$") # grammar rules and dictionary _rules = None _dOptions = dict(gc_options.dOpt) # duplication necessary, to be able to reset to default _aIgnoredRules = set() _oDict = None _dAnalyses = {} # cache for data from dictionary _GLOBALS = globals() #### Parsing def parse (sText, sCountry="${country_default}", bDebug=False, dOptions=None): "analyses the paragraph sText and returns list of errors" aErrors = None sAlt = sText dDA = {} dOpt = _dOptions if not dOptions else dOptions # parse paragraph try: sNew, aErrors = _proofread(sText, sAlt, 0, True, dDA, sCountry, dOpt, bDebug) if sNew: sText = sNew except: raise # parse sentences for iStart, iEnd in _getSentenceBoundaries(sText): if 4 < (iEnd - iStart) < 2000: dDA.clear() try: _, errs = _proofread(sText[iStart:iEnd], sAlt[iStart:iEnd], iStart, False, dDA, sCountry, dOpt, bDebug) aErrors.extend(errs) except: raise return aErrors def _getSentenceBoundaries (sText): iStart = _zBeginOfParagraph.match(sText).end() for m in _zEndOfSentence.finditer(sText): yield (iStart, m.end()) iStart = m.end() def _proofread (s, sx, nOffset, bParagraph, dDA, sCountry, dOptions, bDebug): aErrs = [] bChange = False if not bParagraph: # after the first pass, we modify automatically some characters if u" " in s: s = s.replace(u" ", u' ') # nbsp bChange = True if u" " in s: s = s.replace(u" ", u' ') # nnbsp bChange = True if u"@" in s: s = s.replace(u"@", u' ') bChange = True if u"'" in s: s = s.replace(u"'", u"’") bChange = True if u"‑" in s: s = s.replace(u"‑", u"-") # nobreakdash bChange = True bIdRule = option('idrule') for sOption, lRuleGroup in _getRules(bParagraph): if not sOption or dOptions.get(sOption, False): for zRegex, bUppercase, sRuleId, lActions in lRuleGroup: if sRuleId not in _aIgnoredRules: for m in zRegex.finditer(s): for sFuncCond, cActionType, sWhat, *eAct in lActions: # action in lActions: [ condition, action type, replacement/suggestion/action[, iGroup[, message, URL]] ] try: if not sFuncCond or _GLOBALS[sFuncCond](s, sx, m, dDA, sCountry): if cActionType == "-": # grammar error # (text, replacement, nOffset, m, iGroup, sId, bUppercase, sURL, bIdRule) aErrs.append(_createError(s, sWhat, nOffset, m, eAct[0], sRuleId, bUppercase, eAct[1], eAct[2], bIdRule, sOption)) elif cActionType == "~": # text processor s = _rewrite(s, sWhat, eAct[0], m, bUppercase) bChange = True if bDebug: echo(u"~ " + s + " -- " + m.group(eAct[0]) + " # " + sRuleId) elif cActionType == "=": # disambiguation _GLOBALS[sWhat](s, m, dDA) if bDebug: echo(u"= " + m.group(0) + " # " + sRuleId + "\nDA: " + str(dDA)) else: echo("# error: unknown action at " + sRuleId) except Exception as e: raise Exception(str(e), sRuleId) if bChange: return (s, aErrs) return (False, aErrs) def _createWriterError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error for Writer (LO/OO)" xErr = SingleProofreadingError() #xErr = uno.createUnoStruct( "com.sun.star.linguistic2.SingleProofreadingError" ) xErr.nErrorStart = nOffset + m.start(iGroup) xErr.nErrorLength = m.end(iGroup) - m.start(iGroup) xErr.nErrorType = PROOFREADING xErr.aRuleIdentifier = sId # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, sugg.split("|"))) else: xErr.aSuggestions = tuple(sugg.split("|")) else: xErr.aSuggestions = () elif sRepl == "_": xErr.aSuggestions = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, m.expand(sRepl).split("|"))) else: xErr.aSuggestions = tuple(m.expand(sRepl).split("|")) # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) xErr.aShortComment = sMessage # sMessage.split("|")[0] # in context menu xErr.aFullComment = sMessage # sMessage.split("|")[-1] # in dialog if bIdRule: xErr.aShortComment += " # " + sId # URL if sURL: p = PropertyValue() p.Name = "FullCommentURL" p.Value = sURL xErr.aProperties = (p,) else: xErr.aProperties = () return xErr def _createDictError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): "error as a dictionary" dErr = {} dErr["nStart"] = nOffset + m.start(iGroup) dErr["nEnd"] = nOffset + m.end(iGroup) dErr["sRuleId"] = sId dErr["sType"] = sOption if sOption else "notype" # suggestions if sRepl[0:1] == "=": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, sugg.split("|"))) else: dErr["aSuggestions"] = sugg.split("|") else: dErr["aSuggestions"] = () elif sRepl == "_": dErr["aSuggestions"] = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr["aSuggestions"] = list(map(str.capitalize, m.expand(sRepl).split("|"))) else: dErr["aSuggestions"] = m.expand(sRepl).split("|") # Message if sMsg[0:1] == "=": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) dErr["sMessage"] = sMessage if bIdRule: dErr["sMessage"] += " # " + sId # URL dErr["URL"] = sURL if sURL else "" return dErr def _rewrite (s, sRepl, iGroup, m, bUppercase): "text processor: write sRepl in s at iGroup position" ln = m.end(iGroup) - m.start(iGroup) if sRepl == "*": sNew = " " * ln elif sRepl == ">" or sRepl == "_" or sRepl == u"~": sNew = sRepl + " " * (ln-1) elif sRepl == "@": sNew = "@" * ln elif sRepl[0:1] == "=": if sRepl[1:2] != "@": sNew = _GLOBALS[sRepl[1:]](s, m) sNew = sNew + " " * (ln-len(sNew)) else: sNew = _GLOBALS[sRepl[2:]](s, m) sNew = sNew + "@" * (ln-len(sNew)) if bUppercase and m.group(iGroup)[0:1].isupper(): sNew = sNew.capitalize() else: sNew = m.expand(sRepl) sNew = sNew + " " * (ln-len(sNew)) return s[0:m.start(iGroup)] + sNew + s[m.end(iGroup):] def ignoreRule (sId): _aIgnoredRules.add(sId) def resetIgnoreRules (): _aIgnoredRules.clear() #### init try: # LibreOffice / OpenOffice from com.sun.star.linguistic2 import SingleProofreadingError from com.sun.star.text.TextMarkupType import PROOFREADING from com.sun.star.beans import PropertyValue #import lightproof_handler_${implname} as opt _createError = _createWriterError except ImportError: _createError = _createDictError def load (): global _oDict try: _oDict = IBDAWG("${binary_dic}") except: traceback.print_exc() def setOptions (dOpt): _dOptions.update(dOpt) def getOptions (): return _dOptions def getOptionsLabels (sLang): return gc_options.getUI(sLang) def resetOptions (): global _dOptions _dOptions = dict(gc_options.dOpt) def getDictionary (): return _oDict def _getRules (bParagraph): try: if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules except: _loadRules() if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules def _loadRules2 (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rule in chain(_rules.lParagraphRules, _rules.lSentenceRules): try: rule[1] = re.compile(rule[1]) except: echo("Bad regular expression in # " + str(rule[3])) rule[1] = "(?i)<Grammalecte>" def _loadRules (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rulegroup in chain(_rules.lParagraphRules, _rules.lSentenceRules): for rule in rulegroup[1]: try: rule[0] = re.compile(rule[0]) except: echo("Bad regular expression in # " + str(rule[2])) rule[0] = "(?i)<Grammalecte>" def _getPath (): return os.path.join(os.path.dirname(sys.modules[__name__].__file__), __name__ + ".py") #### common functions def option (sOpt): "return True if option sOpt is active" return _dOptions.get(sOpt, False) def displayInfo (dDA, tWord): "for debugging: retrieve info of word" if not tWord: echo("> nothing to find") return True if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): echo("> not in FSA") return True if tWord[0] in dDA: echo("DA: " + str(dDA[tWord[0]])) echo("FSA: " + str(_dAnalyses[tWord[1]])) return True def _storeMorphFromFSA (sWord): "retrieves morphologies list from _oDict -> _dAnalyses" global _dAnalyses _dAnalyses[sWord] = _oDict.getMorph(sWord) return True if _dAnalyses[sWord] else False def morph (dDA, tWord, sPattern, bStrict=True, bNoWord=False): "analyse a tuple (position, word), return True if sPattern in morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] if not lMorph: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in lMorph) return any(p.search(s) for s in lMorph) def morphex (dDA, tWord, sPattern, sNegPattern, bNoWord=False): "analyse a tuple (position, word), returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation on)" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in lMorph): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in lMorph) def analyse (sWord, sPattern, bStrict=True): "analyse a word, return True if sPattern in morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False if not _dAnalyses[sWord]: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in _dAnalyses[sWord]) return any(p.search(s) for s in _dAnalyses[sWord]) def analysex (sWord, sPattern, sNegPattern): "analyse a word, returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation off)" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in _dAnalyses[sWord]): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in _dAnalyses[sWord]) def stem (sWord): "returns a list of sWord's stems" if not sWord: return [] if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return [] return [ s[1:s.find(" ")] for s in _dAnalyses[sWord] ] ## functions to get text outside pattern scope # warning: check compile_rules.py to understand how it works def nextword (s, iStart, n): "get the nth word of the input string or empty string" m = re.match(u"( +[\\w%-]+){" + str(n-1) + u"} +([\\w%-]+)", s[iStart:]) if not m: return None return (iStart+m.start(2), m.group(2)) def prevword (s, iEnd, n): "get the (-)nth word of the input string or empty string" m = re.search(u"([\\w%-]+) +([\\w%-]+ +){" + str(n-1) + u"}$", s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def nextword1 (s, iStart): "get next word (optimization)" m = _zNextWord.match(s[iStart:]) if not m: return None return (iStart+m.start(1), m.group(1)) def prevword1 (s, iEnd): "get previous word (optimization)" m = _zPrevWord.search(s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def look (s, sPattern, sNegPattern=None): "seek sPattern in s (before/after/fulltext), if sNegPattern not in s" if sNegPattern and re.search(sNegPattern, s): return False if re.search(sPattern, s): return True return False def look_chk1 (dDA, s, nOffset, sPattern, sPatternGroup1, sNegPatternGroup1=None): "returns True if s has pattern sPattern and m.group(1) has pattern sPatternGroup1" m = re.search(sPattern, s) if not m: return False try: sWord = m.group(1) nPos = m.start(1) + nOffset except: #print("Missing group 1") return False if sNegPatternGroup1: return morphex(dDA, (nPos, sWord), sPatternGroup1, sNegPatternGroup1) return morph(dDA, (nPos, sWord), sPatternGroup1, False) #### Disambiguator def select (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def exclude (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if not re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) elif lDefault: dDA[nPos] = lDefault #echo("= "+sWord+" "+str(dDA.get(nPos, "null"))) return True def define (dDA, nPos, lMorph): dDA[nPos] = lMorph #echo("= "+str(nPos)+" "+str(dDA[nPos])) return True #### GRAMMAR CHECKER PLUGINS ${plugins} ${generated}
SamuelLongchamps/grammalecte
gc_core/py/gc_engine.py
Python
gpl-3.0
17,150
package com.entrepidea.jvm; import java.util.ArrayList; import java.util.List; /** * @Desc: * @Source: 深入理解Java虚拟机:JVM高级特性与最佳实践(第2版) * Created by jonat on 10/18/2019. * TODO need revisit - the code seem just running - supposedly it should end soon with exceptions. */ public class RuntimeConstantPoolOOM { public static void main(String[] args){ List<String> l = new ArrayList<>(); int i=0; while(true){ l.add(String.valueOf(i++).intern()); } } }
entrepidea/projects
java/java.core/src/main/java/com/entrepidea/jvm/RuntimeConstantPoolOOM.java
Java
gpl-3.0
551
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LobbyClient; using PlasmaShared; using ZkData; namespace ZeroKWeb.SpringieInterface { public class StartSetup { static bool listOnlyThatLevelsModules = false; // may cause bugs /// <summary> /// Sets up all the things that Springie needs to know for the battle: how to balance, who to get extra commanders, what PlanetWars structures to create, etc. /// </summary> public static SpringBattleStartSetup GetSpringBattleStartSetup(BattleContext context) { try { AutohostMode mode = context.GetMode(); var ret = new SpringBattleStartSetup(); if (mode == AutohostMode.Planetwars) { ret.BalanceTeamsResult = Balancer.BalanceTeams(context, true,null, null); context.Players = ret.BalanceTeamsResult.Players; } var commanderTypes = new LuaTable(); var db = new ZkDataContext(); // calculate to whom to send extra comms var accountIDsWithExtraComms = new List<int>(); if (mode == AutohostMode.Planetwars || mode == AutohostMode.Generic || mode == AutohostMode.GameFFA || mode == AutohostMode.Teams) { IOrderedEnumerable<IGrouping<int, PlayerTeam>> groupedByTeam = context.Players.Where(x => !x.IsSpectator).GroupBy(x => x.AllyID).OrderByDescending(x => x.Count()); IGrouping<int, PlayerTeam> biggest = groupedByTeam.FirstOrDefault(); if (biggest != null) { foreach (var other in groupedByTeam.Skip(1)) { int cnt = biggest.Count() - other.Count(); if (cnt > 0) { foreach (Account a in other.Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)).OrderByDescending(x => x.Elo*x.EloWeight).Take( cnt)) accountIDsWithExtraComms.Add(a.AccountID); } } } } bool is1v1 = context.Players.Where(x => !x.IsSpectator).ToList().Count == 2 && context.Bots.Count == 0; // write Planetwars details to modoptions (for widget) Faction attacker = null; Faction defender = null; Planet planet = null; if (mode == AutohostMode.Planetwars) { planet = db.Galaxies.First(x => x.IsDefault).Planets.First(x => x.Resource.InternalName == context.Map); attacker = context.Players.Where(x => x.AllyID == 0 && !x.IsSpectator) .Select(x => db.Accounts.First(y => y.AccountID == x.LobbyID)) .Where(x => x.Faction != null) .Select(x => x.Faction) .First(); defender = planet.Faction; if (attacker == defender) defender = null; ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "attackingFaction", Value = attacker.Shortcut }); if (defender != null) ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "defendingFaction", Value = defender.Shortcut }); ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "planet", Value = planet.Name }); } // write player custom keys (level, elo, is muted, etc.) foreach (PlayerTeam p in context.Players) { Account user = db.Accounts.Find(p.LobbyID); if (user != null) { var userParams = new List<SpringBattleStartSetup.ScriptKeyValuePair>(); ret.UserParameters.Add(new SpringBattleStartSetup.UserCustomParameters { LobbyID = p.LobbyID, Parameters = userParams }); bool userBanMuted = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanMute); if (userBanMuted) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "muted", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "faction", Value = user.Faction != null ? user.Faction.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "clan", Value = user.Clan != null ? user.Clan.Shortcut : "" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "level", Value = user.Level.ToString() }); double elo = mode == AutohostMode.Planetwars ? user.EffectivePwElo : (is1v1 ? user.Effective1v1Elo : user.EffectiveElo); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "elo", Value = Math.Round(elo).ToString() }); // elo for ingame is just ordering for auto /take userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "avatar", Value = user.Avatar }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "admin", Value = (user.IsZeroKAdmin ? "1" : "0") }); if (!p.IsSpectator) { // set valid PW structure attackers if (mode == AutohostMode.Planetwars) { bool allied = user.Faction != null && defender != null && user.Faction != defender && defender.HasTreatyRight(user.Faction, x => x.EffectPreventIngamePwStructureDestruction == true, planet); if (!allied && user.Faction != null && (user.Faction == attacker || user.Faction == defender)) { userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "canAttackPwStructures", Value = "1" }); } } var pu = new LuaTable(); bool userUnlocksBanned = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanUnlocks); bool userCommandersBanned = user.PunishmentsByAccountID.Any(x => !x.IsExpired && x.BanCommanders); if (!userUnlocksBanned) { if (mode != AutohostMode.Planetwars || user.Faction == null) foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock)) pu.Add(unlock.Code); else { foreach (Unlock unlock in user.AccountUnlocks.Select(x => x.Unlock).Union(user.Faction.GetFactionUnlocks().Select(x => x.Unlock)).Where(x => x.UnlockType == UnlockTypes.Unit)) pu.Add(unlock.Code); } } userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "unlocks", Value = pu.ToBase64String() }); if (accountIDsWithExtraComms.Contains(user.AccountID)) userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "extracomm", Value = "1" }); var pc = new LuaTable(); if (!userCommandersBanned) { // set up commander data foreach (Commander c in user.Commanders.Where(x => x.Unlock != null && x.ProfileNumber <= GlobalConst.CommanderProfileCount)) { try { if (string.IsNullOrEmpty(c.Name) || c.Name.Any(x => x == '"') ) { c.Name = c.CommanderID.ToString(); } LuaTable morphTable = new LuaTable(); pc["[\"" + c.Name + "\"]"] = morphTable; // process decoration icons LuaTable decorations = new LuaTable(); foreach (Unlock d in c.CommanderDecorations.Where(x => x.Unlock != null).OrderBy( x => x.SlotID).Select(x => x.Unlock)) { CommanderDecorationIcon iconData = db.CommanderDecorationIcons.FirstOrDefault(x => x.DecorationUnlockID == d.UnlockID); if (iconData != null) { string iconName = null, iconPosition = null; // FIXME: handle avatars and preset/custom icons if (iconData.IconType == (int)DecorationIconTypes.Faction) { iconName = user.Faction != null ? user.Faction.Shortcut : null; } else if (iconData.IconType == (int)DecorationIconTypes.Clan) { iconName = user.Clan != null ? user.Clan.Shortcut : null; } if (iconName != null) { iconPosition = CommanderDecoration.GetIconPosition(d); LuaTable entry = new LuaTable(); entry.Add("image", iconName); decorations.Add("icon_" + iconPosition.ToLower(), entry); } } else decorations.Add(d.Code); } string prevKey = null; for (int i = 0; i <= GlobalConst.NumCommanderLevels; i++) { string key = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i); morphTable.Add(key); // TODO: maybe don't specify morph series in player data, only starting unit var comdef = new LuaTable(); commanderTypes[key] = comdef; comdef["chassis"] = c.Unlock.Code + i; var modules = new LuaTable(); comdef["modules"] = modules; comdef["decorations"] = decorations; comdef["name"] = c.Name.Substring(0, Math.Min(25, c.Name.Length)) + " level " + i; //if (i < GlobalConst.NumCommanderLevels) //{ // comdef["next"] = string.Format("c{0}_{1}_{2}", user.AccountID, c.ProfileNumber, i+1); //} //comdef["owner"] = user.Name; if (i > 0) { comdef["cost"] = c.GetTotalMorphLevelCost(i); if (listOnlyThatLevelsModules) { if (prevKey != null) comdef["prev"] = prevKey; prevKey = key; foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel == i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } else { foreach (Unlock m in c.CommanderModules.Where(x => x.CommanderSlot.MorphLevel <= i && x.Unlock != null).OrderBy( x => x.Unlock.UnlockType).ThenBy(x => x.SlotID).Select(x => x.Unlock)) modules.Add(m.Code); } } } } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw new ApplicationException( string.Format("Error processing commander: {0} - {1} of player {2} - {3}", c.CommanderID, c.Name, user.AccountID, user.Name), ex); } } } else userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "jokecomm", Value = "1" }); userParams.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "commanders", Value = pc.ToBase64String() }); } } } ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "commanderTypes", Value = commanderTypes.ToBase64String() }); // set PW structures if (mode == AutohostMode.Planetwars) { string owner = planet.Faction != null ? planet.Faction.Shortcut : ""; var pwStructures = new LuaTable(); foreach (PlanetStructure s in planet.PlanetStructures.Where(x => x.StructureType!= null && !string.IsNullOrEmpty(x.StructureType.IngameUnitName))) { pwStructures.Add("s" + s.StructureTypeID, new LuaTable { { "unitname", s.StructureType.IngameUnitName }, //{ "isDestroyed", s.IsDestroyed ? true : false }, { "name", string.Format("{0} {1} ({2})", owner, s.StructureType.Name, s.Account!= null ? s.Account.Name:"unowned") }, { "description", s.StructureType.Description } }); } ret.ModOptions.Add(new SpringBattleStartSetup.ScriptKeyValuePair { Key = "planetwarsStructures", Value = pwStructures.ToBase64String() }); } return ret; } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } } } }
TurBoss/Zero-K-Infrastructure
Zero-K.info/SpringieInterface/StartSetup.cs
C#
gpl-3.0
16,808
package com.kimkha.finanvita.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.util.SparseBooleanArray; import android.view.*; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import com.kimkha.finanvita.R; import com.kimkha.finanvita.adapters.AbstractCursorAdapter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public abstract class ItemListFragment extends BaseFragment implements AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String RESULT_EXTRA_ITEM_ID = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_ID"; public static final String RESULT_EXTRA_ITEM_IDS = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_IDS"; // ----------------------------------------------------------------------------------------------------------------- public static final int SELECTION_TYPE_NONE = 0; public static final int SELECTION_TYPE_SINGLE = 1; public static final int SELECTION_TYPE_MULTI = 2; // ----------------------------------------------------------------------------------------------------------------- protected static final String ARG_SELECTION_TYPE = "ARG_SELECTION_TYPE"; protected static final String ARG_ITEM_IDS = "ARG_ITEM_IDS"; protected static final String ARG_IS_OPEN_DRAWER_LAYOUT = "ARG_IS_OPEN_DRAWER_LAYOUT"; // ----------------------------------------------------------------------------------------------------------------- protected static final String STATE_SELECTED_POSITIONS = "STATE_SELECTED_POSITIONS"; // ----------------------------------------------------------------------------------------------------------------- protected static final int LOADER_ITEMS = 1468; // ----------------------------------------------------------------------------------------------------------------- protected ListView list_V; protected View create_V; // ----------------------------------------------------------------------------------------------------------------- protected AbstractCursorAdapter adapter; protected int selectionType; public static Bundle makeArgs(int selectionType, long[] itemIDs) { return makeArgs(selectionType, itemIDs, false); } public static Bundle makeArgs(int selectionType, long[] itemIDs, boolean isOpenDrawerLayout) { final Bundle args = new Bundle(); args.putInt(ARG_SELECTION_TYPE, selectionType); args.putLongArray(ARG_ITEM_IDS, itemIDs); args.putBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, isOpenDrawerLayout); return args; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); // Get arguments final Bundle args = getArguments(); selectionType = args != null ? args.getInt(ARG_SELECTION_TYPE, SELECTION_TYPE_NONE) : SELECTION_TYPE_NONE; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_items_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get views list_V = (ListView) view.findViewById(R.id.list_V); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Setup if (selectionType == SELECTION_TYPE_NONE) { create_V = LayoutInflater.from(getActivity()).inflate(R.layout.li_create_new, list_V, false); list_V.addFooterView(create_V); } adapter = createAdapter(getActivity()); list_V.setAdapter(adapter); list_V.setOnItemClickListener(this); if (getArguments().getBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, false)) { final int paddingHorizontal = getResources().getDimensionPixelSize(R.dimen.dynamic_margin_drawer_narrow_horizontal); list_V.setPadding(paddingHorizontal, list_V.getPaddingTop(), paddingHorizontal, list_V.getPaddingBottom()); } if (selectionType == SELECTION_TYPE_MULTI) { list_V.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); if (savedInstanceState != null) { final ArrayList<Integer> selectedPositions = savedInstanceState.getIntegerArrayList(STATE_SELECTED_POSITIONS); list_V.setTag(selectedPositions); } else { final long[] selectedIDs = getArguments().getLongArray(ARG_ITEM_IDS); list_V.setTag(selectedIDs); } } // Loader getLoaderManager().initLoader(LOADER_ITEMS, null, this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (selectionType == SELECTION_TYPE_MULTI) { final ArrayList<Integer> selectedPositions = new ArrayList<Integer>(); final SparseBooleanArray listPositions = list_V.getCheckedItemPositions(); if (listPositions != null) { for (int i = 0; i < listPositions.size(); i++) { if (listPositions.get(listPositions.keyAt(i))) selectedPositions.add(listPositions.keyAt(i)); } } outState.putIntegerArrayList(STATE_SELECTED_POSITIONS, selectedPositions); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.items_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_create: startItemCreate(getActivity(), item.getActionView()); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { switch (id) { case LOADER_ITEMS: return createItemsLoader(); } return null; } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(cursor); break; } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(null); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { switch (selectionType) { case SELECTION_TYPE_NONE: if (position == adapter.getCount()) startItemCreate(getActivity(), view); else startItemDetails(getActivity(), id, position, adapter, adapter.getCursor(), view); break; case SELECTION_TYPE_SINGLE: // Prepare extras final Bundle extras = new Bundle(); onItemSelected(id, adapter, adapter.getCursor(), extras); Intent data = new Intent(); data.putExtra(RESULT_EXTRA_ITEM_ID, id); data.putExtras(extras); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); break; case SELECTION_TYPE_MULTI: adapter.setSelectedIDs(list_V.getCheckedItemIds()); break; } } protected abstract AbstractCursorAdapter createAdapter(Context context); protected abstract Loader<Cursor> createItemsLoader(); /** * Called when item id along with extras should be returned to another activity. If only item id is necessary, you don't need to do anything. Just extra values should be put in outExtras. * * @param itemId Id of selected item. You don't need to put it to extras. This will be done automatically. * @param adapter Adapter for convenience. * @param c Cursor. * @param outExtras Put all additional data in here. */ protected abstract void onItemSelected(long itemId, AbstractCursorAdapter adapter, Cursor c, Bundle outExtras); /** * Called when you should start item detail activity * * @param context Context. * @param itemId Id of selected item. * @param position Selected position. * @param adapter Adapter for convenience. * @param c Cursor. * @param view */ protected abstract void startItemDetails(Context context, long itemId, int position, AbstractCursorAdapter adapter, Cursor c, View view); /** * Start item create activity here. */ protected abstract void startItemCreate(Context context, View view); public long[] getSelectedItemIDs() { return list_V.getCheckedItemIds(); } protected void bindItems(Cursor c) { boolean needUpdateSelectedIDs = adapter.getCount() == 0 && selectionType == SELECTION_TYPE_MULTI; adapter.swapCursor(c); if (needUpdateSelectedIDs && list_V.getTag() != null) { final Object tag = list_V.getTag(); if (tag instanceof ArrayList) { //noinspection unchecked final ArrayList<Integer> selectedPositions = (ArrayList<Integer>) tag; list_V.setTag(selectedPositions); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedPositions.size(); i++) list_V.setItemChecked(selectedPositions.get(i), true); } else if (tag instanceof long[]) { final long[] selectedIDs = (long[]) tag; final Set<Long> selectedIDsSet = new HashSet<Long>(); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedIDs.length; i++) selectedIDsSet.add(selectedIDs[i]); long itemId; for (int i = 0; i < adapter.getCount(); i++) { itemId = list_V.getItemIdAtPosition(i); if (selectedIDsSet.contains(itemId)) { selectedIDsSet.remove(itemId); list_V.setItemChecked(i, true); if (selectedIDsSet.size() == 0) break; } } } adapter.setSelectedIDs(list_V.getCheckedItemIds()); } } }
kimkha/Finanvita
Finanvita/src/main/java/com/kimkha/finanvita/ui/ItemListFragment.java
Java
gpl-3.0
11,290
// XDwgDirectReader.cpp: implementation of the XDwgDirectReader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "atlbase.h" #include "XDwgDirectReader.h" #include "db.h" #include "DwgEntityDumper.h" #include "ExSystemServices.h" #include "ExHostAppServices.h" #include "RxDynamicModule.h" ////////////////////////////////////////////////////////////////////////// /////////////DwgReaderServices////////////////////////////////////////////// class DwgReaderServices : public ExSystemServices, public ExHostAppServices { protected: ODRX_USING_HEAP_OPERATORS(ExSystemServices); }; OdRxObjectImpl<DwgReaderServices> svcs; ExProtocolExtension theProtocolExtensions; const CString g_szEntityType = "ENTITY_TYPE"; //gisÊý¾Ý¸ñÍø´óС const double DEFAULT_GIS_GRID_SIZE = 120.0; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// XDWGReader::XDWGReader() { //³õʼ»¯DwgDirect¿â odInitialize(&svcs); theProtocolExtensions.initialize(); //ĬÈ϶ÁÈ¡CAD²ÎÊýÉèÖà m_IsReadPolygon = FALSE; m_IsLine2Polygon = FALSE; m_IsBreakBlock = FALSE; m_IsReadInvisible = FALSE; m_IsJoinXDataAttrs = FALSE; m_IsReadBlockPoint = TRUE; m_IsCreateAnnotation = TRUE; m_iUnbreakBlockMode = 0; m_pSpRef = NULL; m_dAnnoScale = 1; m_bConvertAngle = TRUE; m_pProgressBar = NULL; m_pLogRec = NULL; InitAOPointers(); m_Regapps.RemoveAll(); m_unExplodeBlocks.RemoveAll(); m_bFinishedCreateFtCls = FALSE; m_StepNum = 5000; } XDWGReader::~XDWGReader() { m_unExplodeBlocks.RemoveAll(); theProtocolExtensions.uninitialize(); odUninitialize(); if (m_pLogRec != NULL) { delete m_pLogRec; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ɾ³ýÒÑ´æÔÚµÄÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::CheckDeleteFtCls(IFeatureWorkspace* pFtWS, CString sFtClsName) { if (pFtWS == NULL) return; IFeatureClass* pFtCls = NULL; pFtWS->OpenFeatureClass(CComBSTR(sFtClsName), &pFtCls); if (pFtCls != NULL) { IDatasetPtr pDs = pFtCls; if (pDs != NULL) { pDs->Delete(); } } } /******************************************************************** ¼òÒªÃèÊö : ÅúÁ¿¶ÁȡǰµÄ×¼±¸¹¤×÷ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PrepareReadDwg(IWorkspace* pTargetWS, IDataset* pTargetDataset, ISpatialReference* pSpRef) { try { m_pTargetWS = pTargetWS; //³õʼ»¯Ö¸Õë //InitAOPointers(); //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; ////////////////////////////////////////////////////////////////////////// IFeatureDatasetPtr pFeatDataset(pTargetDataset); if (pSpRef == NULL) { ISpatialReferencePtr pUnknownSpRef(CLSID_UnknownCoordinateSystem); m_pSpRef = pUnknownSpRef.Detach(); m_pSpRef->SetDomain(0.0, 1000000000, 0.0, 1000000000); } else { m_pSpRef = pSpRef; } ////////////////////////////////////////////////////////////////////////// //ÉèÖÃΪ¸ß¾«¶È£¬·ñÔòÎÞ·¨´´½¨±í»òFEATURECLASS IControlPrecision2Ptr pControlPrecision(m_pSpRef); if (pControlPrecision != NULL) { pControlPrecision->put_IsHighPrecision(VARIANT_TRUE); } //ÉèÖÿռä²Î¿¼¾«¶ÈÖµ ISpatialReferenceResolutionPtr spatialReferenceResolution = m_pSpRef; spatialReferenceResolution->SetDefaultMResolution(); spatialReferenceResolution->SetDefaultZResolution(); spatialReferenceResolution->SetDefaultXYResolution(); //ÉèÖÿռä×ø±êÎó²îÖµ ISpatialReferenceTolerancePtr spatialReferenceTolerance = m_pSpRef; spatialReferenceTolerance->SetDefaultMTolerance(); spatialReferenceTolerance->SetDefaultZTolerance(); spatialReferenceTolerance->SetDefaultXYTolerance(); m_bFinishedCreateFtCls = FALSE; return TRUE; } catch (...) { WriteLog("³õʼ»¯Òì³£,Çë¼ì²é¹¤×÷¿Õ¼äºÍ¿Õ¼ä²Î¿¼ÊÇ·ñÕýÈ·."); return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨Ä¿±êÒªËØÀà //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::CreateTargetAllFeatureClass() { try { IFeatureWorkspacePtr pFtWS(m_pTargetWS); if (pFtWS == NULL) return FALSE; HRESULT hr; CString sInfoText; //´´½¨ÏµÍ³±í½á¹¹ IFieldsPtr ipFieldsPoint = 0; IFieldsPtr ipFieldsLine = 0; IFieldsPtr ipFieldsPolygon = 0; IFieldsPtr ipFieldsText = 0; IFieldsPtr ipFieldsAnnotation = 0; //Éú³ÉÆÕͨµãÀà×Ö¶Î CreateDwgPointFields(m_pSpRef, &ipFieldsPoint); //Éú³É×¢¼ÇµãÀà×Ö¶Î CreateDwgTextPointFields(m_pSpRef, &ipFieldsText); //Éú³ÉÏßÒªËØÀà×Ö¶Î CreateDwgLineFields(m_pSpRef, &ipFieldsLine); //Éú³ÉÃæÒªËØÀà×Ö¶Î CreateDwgPolygonFields(m_pSpRef, &ipFieldsPolygon); //Éú³É×¢¼Çͼ²ã×Ö¶Î CreateDwgAnnotationFields(m_pSpRef, &ipFieldsAnnotation); ////////////////////////////////////////////////////////////////////////// //Ôö¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î if (m_IsJoinXDataAttrs && m_Regapps.GetCount() > 0) { IFieldsEditPtr ipEditFieldsPoint = ipFieldsPoint; IFieldsEditPtr ipEditFieldsLine = ipFieldsLine; IFieldsEditPtr ipEditFieldsPolygon = ipFieldsPolygon; IFieldsEditPtr ipEditFieldsText = ipFieldsText; IFieldsEditPtr ipEditFieldsAnnotation = ipFieldsAnnotation; CString sRegappName; for (int i = 0; i < m_Regapps.GetCount(); i++) { //´´½¨À©Õ¹ÊôÐÔ×Ö¶Î IFieldPtr ipField(CLSID_Field); IFieldEditPtr ipFieldEdit = ipField; sRegappName = m_Regapps.GetAt(m_Regapps.FindIndex(i)); CComBSTR bsStr = sRegappName; ipFieldEdit->put_Name(bsStr); ipFieldEdit->put_AliasName(bsStr); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(2000); long lFldIndex = 0; ipEditFieldsPoint->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPoint->AddField(ipField); } ipEditFieldsLine->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsLine->AddField(ipField); } ipEditFieldsPolygon->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsPolygon->AddField(ipField); } ipEditFieldsText->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsText->AddField(ipField); } ipEditFieldsAnnotation->FindField(bsStr, &lFldIndex); if (lFldIndex == -1) { ipEditFieldsAnnotation->AddField(ipField); } } } //Èç¹ûÓÐͼ²ãÏÈɾ³ý CheckDeleteFtCls(pFtWS, "Point"); CheckDeleteFtCls(pFtWS, "TextPoint"); CheckDeleteFtCls(pFtWS, "Line"); CheckDeleteFtCls(pFtWS, "Polygon"); CheckDeleteFtCls(pFtWS, "Annotation"); CheckDeleteFtCls(pFtWS, "ExtendTable"); //´´½¨µãͼ²ã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPoint, CComBSTR("Point"), esriFTSimple, m_pFeatClassPoint); if (m_pFeatClassPoint != NULL) { hr = m_pFeatClassPoint->Insert(VARIANT_TRUE, &m_pPointFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPoint->CreateFeatureBuffer(&m_pPointFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨µãFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PointÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨ÏßÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsLine, CComBSTR("Line"), esriFTSimple, m_pFeatClassLine); if (m_pFeatClassLine != NULL) { hr = m_pFeatClassLine->Insert(VARIANT_TRUE, &m_pLineFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassLine->CreateFeatureBuffer(&m_pLineFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÏßFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨LineÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } if (m_IsReadPolygon || m_IsLine2Polygon) { //´´½¨ÃæÒªËØÀà hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsPolygon, CComBSTR("Polygon"), esriFTSimple, m_pFeatClassPolygon); if (m_pFeatClassPolygon != NULL) { hr = m_pFeatClassPolygon->Insert(VARIANT_TRUE, &m_pPolygonFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassPolygon->CreateFeatureBuffer(&m_pPolygonFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨ÃæFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨PolygonÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //arcgis ×¢¼Çͼ²ã if (m_IsCreateAnnotation) { m_pAnnoFtCls = CreateAnnoFtCls(m_pTargetWS, "Annotation", ipFieldsAnnotation); if (m_pAnnoFtCls != NULL) { //ÉèÖÃÏÖʵ±ÈÀý³ß IUnknownPtr pUnk; m_pAnnoFtCls->get_Extension(&pUnk); IAnnoClassAdminPtr pAnnoClassAdmin = pUnk; if (pAnnoClassAdmin != NULL) { hr = pAnnoClassAdmin->put_ReferenceScale(m_dAnnoScale); hr = pAnnoClassAdmin->UpdateProperties(); } hr = m_pAnnoFtCls->Insert(VARIANT_TRUE, &m_pAnnoFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pAnnoFtCls->CreateFeatureBuffer(&m_pAnnoFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨×¢¼ÇFeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨AnnotationÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } //´´½¨×¢¼Çͼ²ã×ÖÌå IFontDispPtr pFont(CLSID_StdFont); IFontPtr fnt = pFont; fnt->put_Name(CComBSTR("ËÎÌå")); CY cy; cy.int64 = 9; fnt->put_Size(cy); m_pAnnoTextFont = pFont.Detach(); } else { //Îı¾µã hr = CreateDatasetFeatureClass(pFtWS, NULL, ipFieldsText, CComBSTR("TextPoint"), esriFTSimple, m_pFeatClassText); if (m_pFeatClassText != NULL) { hr = m_pFeatClassText->Insert(VARIANT_TRUE, &m_pTextFeatureCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾µãFeatureCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pFeatClassText->CreateFeatureBuffer(&m_pTextFeatureBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨Îı¾FeautureBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨TextÒªËØÀàʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } } //À©Õ¹ÊôÐÔ±í hr = CreateExtendTable(pFtWS, CComBSTR("ExtendTable"), &m_pExtendTable); if (m_pExtendTable != NULL) { hr = m_pExtendTable->Insert(VARIANT_TRUE, &m_pExtentTableRowCursor); if (FAILED(hr)) { sInfoText.Format("´´½¨TableBufferʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } hr = m_pExtendTable->CreateRowBuffer(&m_pExtentTableRowBuffer); if (FAILED(hr)) { sInfoText.Format("´´½¨TableCursorʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); } } else { sInfoText.Format("´´½¨ExtendTableʧ°Ü:%s", CatchErrorInfo()); WriteLog(sInfoText); return FALSE; } m_bFinishedCreateFtCls = TRUE; return TRUE; } catch (...) { return FALSE; } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : Öð¸ö¶ÁÈ¡CADÎļþ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// BOOL XDWGReader::ReadFile(LPCTSTR lpdwgFilename) { try { //Éú³ÉÄ¿±êGDBͼ²ã if (!m_bFinishedCreateFtCls) { if (!CreateTargetAllFeatureClass()) { WriteLog("´´½¨Ä¿±êÒªËØÀà³öÏÖÒì³££¬ÎÞ·¨½øÐиñʽת»»¡£"); return FALSE; } } //Çå³ý²»¶ÁµÄͼ²ãÁбí m_UnReadLayers.RemoveAll(); //´ò¿ªCADÎļþ²¢¶ÁÈ¡ //µÃµ½DWGͼÃûºÍÈÕÖ¾ÎļþÃû CString szDatasetName ; CString szLogFileName; int index; CString sFileName = lpdwgFilename; sFileName = sFileName.Mid(sFileName.ReverseFind('\\') + 1); index = ((CString) lpdwgFilename).ReverseFind('\\'); int ilength = ((CString) lpdwgFilename).GetLength(); szDatasetName = CString(lpdwgFilename).Right(ilength - 1 - index); index = szDatasetName.ReverseFind('.'); szDatasetName = szDatasetName.Left(index); m_strDwgName = szDatasetName; // ¼Ç¼¿ªÊ¼´¦Àíʱ¼ä CTime tStartTime = CTime::GetCurrentTime(); CString sInfoText; sInfoText.Format("¿ªÊ¼¶Á %s Îļþ.", lpdwgFilename); WriteLog(sInfoText); if (m_pProgressBar != NULL) { m_pProgressBar->SetPos(0); CString sProgressText; sProgressText.Format("ÕýÔÚ¶ÁÈ¡%s, ÇëÉÔºò...", lpdwgFilename); m_pProgressBar->SetWindowText(sProgressText); } OdDbDatabasePtr pDb; pDb = svcs.readFile(lpdwgFilename, false, false, Oda::kShareDenyReadWrite); if (pDb.isNull()) { WriteLog("DWGÎļþΪ¿Õ!"); } // ´ÓdwgÎļþ»ñµÃ·¶Î§ sInfoText.Format("ͼ·ù·¶Î§: ×îСX×ø±ê:%f, ×î´óX×ø±ê:%f, ×îСY×ø±ê:%f, ×î´óY×ø±ê:%f \n", 0.9 * pDb->getEXTMIN().x, 1.1 * pDb->getEXTMAX().x, 0.9 * pDb->getEXTMIN().y, 1.1 * pDb->getEXTMAX().y); WriteLog(sInfoText); //¶ÁCADÎļþ ReadBlock(pDb); pDb.release(); //¼Ç¼Íê³Éʱ¼ä CTime tEndTime = CTime::GetCurrentTime(); CTimeSpan span = tEndTime - tStartTime; sInfoText.Format("%sÎļþת»»Íê³É!¹²ºÄʱ%dʱ%d·Ö%dÃë.", lpdwgFilename, span.GetHours(), span.GetMinutes(), span.GetSeconds()); WriteLog(sInfoText); WriteLog("=============================================================="); return TRUE; } catch (...) { CString sErr; sErr.Format("%sÎļþ²»´æÔÚ»òÕý´¦ÓÚ´ò¿ª×´Ì¬£¬ÎÞ·¨½øÐÐÊý¾Ý¶ÁÈ¡£¬Çë¼ì²é¡£", lpdwgFilename); WriteLog(sErr); return FALSE; } } /******************************************************************** ¼òÒªÃèÊö : ÉèÖÃÈÕÖ¾´æ·Å·¾¶ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÈÕ ÆÚ : 2008/09/27,BeiJing. ×÷ Õß : ×ÚÁÁ <zongliang@Hy.com.cn> ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::PutLogFilePath(CString sLogFile) { m_pLogRec = new CLogRecorder(sLogFile); m_sLogFilePath = sLogFile; } //дÈÕÖ¾Îļþ void XDWGReader::WriteLog(CString sLog) { if (m_pLogRec == NULL) { return; } if (!sLog.IsEmpty()) { m_pLogRec->WriteLog(sLog); } } //½áÊøDWGµÄ¶ÁÈ¡¹¤×÷ BOOL XDWGReader::CommitReadDwg() { //ÊÍ·ÅÓõ½µÄ¶ÔÏó ReleaseAOs(); if (m_pLogRec != NULL) { m_pLogRec->CloseFile(); } return TRUE; } void XDWGReader::ReadHeader(OdDbDatabase* pDb) { OdString sName = pDb->getFilename(); CString sInfoText; sInfoText.Format("Database was loaded from:%s", sName.c_str()); WriteLog(sInfoText); OdDb::DwgVersion vVer = pDb->originalFileVersion(); sInfoText.Format("File version is: %s", OdDb::DwgVersionToStr(vVer)); WriteLog(sInfoText); sInfoText.Format("Header Variables: %f,%f", pDb->getLTSCALE(), pDb->getATTMODE()); WriteLog(sInfoText); OdDbDate d = pDb->getTDCREATE(); short month, day, year, hour, min, sec, msec; d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); d = pDb->getTDUPDATE(); d.getDate(month, day, year); d.getTime(hour, min, sec, msec); sInfoText.Format(" TDCREATE: %d-%d-%d,%d:%d:%d", month, day, year, hour, min, sec); WriteLog(sInfoText); } void XDWGReader::ReadSymbolTable(OdDbObjectId tableId) { OdDbSymbolTablePtr pTable = tableId.safeOpenObject(); CString sInfoText; sInfoText.Format("±íÃû:%s", pTable->isA()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pTable->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbSymbolTableRecordPtr pTableRec = pIter->getRecordId().safeOpenObject(); CString TableRecName; TableRecName.Format("%s", pTableRec->getName().c_str()); TableRecName.MakeUpper(); sInfoText.Format(" %s<%s>", TableRecName, pTableRec->isA()->name()); WriteLog(sInfoText); } } void XDWGReader::ReadLayers(OdDbDatabase* pDb) { OdDbLayerTablePtr pLayers = pDb->getLayerTableId().safeOpenObject(); CString sInfoText; sInfoText.Format("²ãÃû:%s", pLayers->desc()->name()); WriteLog(sInfoText); OdDbSymbolTableIteratorPtr pIter = pLayers->newIterator(); for (pIter->start(); !pIter->done(); pIter->step()) { OdDbLayerTableRecordPtr pLayer = pIter->getRecordId().safeOpenObject(); CString LayerName; LayerName.Format("%s", pLayer->desc()->name()); LayerName.MakeUpper(); sInfoText.Format(" %s<%s>,layercolor:%d,%s,%s,%s,%s", pLayer->getName().c_str(), LayerName, pLayer->colorIndex(), pLayer->isOff() ? "Off" : "On", pLayer->isLocked() ? "Locked" : "Unlocked", pLayer->isFrozen() ? "Frozen" : "UnFrozen", pLayer->isDependent() ? "Dep. on XRef" : "Not dep. on XRef"); WriteLog(sInfoText); } } /************************************************************************ ¼òÒªÃèÊö : ¶ÁDWGÀ©Õ¹ÊôÐÔ,²¢Ð´Èëµ½À©Õ¹ÊôÐÔ±íÖÐ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::ReadExtendAttribs(OdResBuf* xIter, CString sEntityHandle) { if (xIter == 0 || m_pExtendTable == NULL) return; CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ[]ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*)rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; HRESULT hr; long lFieldIndex; CComBSTR bsStr; CComVariant vtVal; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { CString sAllValues = "[" + pList->GetNext(pos) + "]"; while (pos != NULL) { sAllValues = sAllValues + "[" + pList->GetNext(pos) + "]"; } //Add Extend data to Extend Table bsStr = "Handle"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sEntityHandle; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "BaseName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = m_strDwgName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataName"; m_pExtendTable->FindField(bsStr, &lFieldIndex); sAppName.MakeUpper(); vtVal = sAppName; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); bsStr = "XDataValue"; m_pExtendTable->FindField(bsStr, &lFieldIndex); vtVal = sAllValues; m_pExtentTableRowBuffer->put_Value(lFieldIndex, vtVal); hr = m_pExtentTableRowCursor->InsertRow(m_pExtentTableRowBuffer, &m_TableId); if (FAILED(hr)) { WriteLog("À©Õ¹ÊôÐÔ¶Áȡʧ°Ü:" + CatchErrorInfo()); } } m_pExtentTableRowCursor->Flush(); vtVal.Clear(); bsStr.Empty(); pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); } /******************************************************************** ¼òÒªÃèÊö : ÖØÃüÃûͼ²ãÃû£¬Õë¶Ô¼ÃÄÏÏîÄ¿µãºÍÏßÔÚͬÒÔͼ²ãÏ£¬·ÖÀë³öÏßÒªËØµ½Ö¸¶¨Í¼²ãÏ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ /*void XDWGReader::RenameEntityLayerName(CString sDwgOriLayerName, IFeatureBuffer*& pFeatBuffer) { if (m_lstRenameLayers.GetCount() <= 0) { return; } //ÖØÐÂÖ¸¶¨Í¼²ã£¬°ÑÏß²ã·Åµ½ÏàÓ¦µÄ¸¨ÖúÏßͼ²ãÖÐÈ¥ POSITION pos = m_lstRenameLayers.GetHeadPosition(); while (pos != NULL) { RenameLayerRecord* pRenameRec = m_lstRenameLayers.GetNext(pos); if (pRenameRec->sDWG_LAYERNAME_CONTAINS.IsEmpty()||pRenameRec->sNEW_DWG_LAYERNAME.IsEmpty()||pRenameRec->sNEW_LAYERTYPE.IsEmpty()) { continue; } if (pRenameRec->sNEW_LAYERTYPE.CompareNoCase("Line") == 0) { CStringList lstKeys; CString sKeyStr; CString sLayerNameContains = pRenameRec->sDWG_LAYERNAME_CONTAINS; int iPos = sLayerNameContains.Find(','); while (iPos != -1) { sKeyStr = sLayerNameContains.Mid(0, iPos); sLayerNameContains = sLayerNameContains.Mid(iPos + 1); iPos = sLayerNameContains.Find(','); lstKeys.AddTail(sKeyStr); } sKeyStr = sLayerNameContains; lstKeys.AddTail(sKeyStr); bool bFindKey = true; for (int ki=0; ki< lstKeys.GetCount(); ki++) { sKeyStr = lstKeys.GetAt(lstKeys.FindIndex(ki)); if (sDwgOriLayerName.Find(sKeyStr) == -1) { bFindKey = false; break; } } //Èç¹û°üº¬ËùÓÐÌØÕ÷Öµ£¬Ôò¸üÃû if (bFindKey) { AddAttributes("Layer", pRenameRec->sNEW_DWG_LAYERNAME, pFeatBuffer); break; } } } } */ /******************************************************************** ¼òÒªÃèÊö : ²åÈë×¢¼ÇÒªËØ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InsertAnnoFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (sEntType.Compare("AcDbMText") == 0 || sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; //¶ÔÆëµã OdGePoint3d alignPoint; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; if (sEntType.Compare("AcDbMText") == 0) { OdDbMTextPtr pMText = OdDbMTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pMText->contents(); int iPos = sText.ReverseFind(';'); sText = sText.Mid(iPos + 1); sText.Replace("{", ""); sText.Replace("}", ""); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pMText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß¶È sHeight.Format("%f", pMText->textHeight()); //¸ß³ÌÖµ sElevation.Format("%f", pMText->location().z); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pMText->rotation(); //¸ßºÍ¿í dHeight = pMText->textHeight(); dWeight = pMText->width(); //λÖõã textPos = pMText->location(); //ÉèÖÃ¶ÔÆë·½Ê½ if (pMText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pMText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pMText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pMText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pMText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pMText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pMText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pMText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } else if (sEntType.Compare("AcDbText") == 0 || sEntType.Compare("AcDbAttribute") == 0) { OdDbTextPtr pText = OdDbTextPtr(pEnt); //Îı¾ÄÚÈÝ sText = pText->textString(); //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->position(); alignPoint = pText->alignmentPoint(); //if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã //{ // textPos = pText->position(); //} CString tempstr; tempstr.Format("%f", alignPoint.x); AddAttributes("AlignPtX", tempstr, m_pAnnoFeatureBuffer); tempstr.Format("%f", alignPoint.y); AddAttributes("AlignPtY", tempstr, m_pAnnoFeatureBuffer); //OdGePoint3dArray boundingPoints; //pText->getBoundingPoints(boundingPoints); //OdGePoint3d topLeft = boundingPoints[0]; //OdGePoint3d topRight = boundingPoints[1]; //OdGePoint3d bottomLeft = boundingPoints[2]; //OdGePoint3d bottomRight = boundingPoints[3]; //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ²åÈëCADÊôÐÔ¶ÔÏó //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::InsertDwgAttribFeature(OdRxObject* pEnt) { HRESULT hr; OdDbEntityPtr pOdDbEnt = pEnt; if (pOdDbEnt.isNull()) return; CString sEntType = pOdDbEnt->isA()->name(); if (strcmp(sEntType, "AcDbAttributeDefinition") == 0) { // Ìí¼ÓÊôÐÔ AddBaseAttributes(pOdDbEnt, "Annotation", m_pAnnoFeatureBuffer); //CString sTempVal; CString sText = ""; double dHeight = 0; double dWeight = 0; double dAngle = 0; OdGePoint3d textPos; esriTextHorizontalAlignment horizAlign = esriTHALeft; esriTextVerticalAlignment vertAlign = esriTVABaseline; CString sTextStyle = "STANDARD"; CString sHeight = "0"; CString sElevation = "0"; CString sThickness = "0"; CString sOblique = "0"; OdDbAttributeDefinitionPtr pText = OdDbAttributeDefinitionPtr(pEnt); //Îı¾ÄÚÈÝ CString sTag = pText->tag(); CString sPrompt = pText->prompt(); sText = sTag; //Îı¾·ç¸ñ OdDbSymbolTableRecordPtr symbolbRec = OdDbSymbolTableRecordPtr(pText->textStyle().safeOpenObject()); if (!symbolbRec.isNull()) { sTextStyle.Format("%s", symbolbRec->getName()); } //¸ß³ÌÖµ sElevation.Format("%f", pText->position().z); //¸ß¶È sHeight.Format("%f", pText->height()); //ºñ¶È sThickness.Format("%.f", pText->thickness()); //Çã½Ç sOblique.Format("%f", pText->oblique()); ////Éú³É×¢¼ÇÐèÒªµÄ²ÎÊý//// //½Ç¶È dAngle = pText->rotation(); dHeight = pText->height(); dWeight = 0; textPos = pText->alignmentPoint(); if (textPos.x <= 0.0001 && textPos.y <= 0.0001) //Èç¹ûûÓÐ¶ÔÆëµã£¬ÔòʹÓÃλÖõã { textPos = pText->position(); } //ÉèÖÃ¶ÔÆë·½Ê½ if (pText->horizontalMode() == OdDb::kTextLeft) { horizAlign = esriTHALeft; } else if (pText->horizontalMode() == OdDb::kTextCenter) { horizAlign = esriTHACenter; } else if (pText->horizontalMode() == OdDb::kTextRight) { horizAlign = esriTHARight; } else if (pText->horizontalMode() == OdDb::kTextFit) { horizAlign = esriTHAFull; } if (pText->verticalMode() == OdDb::kTextBase) { vertAlign = esriTVABaseline; } else if (pText->verticalMode() == OdDb::kTextBottom) { vertAlign = esriTVABottom; } else if (pText->verticalMode() == OdDb::kTextTop) { vertAlign = esriTVATop; } else if (pText->verticalMode() == OdDb::kTextVertMid) { vertAlign = esriTVACenter; } //ÉèÖÃ×¢¼ÇÎı¾·ç¸ñ AddAttributes("TextStyle", sTextStyle, m_pAnnoFeatureBuffer); AddAttributes("Height", sHeight, m_pAnnoFeatureBuffer); AddAttributes("Elevation", sElevation, m_pAnnoFeatureBuffer); AddAttributes("Thickness", sThickness, m_pAnnoFeatureBuffer); AddAttributes("Oblique", sOblique, m_pAnnoFeatureBuffer); //´´½¨ Element ITextElementPtr pTextElement = MakeTextElementByStyle(sText, dAngle, dHeight, textPos.x, textPos.y, m_dAnnoScale, horizAlign, vertAlign); IElementPtr pElement = pTextElement; IAnnotationFeaturePtr pTarAnnoFeat = m_pAnnoFeatureBuffer; hr = pTarAnnoFeat->put_Annotation(pElement); PutExtendAttribsValue(m_pAnnoFeatureBuffer, OdDbEntityPtr(pEnt)->xData()); CComVariant OID; hr = m_pAnnoFeatureCursor->InsertFeature(m_pAnnoFeatureBuffer, &OID); if (FAILED(hr)) { CString sInfoText; sInfoText = "Annotation¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } /******************************************************************** ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔÖµ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ BOOL XDWGReader::PutExtendAttribsValue(IFeatureBuffer*& pFtBuf, OdResBuf* xIter) { if (m_IsJoinXDataAttrs == FALSE || m_Regapps.GetCount() <= 0 || xIter == NULL) { return FALSE; } CMapStringToPtr mapExtraRes; //±£´æËùÓÐÓ¦Óü°À©Õ¹ÊôÐÔ (Ó¦ÓÃÃû+CStringList*) //Registered Application Name CString sAppName; CString sExtendValue; //CStringList lstExtendValues;//ËùÓÐÀ©Õ¹ÊôÐÔ,ÓÃ,ºÅ·Ö¸ô OdResBuf* xIterLoop = xIter; for (; xIterLoop != 0; xIterLoop = xIterLoop->next()) { int code = xIterLoop->restype(); switch (OdDxfCode::_getType(code)) { case OdDxfCode::Name: case OdDxfCode::String: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::Bool: sExtendValue.Format("%d", xIterLoop->getBool()); break; case OdDxfCode::Integer8: sExtendValue.Format("%d", xIterLoop->getInt8()); break; case OdDxfCode::Integer16: sExtendValue.Format("%d", xIterLoop->getInt16()); break; case OdDxfCode::Integer32: sExtendValue.Format("%d", xIterLoop->getInt32()); break; case OdDxfCode::Double: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Angle: sExtendValue.Format("%f", xIterLoop->getDouble()); break; case OdDxfCode::Point: { OdGePoint3d p = xIterLoop->getPoint3d(); sExtendValue.Format("%f,%f,%f", p.x, p.y, p.z); } break; case OdDxfCode::BinaryChunk: sExtendValue = "<Binary Data>"; break; case OdDxfCode::Handle: case OdDxfCode::LayerName: sExtendValue.Format("%s", xIterLoop->getString().c_str()); break; case OdDxfCode::ObjectId: case OdDxfCode::SoftPointerId: case OdDxfCode::HardPointerId: case OdDxfCode::SoftOwnershipId: case OdDxfCode::HardOwnershipId: { OdDbHandle h = xIterLoop->getHandle(); sExtendValue.Format("%s", h.ascii()); } break; case OdDxfCode::Unknown: default: sExtendValue = "Unknown"; break; } //Registered Application Name if (code == OdResBuf::kDxfRegAppName) { sAppName = sExtendValue; //Éú³É¶ÔÓ¦ÓÚ¸ÃÓ¦ÓõÄStringList CStringList* pLstExtra = new CStringList(); mapExtraRes.SetAt(sAppName, pLstExtra); } else if (code == OdResBuf::kDxfXdAsciiString || code == OdResBuf::kDxfXdReal) { void* rValue; if (mapExtraRes.Lookup(sAppName, rValue)) { CStringList* pLstExtra = (CStringList*) rValue; //±£´æµ½¶ÔÓ¦ÓÚ¸ÃAPPNameµÄListÖÐ pLstExtra->AddTail(sExtendValue); } } } //µÃµ½×Ö¶Î IFieldsPtr pFields; pFtBuf->get_Fields(&pFields); POSITION mapPos = mapExtraRes.GetStartPosition(); while (mapPos) { CString sAppName; void* rValue; mapExtraRes.GetNextAssoc(mapPos, sAppName, rValue); CStringList* pList = (CStringList*) rValue; long lIdx = 0; pFields->FindField(CComBSTR(sAppName), &lIdx); if (lIdx != -1) { CString sAllValues = ""; //Éú³ÉÀ©Õ¹ÊôÐÔ×Ö·û´® POSITION pos = pList->GetHeadPosition(); if (pos != NULL) { sAllValues = pList->GetNext(pos); while (pos != NULL) { sAllValues = sAllValues + "," + pList->GetNext(pos) ; } pFtBuf->put_Value(lIdx, CComVariant(sAllValues)); } } pList->RemoveAll(); delete pList; } mapExtraRes.RemoveAll(); return TRUE; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ¶ÁCADµÄÿ¸öʵÌåÒªËØ //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// void XDWGReader::ReadEntity(OdDbObjectId id) { OdDbEntityPtr pEnt = id.safeOpenObject(); OdDbLayerTableRecordPtr pLayerTableRecord = pEnt->layerId().safeOpenObject(); CString sInfoText; if ((pLayerTableRecord->isOff() || pLayerTableRecord->isLocked() || pLayerTableRecord->isFrozen()) && (m_IsReadInvisible == FALSE)) { //±ÜÃâÈÕÖ¾ÖØ¸´ÄÚÈÝ CString sUnReadLayer = pEnt->layer().c_str(); POSITION pos = m_UnReadLayers.Find(sUnReadLayer); if (pos == NULL) { m_UnReadLayers.AddTail(sUnReadLayer); sInfoText.Format("<%s>²ãÒªËØ²»¿ÉÊÓ²»´¦Àí!", sUnReadLayer); WriteLog(sInfoText); } m_lUnReadEntityNum++; } else { OdDbHandle hTmp; char szEntityHandle[50] = {0}; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(szEntityHandle); //¼Ç¼µ±Ç°handleÖµ m_sEntityHandle = szEntityHandle; //Çå¿ÕFeatureBuffer CleanAllFeatureBuffers(); OdSmartPtr<OdDbEntity_Dumper> pEntDumper = pEnt; IGeometryPtr pShape; HRESULT hr; CComVariant OID; pEntDumper->m_DwgReader = this; // »ñµÃ¼¸ºÎÊý¾Ý pShape = pEntDumper->dump(pEnt); if (pShape == NULL) { m_lUnReadEntityNum++; return ; } //ÐÞÕý¿Õ¼ä²Î¿¼ hr = pShape->Project(m_pSpRef); // Îı¾ CString sEntType = OdDbEntityPtr(pEnt)->isA()->name(); if ((strcmp(sEntType, "AcDbMText") == 0) || (strcmp(sEntType, "AcDbText") == 0) || (strcmp(sEntType, "AcDbShape") == 0)) { if (m_IsCreateAnnotation) { //²åÈë×¢¼Ç¶ÔÏó InsertAnnoFeature(pEnt); } else { hr = m_pTextFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Annotation", m_pTextFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pTextFeatureBuffer)) { PutExtendAttribsValue(m_pTextFeatureBuffer, pEnt->xData()); hr = m_pTextFeatureCursor->InsertFeature(m_pTextFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Text¶ÔÏóдÈëµ½PGDBʧ°Ü¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Text¶ÔÏó×ø±ê²»ÕýÈ·¡£" + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { esriGeometryType shapeType; pShape->get_GeometryType(&shapeType); if (shapeType == esriGeometryPoint) //µã { hr = m_pPointFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Point", m_pPointFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPointFeatureBuffer)) { PutExtendAttribsValue(m_pPointFeatureBuffer, pEnt->xData()); hr = m_pPointFeatureCursor->InsertFeature(m_pPointFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Point¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Point¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } if (strcmp(pEnt->isA()->name(), "AcDbBlockReference") == 0) m_lBlockNum++; } else if (shapeType == esriGeometryPolyline) //Ïß { hr = m_pLineFeatureBuffer->putref_Shape(pShape); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Line", m_pLineFeatureBuffer); CString sDwgLayer; sDwgLayer.Format("%s", pEnt->layer().c_str()); if (CompareCodes(m_pLineFeatureBuffer)) { PutExtendAttribsValue(m_pLineFeatureBuffer, pEnt->xData()); hr = m_pLineFeatureCursor->InsertFeature(m_pLineFeatureBuffer, &OID); if (FAILED(hr)) { IFieldsPtr pFlds; m_pLineFeatureBuffer->get_Fields(&pFlds); long numFields; pFlds->get_FieldCount(&numFields); for (int t = 0; t < numFields; t++) { CComVariant tVal; IFieldPtr pFld; pFlds->get_Field(t, &pFld); CComBSTR bsName; pFld->get_Name(&bsName); m_pLineFeatureBuffer->get_Value(t, &tVal); } sInfoText = "Line¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText = "Line¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } // Èç¹û±ÕºÏ¾ÍÔÙÉú³ÉÃæ VARIANT_BOOL isclosed; IPolylinePtr pPolyline(CLSID_Polyline); pPolyline = pShape; pPolyline->get_IsClosed(&isclosed); if (isclosed && m_IsLine2Polygon) { IPolygonPtr pPolygon(CLSID_Polygon); ((ISegmentCollectionPtr) pPolygon)->AddSegmentCollection((ISegmentCollectionPtr) pPolyline); IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); //±àÂë¶ÔÕÕ if (CompareCodes(m_pPolygonFeatureBuffer)) { //¹Ò½ÓÀ©Õ¹ÊôÐÔ PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); } } } else { sInfoText = "Polyline¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); } } } else if (shapeType == esriGeometryPolygon) //Ãæ¡¢Ìî³ä { if(m_IsReadPolygon) { IPolygonPtr pPolygon(CLSID_Polygon); pPolygon = pShape; IAreaPtr pArea = (IAreaPtr)pPolygon; double dArea = 0.0; pArea->get_Area(&dArea); if (dArea < 0.0) { pPolygon->ReverseOrientation(); } hr = m_pPolygonFeatureBuffer->putref_Shape((IGeometryPtr)pPolygon); if (SUCCEEDED(hr)) { AddBaseAttributes(pEnt, "Polygon", m_pPolygonFeatureBuffer); PutExtendAttribsValue(m_pPolygonFeatureBuffer, pEnt->xData()); hr = m_pPolygonFeatureCursor->InsertFeature(m_pPolygonFeatureBuffer, &OID); if (FAILED(hr)) { sInfoText = "Polygon¶ÔÏóдÈëµ½PGDBʧ°Ü." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } else { sInfoText = "Polygon¶ÔÏó×ø±ê²»ÕýÈ·." + CatchErrorInfo(); WriteLog(sInfoText); m_lUnReadEntityNum++; } } } else { sInfoText.Format("%sͼ²ãÖÐHandleֵΪ:%s µÄÒªËØÎÞ·¨´¦Àí.", pEnt->layer().c_str(), szEntityHandle); WriteLog(sInfoText); //ÎÞ·¨Ê¶±ð¼ÆÊý¼Ó1 m_lUnReadEntityNum++; } } //¶ÁÈ¡À©Õ¹ÊôÐÔµ½À©Õ¹ÊôÐÔ±í ReadExtendAttribs(pEnt->xData(), szEntityHandle); } } //¶ÁCADÎļþ void XDWGReader::ReadBlock(OdDbDatabase* pDb) { // Open ModelSpace OdDbBlockTableRecordPtr pBlock = pDb->getModelSpaceId().safeOpenObject(); // ³õʼ»¯ m_lBlockNum = 0; m_bn = -1; m_lEntityNum = 0; //ÎÞ·¨¶ÁÈ¡µÄʵÌå¸öÊý m_lUnReadEntityNum = 0; m_vID = 0; if (m_StepNum < 0) m_StepNum = 5000; // Get an entity iterator OdDbObjectIteratorPtr pEntIter = pBlock->newIterator(); for (; !pEntIter->done(); pEntIter->step()) { m_lEntityNum++; } //É趨½ø¶ÈÌõ·¶Î§ if (m_pProgressBar) { m_pProgressBar->SetRange(0, m_lEntityNum); m_pProgressBar->SetPos(0); } pEntIter.release(); // For each entity in the block pEntIter = pBlock->newIterator(); int iReadCount = 0; for (; !pEntIter->done(); pEntIter->step()) { try { ReadEntity(pEntIter->objectId()); } catch (...) { char szEntityHandle[50] = {0}; pEntIter->objectId().getHandle().getIntoAsciiBuffer(szEntityHandle); CString sErr; sErr.Format("¶ÁÈ¡HandleΪ%sµÄʵÌå³öÏÖÒì³£.", szEntityHandle); WriteLog(sErr); } //É趨½ø¶ÈÌõ²½³¤ if (m_pProgressBar) { m_pProgressBar->StepIt(); } if (++iReadCount % m_StepNum == 0) { if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); } } if (m_pPointFeatureCursor) m_pPointFeatureCursor->Flush(); if (m_pTextFeatureCursor) m_pTextFeatureCursor->Flush(); if (m_pLineFeatureCursor) m_pLineFeatureCursor->Flush(); if (m_pAnnoFeatureCursor) m_pAnnoFeatureCursor->Flush(); if (m_pPolygonFeatureCursor) m_pPolygonFeatureCursor->Flush(); if (m_pExtentTableRowCursor) m_pExtentTableRowCursor->Flush(); pEntIter.release(); CString sResult; sResult.Format("´¦ÀíÒªËØ×ÜÊý:%d", m_lEntityNum - m_lUnReadEntityNum); WriteLog(sResult); } // arcgis Ïà¹Øº¯Êý HRESULT XDWGReader::AddBaseAttributes(OdDbEntity* pEnt, LPCTSTR strEnType, IFeatureBuffer*& pFeatureBuffer) { long lindex; int ival ; CString strval; IFieldsPtr ipFields; char buff[20]; OdDbHandle hTmp; hTmp = pEnt->getDbHandle(); hTmp.getIntoAsciiBuffer(buff); if (pFeatureBuffer == NULL) return S_FALSE; pFeatureBuffer->get_Fields(&ipFields); //µÃµ½esri¼¸ºÎÀàÐÍ CComBSTR bsStr; CComVariant vtVal; bsStr = g_szEntityType; ipFields->FindField(bsStr, &lindex); vtVal = strEnType; pFeatureBuffer->put_Value(lindex, vtVal); //µÃµ½dwg¼¸ºÎÀàÐÍ bsStr = "DwgGeometry"; ipFields->FindField(bsStr, &lindex); vtVal = pEnt->isA()->name(); pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgʵÌå±àºÅ bsStr = "Handle"; ipFields->FindField(bsStr, &lindex); vtVal = buff; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwgͼÃû£¬¼´dwgÎļþÃû¡£ÒÔÈ·±£handleΨһ bsStr = "BaseName"; ipFields->FindField(bsStr, &lindex); vtVal = m_strDwgName; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½dwg²ãÃû bsStr = "Layer"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->layer().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); // TRACE("Put Layer(AddBaseAttributes): "+ strval+" \r\n"); // µÃµ½dwg·ûºÅÑÕÉ«,Ö»Äܵõ½²ãµÄÑÕÉ«£¬Ó¦¸ÃÊÇÿ¸öÒªËØµÄ bsStr = "Color"; ipFields->FindField(bsStr, &lindex); if (pEnt->colorIndex() > 255 || pEnt->colorIndex() < 1) { OdDbLayerTableRecordPtr pLayer = pEnt->layerId().safeOpenObject(); ival = pLayer->colorIndex(); } else ival = pEnt->colorIndex(); vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); // µÃµ½ Linetype £¬¼Ç¼ÏßÐÍ bsStr = "Linetype"; ipFields->FindField(bsStr, &lindex); strval.Format("%s", pEnt->linetype().c_str()); strval.MakeUpper(); vtVal = strval; pFeatureBuffer->put_Value(lindex, vtVal); //¶ÔÏó¿É¼ûÐÔ£¨¿ÉÑ¡£©£º0 = ¿É¼û£»1 = ²»¿É¼û // kInvisible 1 kVisible 0 bsStr = "Visible"; ipFields->FindField(bsStr, &lindex); if (pEnt->visibility() == 1) { ival = 0; } else { ival = 1; } vtVal = ival; pFeatureBuffer->put_Value(lindex, vtVal); //À©Õ¹ÊôÐÔFeatureUID //bsStr = "FEATURE_UID"; //ipFields->FindField(bsStr, &lindex); //if (lindex != -1) //{ // CString sFeatureUID = ReadFeatureUID(pEnt->xData()); // vtVal = sFeatureUID; // pFeatureBuffer->put_Value(lindex, vtVal); //} vtVal.Clear(); bsStr.Empty(); return 0; } void XDWGReader::AddAttributes(LPCTSTR csFieldName, LPCTSTR csFieldValue, IFeatureBuffer*& pFeatureBuffer) { try { long lindex; IFieldsPtr ipFields; CString strval; if (pFeatureBuffer == NULL) return; pFeatureBuffer->get_Fields(&ipFields); CComBSTR bsStr = csFieldName; ipFields->FindField(bsStr, &lindex); if (lindex != -1) { CComVariant vtVal; //°Ñ»¡¶Èֵת»»Îª½Ç¶ÈÖµ if (m_bConvertAngle && (strcmp("Angle", csFieldName) == 0)) { double dRadian = atof(csFieldValue); double dAngle = dRadian * g_dAngleParam; vtVal = dAngle; } else { vtVal = csFieldValue; } HRESULT hr = pFeatureBuffer->put_Value(lindex, vtVal); vtVal.Clear(); } bsStr.Empty(); } catch (...) { CString sError; sError.Format("%s×Ö¶ÎдÈë%sֵʱ³ö´í.", csFieldName, csFieldValue); WriteLog(sError); } } void XDWGReader::CleanAllFeatureBuffers() { if (m_pAnnoFeatureBuffer) CleanFeatureBuffer(m_pAnnoFeatureBuffer); if (m_pTextFeatureBuffer) CleanFeatureBuffer(m_pTextFeatureBuffer); if (m_pLineFeatureBuffer) CleanFeatureBuffer(m_pLineFeatureBuffer); if (m_pPointFeatureBuffer) CleanFeatureBuffer(m_pPointFeatureBuffer); if (m_pPolygonFeatureBuffer) CleanFeatureBuffer(m_pPolygonFeatureBuffer); } //void XDWGReader::BlockIniAttributes() //{ // if (m_pTextFeatureBuffer) // IniBlockAttributes(m_pTextFeatureBuffer); // if (m_pLineFeatureBuffer) // IniBlockAttributes(m_pLineFeatureBuffer); // if (m_pPointFeatureBuffer) // IniBlockAttributes(m_pPointFeatureBuffer); // if (m_pPolygonFeatureBuffer) // IniBlockAttributes(m_pPolygonFeatureBuffer); //} ////////////////////////////////////////////////////////////////////////// //ÕÒ³ö²¢½â¾öÄÚ´æÐ¹Â©ÎÊÌâ by zl void XDWGReader::CleanFeatureBuffer(IFeatureBuffer* pFeatureBuffer) { if (pFeatureBuffer == NULL) return; //ÊÍ·ÅÄÚ´æ IGeometryPtr pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } IFieldsPtr ipFields; long iFieldCount; VARIANT_BOOL isEditable; esriFieldType fieldType; VARIANT emptyVal; ::VariantInit(&emptyVal); CComVariant emptyStr = ""; pFeatureBuffer->get_Fields(&ipFields); ipFields->get_FieldCount(&iFieldCount); for (int i = 0; i < iFieldCount; i++) { IFieldPtr pFld; ipFields->get_Field(i, &pFld); pFld->get_Editable(&isEditable); pFld->get_Type(&fieldType); if (isEditable == VARIANT_TRUE && fieldType != esriFieldTypeGeometry) { if (fieldType == esriFieldTypeString) { pFeatureBuffer->put_Value(i, emptyStr); } else { pFeatureBuffer->put_Value(i, emptyVal); } } } } //void XDWGReader::IniBlockAttributes(IFeatureBuffer* pFeatureBuffer) //{ // long lindex; // // double dbval; // CString strval; // IFieldsPtr ipFields; // if (pFeatureBuffer == NULL) // return; // // //ÊÍ·ÅÄÚ´æ // IGeometry* pShape; // HRESULT hr = pFeatureBuffer->get_Shape(&pShape); // if (SUCCEEDED(hr)) // { // if (pShape != NULL) // { // pShape->SetEmpty(); // } // } // // // Çå¿Õ£¬·ñÔò»á±£Áôǰһ¸öµÄÊôÐÔ // pFeatureBuffer->get_Fields(&ipFields); // CComBSTR bsStr; // CComVariant vtVal; // bsStr = "Thickness"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Scale"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Angle"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Elevation"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr = "Width"; // ipFields->FindField(bsStr, &lindex); // if (lindex != -1) // { // vtVal = 0; // pFeatureBuffer->put_Value(lindex, vtVal); // } // // bsStr.Empty(); // // //IniExtraAttributes(pFeatureBuffer, ipFields); // // return; //} //void XDWGReader::OpenLogFile() //{ // //if (m_pLogRec != NULL) // //{ // // WinExec("Notepad.exe " + m_sLogFilePath, SW_SHOW); // //} // // //if (m_LogList.GetCount() > 0) // //{ // // COleDateTime dtCur = COleDateTime::GetCurrentTime(); // // CString sName = dtCur.Format("%y%m%d_%H%M%S"); // // CString sLogFileName; // // sLogFileName.Format("%sDwgת»»ÈÕÖ¾_%s.log", GetLogPath(), sName); // // // CStdioFile f3(sLogFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeText); // // for (POSITION pos = m_LogList.GetHeadPosition(); pos != NULL;) // // { // // f3.WriteString(m_LogList.GetNext(pos) + "\n"); // // } // // f3.Close(); // // WinExec("Notepad.exe " + sLogFileName, SW_SHOW); // // m_LogList.RemoveAll(); // //} //} CString XDWGReader::CatchErrorInfo() { IErrorInfoPtr ipError; CComBSTR bsStr; CString sError; ::GetErrorInfo(0, &ipError); if (ipError) { ipError->GetDescription(&bsStr); sError = bsStr; } CString sRetErr; sRetErr.Format("¶ÁÈ¡HandleֵΪ:%s µÄ¶ÔÏóʱ³ö´í.´íÎóÔ­Òò:%s", m_sEntityHandle, sError); return sRetErr; } HRESULT XDWGReader::CreateDwgPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼ÏßÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Scale £¬¼Ç¼DWGʵÌå·ûºÅ±ÈÀý´óС ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Scale")); ipFieldEdit->put_AliasName(CComBSTR(L"Scale")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgLineFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolyline); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgPolygonFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit; ipGeomDefEdit = ipGeomDef; // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPolygon); ipGeomDefEdit->put_GridCount(1); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); //ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Width £¬¼Ç¼DWGʵÌåÏß¿í ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Width")); ipFieldEdit->put_AliasName(CComBSTR(L"Width")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } HRESULT XDWGReader::CreateDwgTextPointFields(ISpatialReference* ipSRef, IFields** ppfields) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField; ipField.CreateInstance(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); // create the geometry field IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); // assign the geometry definiton properties. ipGeomDefEdit->put_GeometryType(esriGeometryPoint); ipGeomDefEdit->put_GridCount(1); //double dGridSize = 1000; //VARIANT_BOOL bhasXY; //ipSRef->HasXYPrecision(&bhasXY); //if (bhasXY) //{ // double xmin, ymin, xmax, ymax, dArea; // ipSRef->GetDomain(&xmin, &xmax, &ymin, &ymax); // dArea = (xmax - xmin) * (ymax - ymin); // dGridSize = sqrt(dArea / 100); //} //if (dGridSize <= 0) // dGridSize = 1000; ipGeomDefEdit->put_GridSize(0, DEFAULT_GIS_GRID_SIZE); ipGeomDefEdit->put_AvgNumPoints(2); ipGeomDefEdit->put_HasM(VARIANT_FALSE); ipGeomDefEdit->put_HasZ(VARIANT_FALSE); ipGeomDefEdit->putref_SpatialReference(ipSRef); ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_AliasName(CComBSTR(L"SHAPE")); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldsEdit->AddField(ipField); // create the object id field ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECT ID")); ipFieldEdit->put_Type(esriFieldTypeOID); ipFieldsEdit->AddField(ipField); // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(g_szEntityType)); ipFieldEdit->put_AliasName(CComBSTR(g_szEntityType)); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ DwgGeometry £¬¼Ç¼DWGʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_AliasName(CComBSTR(L"DwgGeometry")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGÏßʵÌåÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Linetype £¬¼Ç¼DWGÏßʵÌåÏßÐÍÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Linetype")); ipFieldEdit->put_AliasName(CComBSTR(L"Linetype")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blockname £¬¼Ç¼BlockÃû×Ö ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blockname")); ipFieldEdit->put_AliasName(CComBSTR(L"Blockname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Blocknumber £¬¼Ç¼ÿ¸öBlock±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Blocknumber")); ipFieldEdit->put_AliasName(CComBSTR(L"Blocknumber")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Angle £¬¼Ç¼DWGÎÄ×ÖʵÌåÐýת½Ç¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Angle")); ipFieldEdit->put_AliasName(CComBSTR(L"Angle")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextString £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÄÚÈÝ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextString")); ipFieldEdit->put_AliasName(CComBSTR(L"TextString")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(255); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¸ß ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ WidthFactor £¬ // is an additional scaling applied in the x direction which makes the text either fatter or thinner. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"WidthFactor")); ipFieldEdit->put_AliasName(CComBSTR(L"WidthFactor")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬Çãб½Ç¶È // is an obliquing angle to be applied to the text, which causes it to "lean" either to the right or left. ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ VerticalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ // kTextBase 0 kTextBottom 1 kTextVertMid 2 kTextTop 3 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"VtMode")); ipFieldEdit->put_AliasName(CComBSTR(L"VtMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ HorizontalMode £¬¼Ç¼DWGÎÄ×ÖʵÌå×Ö¶ÔÆë·½Ê½ //kTextLeft 0 kTextCenter 1 kTextRight 2 kTextAlign 3 // kTextMid 4 kTextFit 5 ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"HzMode")); ipFieldEdit->put_AliasName(CComBSTR(L"HzMode")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMinY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMinY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMinY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxX")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BoundingPointMaxY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"PtMaxY")); ipFieldEdit->put_AliasName(CComBSTR(L"PtMaxY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ BigFontname £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BigFontname")); ipFieldEdit->put_AliasName(CComBSTR(L"BigFontname")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeFilename £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeFilename")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ ShapeName £¬¼Ç¼ DWGÎÄ×ÖʵÌå×ÖÌå ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"ShapeName")); ipFieldEdit->put_AliasName(CComBSTR(L"ShapeName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Visible £¬¼Ç¼DWGʵÌåÊÇ·ñ¿É¼û£¬0²»¿É¼û£¬1¿É¼û ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Visible")); ipFieldEdit->put_AliasName(CComBSTR(L"Visible")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); *ppfields = ipFields.Detach(); return 0; } ////////////////////////////////////////////////////////////////////////// //¼òÒªÃèÊö : ´´½¨×¢¼Çͼ²ã×Ö¶Î //ÊäÈë²ÎÊý : //·µ »Ø Öµ : //ÐÞ¸ÄÈÕÖ¾ : ////////////////////////////////////////////////////////////////////////// HRESULT XDWGReader::CreateDwgAnnotationFields(ISpatialReference* ipSRef, IFields** ppfields) { HRESULT hr; IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (ipSRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(ipSRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointX ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtX")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtX")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ AlignmentPointY ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"AlignPtY")); ipFieldEdit->put_AliasName(CComBSTR(L"AlignPtY")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); *ppfields = ipFieldsEdit.Detach(); return 0; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨À©Õ¹ÊôÐÔ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ HRESULT XDWGReader::CreateExtendTable(IFeatureWorkspace* pFeatWorkspace, BSTR bstrName, ITable** pTable) { HRESULT hr; if (pFeatWorkspace == NULL) return E_FAIL; // Ö»´´½¨£ºBaseName--ͼÃû£»Handle--ÒªËØID;XDataName--À©Õ¹ÊôÐÔÃû³Æ;XDataNum--À©Õ¹ÊôÐÔ±àºÅ;XDataValue--À©Õ¹ËµÃ÷Öµ hr = pFeatWorkspace->OpenTable(bstrName, pTable); // Èç¹û´ò²»¿ªtable¾ÍÈÏΪ²»´æÔÚ¾ÍÖØ½¨table if (*pTable == NULL) { IFieldsPtr ipFields; ipFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipIndexFields; ipIndexFields.CreateInstance(CLSID_Fields); IFieldsEditPtr ipFieldsEdit = ipFields; if (ipFieldsEdit == NULL) return E_FAIL; // Add a field for the user name IFieldEditPtr ipField; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"Handle")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(150); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î1 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"BaseName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipField->put_Required(VARIANT_TRUE); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; //Ìí¼ÓË÷Òý×Ö¶Î2 hr = ipIndexFields->AddField(ipField); if (FAILED(hr)) return hr; hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataName")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(250); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // 2050 Ϊ×î´óÈÝÁ¿ hr = ipField.CreateInstance(CLSID_Field); if (FAILED(hr)) return hr; hr = ipField->put_Name(CComBSTR(L"XDataValue")); if (FAILED(hr)) return hr; hr = ipField->put_Type(esriFieldTypeString); if (FAILED(hr)) return hr; hr = ipField->put_Length(65535); if (FAILED(hr)) return hr; hr = ipFieldsEdit->AddField(ipField); if (FAILED(hr)) return hr; // Try to Create the table hr = pFeatWorkspace->CreateTable(bstrName, ipFields, NULL, NULL, NULL, pTable); if (FAILED(hr)) return hr; IIndexEditPtr ipIndexEdit; ipIndexEdit.CreateInstance(CLSID_Index); ipIndexEdit->putref_Fields(ipIndexFields); hr = (*pTable)->AddIndex(ipIndexEdit); if (FAILED(hr)) return hr; } return S_OK; } HRESULT XDWGReader::CreateDatasetFeatureClass(IFeatureWorkspace* pFWorkspace, IFeatureDataset* pFDS, IFields* pFields, BSTR bstrName, esriFeatureType featType, IFeatureClass*& ppFeatureClass) { if (!pFDS && !pFWorkspace) return S_FALSE; BSTR bstrConfigWord = L""; IFieldPtr ipField; CComBSTR bstrShapeFld; esriFieldType fieldType; long lNumFields; pFields->get_FieldCount(&lNumFields); for (int i = 0; i < lNumFields; i++) { pFields->get_Field(i, &ipField); ipField->get_Type(&fieldType); if (esriFieldTypeGeometry == fieldType) { ipField->get_Name(&bstrShapeFld); break; } } HRESULT hr; if (pFDS) { hr = pFDS->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } else { // Ö±½Ó´ò¿ªFeatureClass,Èç¹û²»³É¹¦¾ÍÔÙ´´½¨ hr = pFWorkspace->OpenFeatureClass(bstrName, &ppFeatureClass); if (ppFeatureClass == NULL) hr = pFWorkspace->CreateFeatureClass(bstrName, pFields, 0, 0, featType, bstrShapeFld, 0, &ppFeatureClass); } return hr; } void XDWGReader::GetGeometryDef(IFeatureClass* pClass, IGeometryDef** pDef) { try { BSTR shapeName; pClass->get_ShapeFieldName(&shapeName); IFieldsPtr pFields; pClass->get_Fields(&pFields); long lGeomIndex; pFields->FindField(shapeName, &lGeomIndex); IFieldPtr pField; pFields->get_Field(lGeomIndex, &pField); pField->get_GeometryDef(pDef); } catch (...) { } } BOOL XDWGReader::IsResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName) { IWorkspace2Ptr iws2(pFWorkspace); VARIANT_BOOL isexist = FALSE; if (iws2) { iws2->get_NameExists(esriDTFeatureClass, CComBSTR(szFCName), &isexist); } return isexist; } void XDWGReader::ResetDomain(IFeatureWorkspace* pFWorkspace, CString szFCName, ISpatialReference* ipSRef) { IGeometryDefPtr ipGeomDef; ISpatialReferencePtr ipOldSRef; double mOldMinX, mOldMinY, mOldMaxY, mOldMaxX; double mMinX, mMinY, mMaxY, mMaxX; double mNewMinX, mNewMinY, mNewMaxY, mNewMaxX, dFX, dFY, mNewXYScale ; HRESULT hr; pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPolygon); GetGeometryDef(m_pFeatClassPolygon, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassPoint); GetGeometryDef(m_pFeatClassPoint, &ipGeomDef); pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassLine); GetGeometryDef(m_pFeatClassLine, &ipGeomDef); //pFWorkspace->OpenFeatureClass(CComBSTR(szFCName), &m_pFeatClassText); //GetGeometryDef(m_pFeatClassText, &ipGeomDef); ipGeomDef->get_SpatialReference(&ipOldSRef); ipOldSRef->GetDomain(&mOldMinX, &mOldMaxX, &mOldMinY, &mOldMaxY); ipSRef->GetDomain(&mMinX, &mMaxX, &mMinY, &mMaxY); if (mMinX < mOldMinX) mNewMinX = mMinX; else mNewMinX = mOldMinX; if (mMinY < mOldMinY) mNewMinY = mMinY; else mNewMinY = mOldMinY; if (mMaxX > mOldMaxX) mNewMaxX = mMaxX; else mNewMaxX = mOldMaxX; if (mMaxY > mOldMaxY) mNewMaxY = mMaxY; else mNewMaxY = mOldMaxY; ipOldSRef->SetDomain(mNewMinX, mNewMaxX, mNewMinY, mNewMaxY); ipOldSRef->GetFalseOriginAndUnits(&dFX, &dFY, &mNewXYScale); ipOldSRef->GetDomain(&mNewMinX, &mNewMaxX, &mNewMinY, &mNewMaxY); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); hr = ipGeomDefEdit->putref_SpatialReference(ipOldSRef); if (FAILED(hr)) { WriteLog(CatchErrorInfo()); } } // bsplineËã·¨ /********************************************************************* ²Î¿¼: n - ¿ØÖƵãÊý - 1 t - the polynomialµÈ¼¶ + 1 control - ¿ØÖƵã×ø±ê¼¯ output - Êä³öÄâºÏµã×ø±ê¼¯ num_output - Êä³öµãÊý Ìõ¼þ: n+2>t (·ñÔòÎÞÇúÏß) ¿ØÖƵã×ø±ê¼¯ºÍµãÊýÒ»Ö ·ÖÅäÊä³öµã¼¯µãÊýºÍ num_outputÒ»Ö **********************************************************************/ void XDWGReader::Bspline(int n, int t, DwgPoint* control, DwgPoint* output, int num_output) { int* u; double increment, interval; DwgPoint calcxyz; int output_index; u = new int[n + t + 1]; ComputeIntervals(u, n, t); increment = (double) (n - t + 2) / (num_output - 1); // how much parameter goes up each time interval = 0; for (output_index = 0; output_index < num_output - 1; output_index++) { ComputePoint(u, n, t, interval, control, &calcxyz); output[output_index].x = calcxyz.x; output[output_index].y = calcxyz.y; output[output_index].z = calcxyz.z; interval = interval + increment; // increment our parameter } output[num_output - 1].x = control[n].x; // put in the last DwgPoint output[num_output - 1].y = control[n].y; output[num_output - 1].z = control[n].z; delete u; } double XDWGReader::Blend(int k, int t, int* u, double v) // calculate the blending value { double value; if (t == 1) // base case for the recursion { if ((u[k] <= v) && (v < u[k + 1])) value = 1; else value = 0; } else { if ((u[k + t - 1] == u[k]) && (u[k + t] == u[k + 1])) // check for divide by zero { value = 0; } else if (u[k + t - 1] == u[k]) // if a term's denominator is zero,use just the other { value = (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } else if (u[k + t] == u[k + 1]) { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v); } else { value = (v - u[k]) / (u[k + t - 1] - u[k]) * Blend(k, t - 1, u, v) + (u[k + t] - v) / (u[k + t] - u[k + 1]) * Blend(k + 1, t - 1, u, v); } } return value; } void XDWGReader::ComputeIntervals(int* u, int n, int t) // figure out the knots { int j; for (j = 0; j <= n + t; j++) { if (j < t) u[j] = 0; else if ((t <= j) && (j <= n)) u[j] = j - t + 1; else if (j > n) u[j] = n - t + 2; // if n-t=-2 then we're screwed, everything goes to 0 } } void XDWGReader::ComputePoint(int* u, int n, int t, double v, DwgPoint* control, DwgPoint* output) { int k; double temp; // initialize the variables that will hold our outputted DwgPoint output->x = 0; output->y = 0; output->z = 0; for (k = 0; k <= n; k++) { temp = Blend(k, t, u, v); // same blend is used for each dimension coordinate output->x = output->x + (control[k]).x * temp; output->y = output->y + (control[k]).y * temp; output->z = output->z + (control[k]).z * temp; } } /************************************************************************ ¼òÒªÃèÊö : Ìí¼ÓÀ©Õ¹ÊôÐÔ×Ö¶Î ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ void XDWGReader::AddExtraFields(CStringList* pRegapps) { if (pRegapps == NULL) return; if (m_IsJoinXDataAttrs == FALSE || pRegapps->GetCount() <= 0) { return; } m_Regapps.AddTail(pRegapps); } /************************************************************************ ¼òÒªÃèÊö : ³õʼ»¯±àÂë¶ÔÕÕ±í ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::InitCompareCodes(ITable* pCompareTable) //{ //if (pCompareTable==NULL) return; // CleanCompareCodes(); // //IFeatureWorkspacePtr ipFeatureWorkspace = API_GetSysWorkspace(); // //if (ipFeatureWorkspace == NULL) // //{ // // AfxMessageBox("´ò¿ªÏµÍ³±í³ö´í£¡", MB_ICONERROR); // // return; // //} // //ITablePtr pCompareTable; // //ipFeatureWorkspace->OpenTable(CComBSTR("CAD2GDB"), &pCompareTable); // //if (pCompareTable == NULL) // //{ // // AfxMessageBox("±àÂë¶ÔÕÕ±í²»´æÔÚ£¬ÎÞ·¨½øÐбàÂë¶ÔÕÕ¡£", MB_ICONERROR); // // return; // //} // CComBSTR bsStr; // IEsriCursorPtr ipCursor; // pCompareTable->Search(NULL, VARIANT_FALSE, &ipCursor); // if (ipCursor != NULL) // { // long lFieldIndex = -1; // IEsriRowPtr ipRow; // IFieldsPtr pFields = NULL; // ipCursor->NextRow(&ipRow); // while (ipRow != NULL) // { // CComVariant vt; // XDwg2GdbRecord* pTbRow = new XDwg2GdbRecord(); // lFieldIndex = -1; // ipRow->get_Fields(&pFields); // bsStr = "DWG_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "DWG_BLOCKNAME"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->DWG_BLOCKNAME = (CString) vt.bstrVal; // } // } // bsStr = "GDB_LAYER"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->GDB_LAYER = (CString) vt.bstrVal; // } // } // bsStr = "YSDM"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSDM = (CString) vt.bstrVal; // } // } // bsStr = "YSMC"; // pFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // ipRow->get_Value(lFieldIndex, &vt); // if (vt.vt != VT_EMPTY && vt.vt != VT_NULL) // { // pTbRow->YSMC = (CString) vt.bstrVal; // } // } // ipCursor->NextRow(&ipRow); // //¼ÓÈë¶ÔÕÕÖµ // m_aryCodes.Add(pTbRow); // } // } // bsStr.Empty(); //} /************************************************************************ ¼òÒªÃèÊö : ´ÓFeatureBufferÖеõ½¸ø¶¨×Ö¶ÎÃûµÄÖµ ÊäÈë²ÎÊý : pFeatureBuffer£ºÔ´pFeatureBuffer, sFieldName£ºÐèҪȡֵµÄ×Ö¶ÎÃû ·µ »Ø Öµ : ¸Ã×Ö¶ÎÔÚFeatureBufferÖеÄÖµ ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ CString XDWGReader::GetFeatureBufferFieldValue(IFeatureBuffer*& pFeatureBuffer, CString sFieldName) { CComVariant vtFieldValue; CString sFieldValue; long lIndex; IFieldsPtr pFields; pFeatureBuffer->get_Fields(&pFields); CComBSTR bsStr = sFieldName; pFields->FindField(bsStr, &lIndex); bsStr.Empty(); if (lIndex == -1) { sFieldValue = ""; } else { pFeatureBuffer->get_Value(lIndex, &vtFieldValue); switch (vtFieldValue.vt) { case VT_EMPTY: case VT_NULL: sFieldValue = ""; break; case VT_BOOL: sFieldValue = vtFieldValue.boolVal == TRUE ? "1" : "0"; break; case VT_UI1: sFieldValue.Format("%d", vtFieldValue.bVal); break; case VT_I2: sFieldValue.Format("%d", vtFieldValue.iVal); break; case VT_I4: sFieldValue.Format("%d", vtFieldValue.lVal); break; case VT_R4: { long lVal = vtFieldValue.fltVal; sFieldValue.Format("%d", lVal); } break; case VT_R8: { long lVal = vtFieldValue.dblVal; sFieldValue.Format("%d", lVal); } break; case VT_BSTR: sFieldValue = vtFieldValue.bstrVal; break; default: sFieldValue = ""; break; } } return sFieldValue; } /************************************************************************ ¼òÒªÃèÊö : ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ //void XDWGReader::PutExtraAttributes(IFeatureBuffer*& pFeatureBuffer, XDwg2GdbRecord* pCode) //{ // HRESULT hr; // LONG lFieldIndex; // // IFieldsPtr ipFields; // pFeatureBuffer->get_Fields(&ipFields); // // // CComBSTR bsStr; // CComVariant vtVal; // // bsStr = "GDB_LAYER"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->GDB_LAYER; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSDM"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSDM; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // bsStr = "YSMC"; // ipFields->FindField(bsStr, &lFieldIndex); // if (lFieldIndex != -1) // { // vtVal = pCode->YSMC; // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // } // // //bsStr = "SymbolCode"; // //ipFields->FindField(bsStr, &lFieldIndex); // //if (lFieldIndex != -1) // //{ // // vtVal = pCode->SymbolCode; // // hr = pFeatureBuffer->put_Value(lFieldIndex, vtVal); // //} // // bsStr.Empty(); //} //supported by feature classes in ArcSDE and feature classes and tables in File Geodatabase. It improves performance of data loading. HRESULT XDWGReader::BeginLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriExclusiveSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (!bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_TRUE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } HRESULT XDWGReader::EndLoadOnlyMode(IFeatureClass*& pTargetClass) { //if (pTargetClass == NULL) //{ // return S_FALSE; //} //IFeatureClassLoadPtr pClassLoad(pTargetClass); //if (pClassLoad) //{ // ISchemaLockPtr pSchemaLock(pTargetClass); // if (pSchemaLock) // { // if (SUCCEEDED(pSchemaLock->ChangeSchemaLock(esriSharedSchemaLock))) // { // VARIANT_BOOL bLoadOnly; // pClassLoad->get_LoadOnlyMode(&bLoadOnly); // if (bLoadOnly) // return pClassLoad->put_LoadOnlyMode(VARIANT_FALSE); // else // return S_OK; // } // } //} //return S_FALSE; return S_OK; } void XDWGReader::ReleaseFeatureBuffer(IFeatureBufferPtr& pFeatureBuffer) { if (pFeatureBuffer == NULL) { return; } //ÊÍ·ÅÄÚ´æ IGeometry* pShape; HRESULT hr = pFeatureBuffer->get_Shape(&pShape); if (SUCCEEDED(hr)) { if (pShape != NULL) { pShape->SetEmpty(); } } } /************************************************************************ ¼òÒªÃèÊö : ±àÂë¶ÔÕÕ ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ BOOL XDWGReader::CompareCodes(IFeatureBuffer*& pFeatureBuffer) { return TRUE; //try //{ // if (pFeatureBuffer == NULL) // return FALSE; // int iCompareCodes = m_aryCodes.GetSize(); // if (iCompareCodes <= 0) // { // return TRUE; // } // //CString sThickness = GetFeatureBufferFieldValue(pFeatureBuffer, "Thickness"); // CString sBlockname = GetFeatureBufferFieldValue(pFeatureBuffer, "Blockname"); // CString sLayer = GetFeatureBufferFieldValue(pFeatureBuffer, "Layer"); // CString sEntityType = GetFeatureBufferFieldValue(pFeatureBuffer, g_szEntityType); // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // //Ïߣ¬Layer->DWG_LAYER // XDwg2GdbRecord* pDwg2GdbRecord = NULL; // IGeometryPtr pGeometry; // pFeatureBuffer->get_Shape(&pGeometry); // if (pGeometry == NULL) // { // return FALSE; // } // esriFeatureType featType; // IFeaturePtr pFeat; // pFeat = pFeatureBuffer; // if (pFeat != NULL) // { // pFeat->get_FeatureType(&featType); // } // else // { // featType = esriFTSimple; // } // //×¢¼Çͼ²ã // if (featType == esriFTAnnotation) // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // else if (featType == esriFTSimple) //Ò»°ãͼ²ã // { // //HRESULT hr; // CComVariant OID; // esriGeometryType shapeType; // pGeometry->get_GeometryType(&shapeType); // if (shapeType == esriGeometryPoint) // { // //µã£±Blockname->DWG_BLOCKNAME // //µã£²Layer->DWG_LAYER // if (!sBlockname.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_BLOCKNAME.CompareNoCase(sBlockname) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // else // { // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // } // return FALSE; // } // else //if(shapeType == esriGeometryPolyline) // { // //Ïߣ¬Layer->DWG_LAYER // if (!sLayer.IsEmpty()) // { // for (int i = 0; i < iCompareCodes; i++) // { // pDwg2GdbRecord = m_aryCodes.GetAt(i); // if (pDwg2GdbRecord->DWG_LAYER.CompareNoCase(sLayer) == 0) // { // PutExtraAttributes(pFeatureBuffer, pDwg2GdbRecord); // return TRUE; // } // } // } // return FALSE; // } // } //} //catch (...) //{ // CString sError; // sError.Format("±àÂëת»»³ö´í¡£"); // WriteLog(sError); // return FALSE; //} //return FALSE; } /************************************************************************ ¼òÒªÃèÊö : ´´½¨×¢¼ÇÀàÐ͵ÄÒªËØÀà ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ IFeatureClass* XDWGReader::CreateAnnoFtCls(IWorkspace* pWS, CString sAnnoName, IFields* pFields) { HRESULT hr; IFeatureWorkspaceAnnoPtr PFWSAnno = pWS; IGraphicsLayerScalePtr pGLS(CLSID_GraphicsLayerScale); pGLS->put_Units(esriMeters); pGLS->put_ReferenceScale(m_dAnnoScale); //' set up symbol collection ISymbolCollectionPtr pSymbolColl(CLSID_SymbolCollection); ITextSymbolPtr myTxtSym(CLSID_TextSymbol); //Set the font for myTxtSym IFontDispPtr myFont(CLSID_StdFont); IFontPtr pFt = myFont; pFt->put_Name(CComBSTR("Courier New")); CY cy; cy.Hi = 0; cy.Lo = 9; pFt->put_Size(cy); myTxtSym->put_Font(myFont); // Set the Color for myTxtSym to be Dark Red IRgbColorPtr myColor(CLSID_RgbColor); myColor->put_Red(150); myColor->put_Green(0); myColor->put_Blue (0); myTxtSym->put_Color(myColor); // Set other properties for myTxtSym myTxtSym->put_Angle(0); myTxtSym->put_RightToLeft(VARIANT_FALSE); myTxtSym->put_VerticalAlignment(esriTVABaseline); myTxtSym->put_HorizontalAlignment(esriTHAFull); myTxtSym->put_Size(200); //myTxtSym->put_Case(esriTCNormal); ISymbolPtr pSymbol = myTxtSym; pSymbolColl->putref_Symbol(0, pSymbol); //set up the annotation labeling properties including the expression IAnnotateLayerPropertiesPtr pAnnoProps(CLSID_LabelEngineLayerProperties); pAnnoProps->put_FeatureLinked(VARIANT_TRUE); pAnnoProps->put_AddUnplacedToGraphicsContainer(VARIANT_FALSE); pAnnoProps->put_CreateUnplacedElements(VARIANT_TRUE); pAnnoProps->put_DisplayAnnotation(VARIANT_TRUE); pAnnoProps->put_UseOutput(VARIANT_TRUE); ILabelEngineLayerPropertiesPtr pLELayerProps = pAnnoProps; IAnnotationExpressionEnginePtr aAnnoVBScriptEngine(CLSID_AnnotationVBScriptEngine); pLELayerProps->putref_ExpressionParser(aAnnoVBScriptEngine); pLELayerProps->put_Expression(CComBSTR("[DESCRIPTION]")); pLELayerProps->put_IsExpressionSimple(VARIANT_TRUE); pLELayerProps->put_Offset(0); pLELayerProps->put_SymbolID(0); pLELayerProps->putref_Symbol(myTxtSym); IAnnotateLayerTransformationPropertiesPtr pATP = pAnnoProps; double dRefScale; pGLS->get_ReferenceScale(&dRefScale); pATP->put_ReferenceScale(dRefScale); pATP->put_Units(esriMeters); pATP->put_ScaleRatio(1); IAnnotateLayerPropertiesCollectionPtr pAnnoPropsColl(CLSID_AnnotateLayerPropertiesCollection); pAnnoPropsColl->Add(pAnnoProps); //' use the AnnotationFeatureClassDescription co - class to get the list of required fields and the default name of the shape field IObjectClassDescriptionPtr pOCDesc(CLSID_AnnotationFeatureClassDescription); IFeatureClassDescriptionPtr pFDesc = pOCDesc; IUIDPtr pInstCLSID; IUIDPtr pExtCLSID; CComBSTR bsShapeFieldName; pOCDesc->get_InstanceCLSID(&pInstCLSID); pOCDesc->get_ClassExtensionCLSID(&pExtCLSID); pFDesc->get_ShapeFieldName(&bsShapeFieldName); /*IFieldsPtr pReqFields; pOCDesc->get_RequiredFields(&pReqFields); //ÉèÖÿռä²Î¿¼ if (m_pSpRef != NULL) { long numFields; pReqFields->get_FieldCount(&numFields); for (int i = 0; i < numFields; i++) { IFieldPtr pField; pReqFields->get_Field(i, &pField); esriFieldType fldType; pField->get_Type(&fldType); if (fldType == esriFieldTypeGeometry) { IFieldEditPtr pEdtField = pField; IGeometryDefPtr pGeoDef; hr = pEdtField->get_GeometryDef(&pGeoDef); IGeometryDefEditPtr pEdtGeoDef = pGeoDef; hr = pEdtGeoDef->putref_SpatialReference(m_pSpRef); hr = pEdtField->putref_GeometryDef(pGeoDef); break; } } } IFieldsEditPtr ipFieldsEdit = pReqFields; //´´½¨CADÎļþÖÐ×¢¼Çͼ²ã×Ö¶Î IFieldEditPtr ipFieldEdit; IFieldPtr ipField; // ´´½¨ Entity £¬¼Ç¼esriʵÌåÀàÐÍ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR("Entity_Type")); ipFieldEdit->put_AliasName(CComBSTR("Entity_Type")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldsEdit->AddField(ipField); // ´´½¨ Handle £¬¼Ç¼DWGʵÌå±àºÅ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Handle")); ipFieldEdit->put_AliasName(CComBSTR(L"Handle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ BaseName £¬¼Ç¼DWGʵÌå²ãÃû¼´DWGÎļþÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"BaseName")); ipFieldEdit->put_AliasName(CComBSTR(L"BaseName")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Layer £¬¼Ç¼DWGʵÌå²ãÃû ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Layer")); ipFieldEdit->put_AliasName(CComBSTR(L"Layer")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(250); ipFieldsEdit->AddField(ipField); // ´´½¨ Color £¬¼Ç¼DWGʵÌå·ûºÅÑÕÉ« ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Color")); ipFieldEdit->put_AliasName(CComBSTR(L"Color")); ipFieldEdit->put_Type(esriFieldTypeInteger); ipFieldsEdit->AddField(ipField); // ´´½¨ Thickness £¬¼Ç¼DWGʵÌåºñ¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Thickness")); ipFieldEdit->put_AliasName(CComBSTR(L"Thickness")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Elevation £¬¼Ç¼DWGʵÌå¸ß³ÌÖµ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Elevation")); ipFieldEdit->put_AliasName(CComBSTR(L"Elevation")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ Height £¬¼Ç¼¸ß¶È ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Height")); ipFieldEdit->put_AliasName(CComBSTR(L"Height")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField); // ´´½¨ TextStyle £¬¼Ç¼ÎÄ×ÖÑùʽ ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"TextStyle")); ipFieldEdit->put_AliasName(CComBSTR(L"TextStyle")); ipFieldEdit->put_Type(esriFieldTypeString); ipFieldEdit->put_Length(150); ipFieldsEdit->AddField(ipField); // ´´½¨ Oblique £¬¼Ç¼Çã½Ç ipField.CreateInstance(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"Oblique")); ipFieldEdit->put_AliasName(CComBSTR(L"Oblique")); ipFieldEdit->put_Type(esriFieldTypeDouble); ipFieldsEdit->AddField(ipField);*/ IFeatureClass* pAnnoFtCls; //' create the new class hr = PFWSAnno->CreateAnnotationClass(CComBSTR(sAnnoName), pFields, pInstCLSID, pExtCLSID, bsShapeFieldName, CComBSTR(""), NULL, 0, pAnnoPropsColl, pGLS, pSymbolColl, VARIANT_TRUE, &pAnnoFtCls); return pAnnoFtCls; } /************************************************************************ ¼òÒªÃèÊö : Éú³É×¢¼ÇElement ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : ************************************************************************/ ITextElement* XDWGReader::MakeTextElementByStyle(CString strText, double dblAngle, double dblHeight, double dblX, double dblY, double ReferenceScale, esriTextHorizontalAlignment horizAlign, esriTextVerticalAlignment vertAlign) { HRESULT hr; ITextElementPtr pTextElement; ISimpleTextSymbolPtr pTextSymbol; CString strHeight; pTextSymbol.CreateInstance(CLSID_TextSymbol); //'Set the text symbol font by getting the IFontDisp interface pTextSymbol->put_Font(m_pAnnoTextFont); double mapUnitsInches; IUnitConverterPtr pUnitConverter(CLSID_UnitConverter); pUnitConverter->ConvertUnits(dblHeight, esriMeters, esriInches, &mapUnitsInches); strHeight.Format("%f", (mapUnitsInches * 72) / ReferenceScale); double dSize = atof(strHeight); pTextSymbol->put_Size(dSize); pTextSymbol->put_HorizontalAlignment(horizAlign); pTextSymbol->put_VerticalAlignment(vertAlign); pTextElement.CreateInstance(CLSID_TextElement); hr = pTextElement->put_ScaleText(VARIANT_TRUE); hr = pTextElement->put_Text(CComBSTR(strText)); hr = pTextElement->put_Symbol(pTextSymbol); IElementPtr pElement = pTextElement; IPointPtr pPoint(CLSID_Point); hr = pPoint->PutCoords(dblX, dblY); hr = pElement->put_Geometry(pPoint); if (fabs(dblAngle) > 0) { ITransform2DPtr pTransform2D = pTextElement; pTransform2D->Rotate(pPoint, dblAngle); } return pTextElement.Detach(); } /******************************************************************** ¼òÒªÃèÊö : ÊͷŽӿÚÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ int XDWGReader::ReleasePointer(IUnknown*& pInterface) { int iRst = 0; if (pInterface != NULL) { try { iRst = pInterface->Release(); pInterface = NULL; } catch(...) { } } return iRst; } // ÊͷŽӿڶÔÏó void XDWGReader::ReleaseAOs(void) { int iRst = 0; iRst = ReleasePointer((IUnknown*&)m_pPointFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureCursor); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowCursor); iRst = ReleasePointer((IUnknown*&)m_pPointFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pTextFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pLineFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pAnnoFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pPolygonFeatureBuffer); iRst = ReleasePointer((IUnknown*&)m_pExtentTableRowBuffer); iRst = ReleasePointer((IUnknown*&)m_pSpRef); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPoint); iRst = ReleasePointer((IUnknown*&)m_pFeatClassText); iRst = ReleasePointer((IUnknown*&)m_pFeatClassLine); iRst = ReleasePointer((IUnknown*&)m_pFeatClassPolygon); iRst = ReleasePointer((IUnknown*&)m_pAnnoFtCls); iRst = ReleasePointer((IUnknown*&)m_pExtendTable); } /******************************************************************** ¼òÒªÃèÊö :³õʼ»¯¶ÔÏóÖ¸Õë ÊäÈë²ÎÊý : ·µ »Ø Öµ : ÐÞ¸ÄÈÕÖ¾ : *********************************************************************/ void XDWGReader::InitAOPointers(void) { m_pPointFeatureCursor = NULL; m_pTextFeatureCursor = NULL; m_pLineFeatureCursor = NULL; m_pAnnoFeatureCursor = NULL; m_pPolygonFeatureCursor = NULL; m_pExtentTableRowCursor = NULL; m_pPointFeatureBuffer = NULL; m_pTextFeatureBuffer = NULL; m_pLineFeatureBuffer = NULL; m_pAnnoFeatureBuffer = NULL; m_pPolygonFeatureBuffer = NULL; m_pExtentTableRowBuffer = NULL; m_pFeatClassPoint = NULL; m_pFeatClassLine = NULL; m_pFeatClassPolygon = NULL; m_pAnnoFtCls = NULL; m_pExtendTable = NULL; m_pFeatClassText = NULL; }
hy1314200/HyDM
DataExchange/DwgConvert/XDwgDirectReader.cpp
C++
gpl-3.0
132,005
# Copyright 2019 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import datetime from collections import defaultdict from core.util import dedupe, first as getfirst from core.trans import tr from ..model.date import DateFormat from .base import GUIObject from .import_table import ImportTable from .selectable_list import LinkedSelectableList DAY = 'day' MONTH = 'month' YEAR = 'year' class SwapType: DayMonth = 0 MonthYear = 1 DayYear = 2 DescriptionPayee = 3 InvertAmount = 4 def last_two_digits(year): return year - ((year // 100) * 100) def swapped_date(date, first, second): attrs = {DAY: date.day, MONTH: date.month, YEAR: last_two_digits(date.year)} newattrs = {first: attrs[second], second: attrs[first]} if YEAR in newattrs: newattrs[YEAR] += 2000 return date.replace(**newattrs) def swap_format_elements(format, first, second): # format is a DateFormat swapped = format.copy() elems = swapped.elements TYPE2CHAR = {DAY: 'd', MONTH: 'M', YEAR: 'y'} first_char = TYPE2CHAR[first] second_char = TYPE2CHAR[second] first_index = [i for i, x in enumerate(elems) if x.startswith(first_char)][0] second_index = [i for i, x in enumerate(elems) if x.startswith(second_char)][0] elems[first_index], elems[second_index] = elems[second_index], elems[first_index] return swapped class AccountPane: def __init__(self, iwin, account, target_account, parsing_date_format): self.iwin = iwin self.account = account self._selected_target = target_account self.name = account.name entries = iwin.loader.accounts.entries_for_account(account) self.count = len(entries) self.matches = [] # [[ref, imported]] self.parsing_date_format = parsing_date_format self.max_day = 31 self.max_month = 12 self.max_year = 99 # 2 digits self._match_entries() self._swap_possibilities = set() self._compute_swap_possibilities() def _compute_swap_possibilities(self): entries = list(self.iwin.loader.accounts.entries_for_account(self.account)) if not entries: return self._swap_possibilities = set([(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]) for first, second in self._swap_possibilities.copy(): for entry in entries: try: swapped_date(entry.date, first, second) except ValueError: self._swap_possibilities.remove((first, second)) break def _match_entries(self): to_import = list(self.iwin.loader.accounts.entries_for_account(self.account)) reference2entry = {} for entry in (e for e in to_import if e.reference): reference2entry[entry.reference] = entry self.matches = [] if self.selected_target is not None: entries = self.iwin.document.accounts.entries_for_account(self.selected_target) for entry in entries: if entry.reference in reference2entry: other = reference2entry[entry.reference] if entry.reconciled: self.iwin.import_table.dont_import.add(other) to_import.remove(other) del reference2entry[entry.reference] else: other = None if other is not None or not entry.reconciled: self.matches.append([entry, other]) self.matches += [[None, entry] for entry in to_import] self._sort_matches() def _sort_matches(self): self.matches.sort(key=lambda t: t[0].date if t[0] is not None else t[1].date) def bind(self, existing, imported): [match1] = [m for m in self.matches if m[0] is existing] [match2] = [m for m in self.matches if m[1] is imported] assert match1[1] is None assert match2[0] is None match1[1] = match2[1] self.matches.remove(match2) def can_swap_date_fields(self, first, second): # 'day', 'month', 'year' return (first, second) in self._swap_possibilities or (second, first) in self._swap_possibilities def match_entries_by_date_and_amount(self, threshold): delta = datetime.timedelta(days=threshold) unmatched = ( to_import for ref, to_import in self.matches if ref is None) unmatched_refs = ( ref for ref, to_import in self.matches if to_import is None) amount2refs = defaultdict(list) for entry in unmatched_refs: amount2refs[entry.amount].append(entry) for entry in unmatched: if entry.amount not in amount2refs: continue potentials = amount2refs[entry.amount] for ref in potentials: if abs(ref.date - entry.date) <= delta: self.bind(ref, entry) potentials.remove(ref) self._sort_matches() def unbind(self, existing, imported): [match] = [m for m in self.matches if m[0] is existing and m[1] is imported] match[1] = None self.matches.append([None, imported]) self._sort_matches() @property def selected_target(self): return self._selected_target @selected_target.setter def selected_target(self, value): self._selected_target = value self._match_entries() # This is a modal window that is designed to be re-instantiated on each import # run. It is shown modally by the UI as soon as its created on the UI side. class ImportWindow(GUIObject): # --- View interface # close() # close_selected_tab() # set_swap_button_enabled(enabled: bool) # update_selected_pane() # show() # def __init__(self, mainwindow, target_account=None): super().__init__() if not hasattr(mainwindow, 'loader'): raise ValueError("Nothing to import!") self.mainwindow = mainwindow self.document = mainwindow.document self.app = self.document.app self._selected_pane_index = 0 self._selected_target_index = 0 def setfunc(index): self.view.set_swap_button_enabled(self.can_perform_swap()) self.swap_type_list = LinkedSelectableList(items=[ "<placeholder> Day <--> Month", "<placeholder> Month <--> Year", "<placeholder> Day <--> Year", tr("Description <--> Payee"), tr("Invert Amounts"), ], setfunc=setfunc) self.swap_type_list.selected_index = SwapType.DayMonth self.panes = [] self.import_table = ImportTable(self) self.loader = self.mainwindow.loader self.target_accounts = [ a for a in self.document.accounts if a.is_balance_sheet_account()] self.target_accounts.sort(key=lambda a: a.name.lower()) accounts = [] for account in self.loader.accounts: if account.is_balance_sheet_account(): entries = self.loader.accounts.entries_for_account(account) if len(entries): new_name = self.document.accounts.new_name(account.name) if new_name != account.name: self.loader.accounts.rename_account(account, new_name) accounts.append(account) parsing_date_format = DateFormat.from_sysformat(self.loader.parsing_date_format) for account in accounts: target = target_account if target is None and account.reference: target = getfirst( t for t in self.target_accounts if t.reference == account.reference ) self.panes.append( AccountPane(self, account, target, parsing_date_format)) # --- Private def _can_swap_date_fields(self, first, second): # 'day', 'month', 'year' pane = self.selected_pane if pane is None: return False return pane.can_swap_date_fields(first, second) def _invert_amounts(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: for split in txn.splits: split.amount = -split.amount self.import_table.refresh() def _refresh_target_selection(self): if not self.panes: return target = self.selected_pane.selected_target self._selected_target_index = 0 if target is not None: try: self._selected_target_index = self.target_accounts.index(target) + 1 except ValueError: pass def _refresh_swap_list_items(self): if not self.panes: return items = [] basefmt = self.selected_pane.parsing_date_format for first, second in [(DAY, MONTH), (MONTH, YEAR), (DAY, YEAR)]: swapped = swap_format_elements(basefmt, first, second) items.append("{} --> {}".format(basefmt.iso_format, swapped.iso_format)) self.swap_type_list[:3] = items def _swap_date_fields(self, first, second, apply_to_all): # 'day', 'month', 'year' assert self._can_swap_date_fields(first, second) if apply_to_all: panes = [p for p in self.panes if p.can_swap_date_fields(first, second)] else: panes = [self.selected_pane] def switch_func(txn): txn.date = swapped_date(txn.date, first, second) self._swap_fields(panes, switch_func) # Now, lets' change the date format on these panes for pane in panes: basefmt = self.selected_pane.parsing_date_format swapped = swap_format_elements(basefmt, first, second) pane.parsing_date_format = swapped pane._sort_matches() self.import_table.refresh() self._refresh_swap_list_items() def _swap_description_payee(self, apply_to_all): if apply_to_all: panes = self.panes else: panes = [self.selected_pane] def switch_func(txn): txn.description, txn.payee = txn.payee, txn.description self._swap_fields(panes, switch_func) def _swap_fields(self, panes, switch_func): seen = set() for pane in panes: entries = self.loader.accounts.entries_for_account(pane.account) txns = dedupe(e.transaction for e in entries) for txn in txns: if txn.affected_accounts() & seen: # We've already swapped this txn in a previous pane. continue switch_func(txn) seen.add(pane.account) self.import_table.refresh() def _update_selected_pane(self): self.import_table.refresh() self._refresh_swap_list_items() self.view.update_selected_pane() self.view.set_swap_button_enabled(self.can_perform_swap()) # --- Override def _view_updated(self): if self.document.can_restore_from_prefs(): self.restore_view() # XXX Logically, we should call _update_selected_pane() but doing so # make tests fail. to investigate. self._refresh_target_selection() self.view.update_selected_pane() self._refresh_swap_list_items() self.import_table.refresh() # --- Public def can_perform_swap(self): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: return self._can_swap_date_fields(DAY, MONTH) elif index == SwapType.MonthYear: return self._can_swap_date_fields(MONTH, YEAR) elif index == SwapType.DayYear: return self._can_swap_date_fields(DAY, YEAR) else: return True def close_pane(self, index): was_selected = index == self.selected_pane_index del self.panes[index] if not self.panes: self.view.close() return self._selected_pane_index = min(self._selected_pane_index, len(self.panes) - 1) if was_selected: self._update_selected_pane() def import_selected_pane(self): pane = self.selected_pane matches = pane.matches matches = [ (e, ref) for ref, e in matches if e is not None and e not in self.import_table.dont_import] if pane.selected_target is not None: # We import in an existing account, adjust all the transactions accordingly target_account = pane.selected_target else: target_account = None self.document.import_entries(target_account, pane.account, matches) self.mainwindow.revalidate() self.close_pane(self.selected_pane_index) self.view.close_selected_tab() def match_entries_by_date_and_amount(self, threshold): self.selected_pane.match_entries_by_date_and_amount(threshold) self.import_table.refresh() def perform_swap(self, apply_to_all=False): index = self.swap_type_list.selected_index if index == SwapType.DayMonth: self._swap_date_fields(DAY, MONTH, apply_to_all=apply_to_all) elif index == SwapType.MonthYear: self._swap_date_fields(MONTH, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DayYear: self._swap_date_fields(DAY, YEAR, apply_to_all=apply_to_all) elif index == SwapType.DescriptionPayee: self._swap_description_payee(apply_to_all=apply_to_all) elif index == SwapType.InvertAmount: self._invert_amounts(apply_to_all=apply_to_all) def restore_view(self): self.import_table.columns.restore_columns() # --- Properties @property def selected_pane(self): return self.panes[self.selected_pane_index] if self.panes else None @property def selected_pane_index(self): return self._selected_pane_index @selected_pane_index.setter def selected_pane_index(self, value): if value >= len(self.panes): return self._selected_pane_index = value self._refresh_target_selection() self._update_selected_pane() @property def selected_target_account(self): return self.selected_pane.selected_target @property def selected_target_account_index(self): return self._selected_target_index @selected_target_account_index.setter def selected_target_account_index(self, value): target = self.target_accounts[value - 1] if value > 0 else None self.selected_pane.selected_target = target self._selected_target_index = value self.import_table.refresh() @property def target_account_names(self): return [tr('< New Account >')] + [a.name for a in self.target_accounts]
hsoft/moneyguru
core/gui/import_window.py
Python
gpl-3.0
15,326
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import android.view.DisplayAdjustments; import android.view.Display; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Proxying implementation of Context that simply delegates all of its calls to * another Context. Can be subclassed to modify behavior without changing * the original Context. */ public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } /** * Set the base context for this ContextWrapper. All calls will then be * delegated to the base context. Throws * IllegalStateException if a base context has already been set. * * @param base The new base context for this wrapper. */ protected void attachBaseContext(Context base) { if (mBase != null) { throw new IllegalStateException("Base context already set"); } mBase = base; } /** * @return the base context as set by the constructor or setBaseContext */ public Context getBaseContext() { return mBase; } @Override public AssetManager getAssets() { return mBase.getAssets(); } @Override public Resources getResources() { return mBase.getResources(); } @Override public PackageManager getPackageManager() { return mBase.getPackageManager(); } @Override public ContentResolver getContentResolver() { return mBase.getContentResolver(); } @Override public Looper getMainLooper() { return mBase.getMainLooper(); } @Override public Context getApplicationContext() { return mBase.getApplicationContext(); } @Override public void setTheme(int resid) { mBase.setTheme(resid); } /** @hide */ @Override public int getThemeResId() { return mBase.getThemeResId(); } @Override public Resources.Theme getTheme() { return mBase.getTheme(); } @Override public ClassLoader getClassLoader() { return mBase.getClassLoader(); } @Override public String getPackageName() { return mBase.getPackageName(); } /** @hide */ @Override public String getBasePackageName() { return mBase.getBasePackageName(); } /** @hide */ @Override public String getOpPackageName() { return mBase.getOpPackageName(); } @Override public ApplicationInfo getApplicationInfo() { return mBase.getApplicationInfo(); } @Override public String getPackageResourcePath() { return mBase.getPackageResourcePath(); } @Override public String getPackageCodePath() { return mBase.getPackageCodePath(); } /** @hide */ @Override public File getSharedPrefsFile(String name) { return mBase.getSharedPrefsFile(name); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return mBase.getSharedPreferences(name, mode); } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { return mBase.openFileInput(name); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { return mBase.openFileOutput(name, mode); } @Override public boolean deleteFile(String name) { return mBase.deleteFile(name); } @Override public File getFileStreamPath(String name) { return mBase.getFileStreamPath(name); } @Override public String[] fileList() { return mBase.fileList(); } @Override public File getFilesDir() { return mBase.getFilesDir(); } @Override public File getNoBackupFilesDir() { return mBase.getNoBackupFilesDir(); } @Override public File getExternalFilesDir(String type) { return mBase.getExternalFilesDir(type); } @Override public File[] getExternalFilesDirs(String type) { return mBase.getExternalFilesDirs(type); } @Override public File getObbDir() { return mBase.getObbDir(); } @Override public File[] getObbDirs() { return mBase.getObbDirs(); } @Override public File getCacheDir() { return mBase.getCacheDir(); } @Override public File getCodeCacheDir() { return mBase.getCodeCacheDir(); } @Override public File getExternalCacheDir() { return mBase.getExternalCacheDir(); } @Override public File[] getExternalCacheDirs() { return mBase.getExternalCacheDirs(); } @Override public File[] getExternalMediaDirs() { return mBase.getExternalMediaDirs(); } @Override public File getDir(String name, int mode) { return mBase.getDir(name, mode); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { return mBase.openOrCreateDatabase(name, mode, factory); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) { return mBase.openOrCreateDatabase(name, mode, factory, errorHandler); } @Override public boolean deleteDatabase(String name) { return mBase.deleteDatabase(name); } @Override public File getDatabasePath(String name) { return mBase.getDatabasePath(name); } @Override public String[] databaseList() { return mBase.databaseList(); } @Override public Drawable getWallpaper() { return mBase.getWallpaper(); } @Override public Drawable peekWallpaper() { return mBase.peekWallpaper(); } @Override public int getWallpaperDesiredMinimumWidth() { return mBase.getWallpaperDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return mBase.getWallpaperDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { mBase.setWallpaper(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { mBase.setWallpaper(data); } @Override public void clearWallpaper() throws IOException { mBase.clearWallpaper(); } @Override public void startActivity(Intent intent) { mBase.startActivity(intent); } /** @hide */ @Override public void startActivityAsUser(Intent intent, UserHandle user) { mBase.startActivityAsUser(intent, user); } @Override public void startActivity(Intent intent, Bundle options) { mBase.startActivity(intent, options); } /** @hide */ @Override public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { mBase.startActivityAsUser(intent, options, user); } @Override public void startActivities(Intent[] intents) { mBase.startActivities(intents); } @Override public void startActivities(Intent[] intents, Bundle options) { mBase.startActivities(intents, options); } /** @hide */ @Override public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { mBase.startActivitiesAsUser(intents, options, userHandle); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @Override public void sendBroadcast(Intent intent) { mBase.sendBroadcast(intent); } @Override public void sendBroadcast(Intent intent, String receiverPermission) { mBase.sendBroadcast(intent, receiverPermission); } /** @hide */ @Override public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { mBase.sendBroadcast(intent, receiverPermission, appOp); } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { mBase.sendOrderedBroadcast(intent, receiverPermission); } @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendBroadcastAsUser(intent, user); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) { mBase.sendBroadcastAsUser(intent, user, receiverPermission); } @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendStickyBroadcast(Intent intent) { mBase.sendStickyBroadcast(intent); } @Override public void sendStickyOrderedBroadcast( Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcast(Intent intent) { mBase.removeStickyBroadcast(intent); } @Override public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendStickyBroadcastAsUser(intent, user); } @Override public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcastAsUser(intent, user, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.removeStickyBroadcastAsUser(intent, user); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter) { return mBase.registerReceiver(receiver, filter); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiver(receiver, filter, broadcastPermission, scheduler); } /** @hide */ @Override public Intent registerReceiverAsUser( BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiverAsUser(receiver, user, filter, broadcastPermission, scheduler); } @Override public void unregisterReceiver(BroadcastReceiver receiver) { mBase.unregisterReceiver(receiver); } @Override public ComponentName startService(Intent service) { return mBase.startService(service); } @Override public boolean stopService(Intent name) { return mBase.stopService(name); } /** @hide */ @Override public ComponentName startServiceAsUser(Intent service, UserHandle user) { return mBase.startServiceAsUser(service, user); } /** @hide */ @Override public boolean stopServiceAsUser(Intent name, UserHandle user) { return mBase.stopServiceAsUser(name, user); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); } /** @hide */ @Override public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) { return mBase.bindServiceAsUser(service, conn, flags, user); } @Override public void unbindService(ServiceConnection conn) { mBase.unbindService(conn); } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { return mBase.startInstrumentation(className, profileFile, arguments); } @Override public Object getSystemService(String name) { return mBase.getSystemService(name); } @Override public int checkPermission(String permission, int pid, int uid) { return mBase.checkPermission(permission, pid, uid); } /** @hide */ @Override public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { return mBase.checkPermission(permission, pid, uid, callerToken); } @Override public int checkCallingPermission(String permission) { return mBase.checkCallingPermission(permission); } @Override public int checkCallingOrSelfPermission(String permission) { return mBase.checkCallingOrSelfPermission(permission); } @Override public void enforcePermission( String permission, int pid, int uid, String message) { mBase.enforcePermission(permission, pid, uid, message); } @Override public void enforceCallingPermission(String permission, String message) { mBase.enforceCallingPermission(permission, message); } @Override public void enforceCallingOrSelfPermission( String permission, String message) { mBase.enforceCallingOrSelfPermission(permission, message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { mBase.grantUriPermission(toPackage, uri, modeFlags); } @Override public void revokeUriPermission(Uri uri, int modeFlags) { mBase.revokeUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, pid, uid, modeFlags); } /** @hide */ @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { return mBase.checkUriPermission(uri, pid, uid, modeFlags, callerToken); } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingUriPermission(uri, modeFlags); } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingOrSelfUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags); } @Override public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission(uri, pid, uid, modeFlags, message); } @Override public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingUriPermission(uri, modeFlags, message); } @Override public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingOrSelfUriPermission(uri, modeFlags, message); } @Override public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { return mBase.createPackageContext(packageName, flags); } /** @hide */ @Override public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException { return mBase.createPackageContextAsUser(packageName, flags, user); } /** @hide */ public Context createApplicationContext(ApplicationInfo application, int flags) throws PackageManager.NameNotFoundException { return mBase.createApplicationContext(application, flags); } /** @hide */ @Override public int getUserId() { return mBase.getUserId(); } @Override public Context createConfigurationContext(Configuration overrideConfiguration) { return mBase.createConfigurationContext(overrideConfiguration); } @Override public Context createDisplayContext(Display display) { return mBase.createDisplayContext(display); } @Override public boolean isRestricted() { return mBase.isRestricted(); } /** @hide */ @Override public DisplayAdjustments getDisplayAdjustments(int displayId) { return mBase.getDisplayAdjustments(displayId); } }
s20121035/rk3288_android5.1_repo
frameworks/base/core/java/android/content/ContextWrapper.java
Java
gpl-3.0
20,584
// Copyright (c) François Paradis // This file is part of Mox, a card game simulator. // // Mox 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, version 3 of the License. // // Mox 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 Mox. If not, see <http://www.gnu.org/licenses/>. using System; using Mox.Events; using Mox.Flow; namespace Mox.Database.Library { public abstract class ZoneChangeTriggeredAbility : TriggeredAbility, IEventHandler<ZoneChangeEvent> { #region Inner Types protected class ZoneChangeContext { public readonly Resolvable<Card> Card; public ZoneChangeContext(Card card) { Card = card; } } #endregion #region Methods /// <summary> /// Returns true if the card can trigger the ability. /// </summary> /// <remarks> /// By default, checks if the card is the source. /// </remarks> /// <param name="card"></param> /// <returns></returns> protected virtual bool IsValidCard(Card card) { return card == Source; } /// <summary> /// Returns true if this is the zone from which the card should come from. /// </summary> /// <param name="zone"></param> /// <returns></returns> protected virtual bool IsTriggeringSourceZone(Zone zone) { return true; } private bool IsTriggeringTargetZone(Game game, ZoneChangeContext zoneChangeContext) { return zoneChangeContext.Card.Resolve(game).Zone.ZoneId == TriggerZone; } public override bool CanPushOnStack(Game game, object zoneChangeContext) { return IsTriggeringTargetZone(game, (ZoneChangeContext) zoneChangeContext); } public override sealed void Play(Spell spell) { ZoneChangeContext zoneChangeContext = (ZoneChangeContext)spell.Context; Play(spell, zoneChangeContext.Card); } protected internal override void ResolveSpellEffect(Part.Context context, Spell spell) { if (IsTriggeringTargetZone(context.Game, (ZoneChangeContext)spell.Context)) { base.ResolveSpellEffect(context, spell); } } protected abstract void Play(Spell spell, Resolvable<Card> card); void IEventHandler<ZoneChangeEvent>.HandleEvent(Game game, ZoneChangeEvent e) { if (IsValidCard(e.Card) && IsTriggeringSourceZone(e.OldZone) && e.NewZone.ZoneId == TriggerZone) { Trigger(new ZoneChangeContext(e.Card)); } } #endregion } }
fparadis2/mox
Source/Mox.Engine/Project/Source/Database/CardFactory/Library/ZoneChangeTriggeredAbility.cs
C#
gpl-3.0
3,243
package com.thomasjensen.checkstyle.addons.checks; /* * Checkstyle-Addons - Additional Checkstyle checks * Copyright (c) 2015-2020, the Checkstyle Addons contributors * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License, version 3, as published by the Free * Software Foundation. * * 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/>. */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.jcip.annotations.Immutable; /** * Represents a Java binary class name for reference types, in the form of its fragments. This is the only way to tell * the difference between a class called <code>A$B</code> and a class called <code>A</code> that has an inner class * <code>B</code>. */ @Immutable public final class BinaryName { private final String pkg; private final List<String> cls; /** * Constructor. * * @param pPkg package name * @param pOuterCls outer class simple name * @param pInnerCls inner class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final String pOuterCls, @Nullable final String... pInnerCls) { pkg = pPkg; List<String> nameList = new ArrayList<>(); if (pOuterCls != null) { nameList.add(pOuterCls); } else { throw new IllegalArgumentException("pOuterCls was null"); } if (pInnerCls != null) { for (final String inner : pInnerCls) { nameList.add(inner); } } cls = Collections.unmodifiableList(nameList); } /** * Constructor. * * @param pPkg package name * @param pClsNames class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final Collection<String> pClsNames) { pkg = pPkg; if (pClsNames.size() == 0) { throw new IllegalArgumentException("pClsNames is empty"); } cls = Collections.unmodifiableList(new ArrayList<>(pClsNames)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pkg != null) { sb.append(pkg); sb.append('.'); } for (final Iterator<String> iter = cls.iterator(); iter.hasNext();) { sb.append(iter.next()); if (iter.hasNext()) { sb.append('$'); } } return sb.toString(); } @Override public boolean equals(final Object pOther) { if (this == pOther) { return true; } if (pOther == null || getClass() != pOther.getClass()) { return false; } BinaryName other = (BinaryName) pOther; if (pkg != null ? !pkg.equals(other.pkg) : other.pkg != null) { return false; } if (!cls.equals(other.cls)) { return false; } return true; } @Override public int hashCode() { int result = pkg != null ? pkg.hashCode() : 0; result = 31 * result + cls.hashCode(); return result; } public String getPackage() { return pkg; } /** * Getter. * * @return the simple name of the outer class (even if this binary name represents an inner class) */ public String getOuterSimpleName() { return cls.get(0); } /** * Getter. * * @return the simple name of the inner class represented by this binary name. <code>null</code> if this binary name * does not represent an inner class */ public String getInnerSimpleName() { return cls.size() > 1 ? cls.get(cls.size() - 1) : null; } /** * The fully qualified name of the outer class. * * @return that, or <code>null</code> if the simple name of the outer class is unknown */ @CheckForNull public String getOuterFqcn() { return (pkg != null ? (pkg + ".") : "") + getOuterSimpleName(); } }
checkstyle-addons/checkstyle-addons
src/main/java/com/thomasjensen/checkstyle/addons/checks/BinaryName.java
Java
gpl-3.0
4,699
#include "Board.h" #include <iostream> using namespace std; void Board::enumExts( ) { if(ptester->hasUnboundedHorizAttacks()) { for( int i = 1; i <= nrows; i++ ) if( PiecesInRow[i] > 1 ) { cout << 0 << endl; return; } } _enumExts(); } void Board::_enumExts( ) { Place P(1,1); if( n() != 0 ) { P = top(); if( PiecesInOrBelowRow[P.row] == n() ) { P.row++; P.col = 1; } } while( P.col <= ncols ) { if( ! IsAttacked(P) ) { push(P); if( n() == npieces ) report( ); else _enumExts( ); pop(); } P.col++; } if( n() == 0 ) cout << sol_count << endl; } void Board::print( ) { int row, col; for( row = nrows; row > 0; row-- ) { for( col = 1; col <= ncols; col++) // if(in(row,col)) cout << '*'; else cout << '0'; if(in(row,col)) cout << '#'; else cout << 'O'; cout << endl; } cout << endl; } void Board::report( ) { sol_count++; if( show_boards ) { cout << "Board " << sol_count << ':' << endl; print( ); } } #include "AttackTester.h" static void useage() { cerr << "Options:\n\ --show-boards\n\ --pieces-per-row n1,n2,n3,...nr [default 1,1,1,...]\n\ --nrows m [default 4]\n\ --ncols n [default 4]\n\ --piece queen [default]\n\ --piece king\n\ --piece rook or others added" << endl; exit( 1 ); } int main(int argc, char *argv[]) { int nrows=4; int ncols=4; bool show_boards = false; int A[Board::Maxrows]; bool piecesPerRowGiven = false; AttackTester *ptester = getp("queen"); argc--; argv++; while( argc-- ) { if(!strcmp(*argv,"--show-boards")) { show_boards = true; argv++; continue; } if(!strcmp(*argv,"--pieces-per-row")) { char *p = *(++argv); int i; for(i = 0; (i < Board::Maxrows) && *p!='\0'; i++ ) { A[i] = strtol(p,&p,0); if( *p == ',' ) p++; else if( *p != '\0' ) useage(); } for( ; i < Board::Maxrows; i++ ) A[i] = 1; piecesPerRowGiven = true; argv++; argc--; continue; } if(!strcmp(*argv,"--nrows")) { argv++; argc--; nrows=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--ncols")) { argv++; argc--; ncols=strtol(*(argv++),NULL,0); continue; } if(!strcmp(*argv,"--piece")) { argv++; argc--; ptester = getp(*(argv++)); if( !ptester ) { cerr << "Unimplemented Piece:" << *(argv - 1) << endl; exit ( 1 ); } continue; } } if(piecesPerRowGiven) { Board myBoard(nrows, ncols, ptester, show_boards, A); myBoard.enumExts( ); } else { Board myBoard(nrows, ncols, ptester, show_boards, NULL ); myBoard.enumExts( ); } return 0; }
chaikens/MathResearchPrograms
Queens/Ver2/Board.cpp
C++
gpl-3.0
2,775
/* * $Id: LeftJoin.java,v 1.2 2006/04/09 12:13:12 laddi Exp $ * Created on 5.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.data.query; import java.util.HashSet; import java.util.Set; import com.idega.data.query.output.Output; import com.idega.data.query.output.Outputable; import com.idega.data.query.output.ToStringer; /** * * Last modified: $Date: 2006/04/09 12:13:12 $ by $Author: laddi $ * * @author <a href="mailto:gummi@idega.com">Gudmundur Agust Saemundsson</a> * @version $Revision: 1.2 $ */ public class LeftJoin implements Outputable { private Column left, right; public LeftJoin(Column left, Column right) { this.left = left; this.right = right; } public Column getLeftColumn() { return this.left; } public Column getRightColumn() { return this.right; } @Override public void write(Output out) { out.print(this.left.getTable()) .print(" left join ") .print(this.right.getTable()) .print(" on ") .print(this.left) .print(" = ") .print(this.right); } public Set<Table> getTables(){ Set<Table> s = new HashSet<Table>(); s.add(this.left.getTable()); s.add(this.right.getTable()); return s; } @Override public String toString() { return ToStringer.toString(this); } }
idega/com.idega.core
src/java/com/idega/data/query/LeftJoin.java
Java
gpl-3.0
1,467
package it.emarolab.owloop.descriptor.utility.classDescriptor; import it.emarolab.amor.owlInterface.OWLReferences; import it.emarolab.owloop.descriptor.construction.descriptorEntitySet.Individuals; import it.emarolab.owloop.descriptor.construction.descriptorExpression.ClassExpression; import it.emarolab.owloop.descriptor.construction.descriptorGround.ClassGround; import it.emarolab.owloop.descriptor.utility.individualDescriptor.LinkIndividualDesc; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import java.util.List; /** * This is an example of a 'simple' Class Descriptor that implements 1 ClassExpression (aka {@link ClassExpression}) interface: * <ul> * <li><b>{@link ClassExpression.Instance}</b>: to describe an Individual of a Class.</li> * </ul> * * See {@link FullClassDesc} for an example of a 'compound' Class Descriptor that implements all ClassExpressions (aka {@link ClassExpression}). * <p> * <div style="text-align:center;"><small> * <b>File</b>: it.emarolab.owloop.core.Axiom <br> * <b>Licence</b>: GNU GENERAL PUBLIC LICENSE. Version 3, 29 June 2007 <br> * <b>Authors</b>: Buoncompagni Luca (luca.buoncompagni@edu.unige.it), Syed Yusha Kareem (kareem.syed.yusha@dibris.unige.it) <br> * <b>affiliation</b>: EMAROLab, DIBRIS, University of Genoa. <br> * <b>date</b>: 01/05/19 <br> * </small></div> */ public class InstanceClassDesc extends ClassGround implements ClassExpression.Instance<LinkIndividualDesc> { private Individuals individuals = new Individuals(); /* Constructors from class: ClassGround */ public InstanceClassDesc(OWLClass instance, OWLReferences onto) { super(instance, onto); } public InstanceClassDesc(String instanceName, OWLReferences onto) { super(instanceName, onto); } public InstanceClassDesc(OWLClass instance, String ontoName) { super(instance, ontoName); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath) { super(instance, ontoName, filePath, iriPath); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instance, ontoName, filePath, iriPath, bufferingChanges); } public InstanceClassDesc(String instanceName, String ontoName) { super(instanceName, ontoName); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath) { super(instanceName, ontoName, filePath, iriPath); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instanceName, ontoName, filePath, iriPath, bufferingChanges); } /* Overriding methods in class: ClassGround */ // To read axioms from an ontology @Override public List<MappingIntent> readAxioms() { return Instance.super.readAxioms(); } // To write axioms to an ontology @Override public List<MappingIntent> writeAxioms() { return Instance.super.writeAxioms(); } /* Overriding methods in classes: Class and ClassExpression */ // Is used by the descriptors's build() method. It's possible to change the return type based on need. @Override public LinkIndividualDesc getIndividualDescriptor(OWLNamedIndividual instance, OWLReferences ontology) { return new LinkIndividualDesc( instance, ontology); } // It returns Individuals from the EntitySet (after being read from the ontology) @Override public Individuals getIndividuals() { return individuals; } /* Overriding method in class: Object */ // To show internal state of the Descriptor @Override public String toString() { return getClass().getSimpleName() + "{" + "\n" + "\n" + "\t" + getGround() + ":" + "\n" + "\n" + "\t\t⇐ " + individuals + "\n" + "}" + "\n"; } }
EmaroLab/owloop
src/main/java/it/emarolab/owloop/descriptor/utility/classDescriptor/InstanceClassDesc.java
Java
gpl-3.0
4,115
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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/>. * */ package store import ( "io" "net/http" "net/url" "github.com/juju/ratelimit" "golang.org/x/net/context" "gopkg.in/retry.v1" "github.com/snapcore/snapd/overlord/auth" "github.com/snapcore/snapd/progress" "github.com/snapcore/snapd/snap" "github.com/snapcore/snapd/testutil" ) var ( HardLinkCount = hardLinkCount ApiURL = apiURL Download = download UseDeltas = useDeltas ApplyDelta = applyDelta AuthLocation = authLocation AuthURL = authURL StoreURL = storeURL StoreDeveloperURL = storeDeveloperURL MustBuy = mustBuy RequestStoreMacaroon = requestStoreMacaroon DischargeAuthCaveat = dischargeAuthCaveat RefreshDischargeMacaroon = refreshDischargeMacaroon RequestStoreDeviceNonce = requestStoreDeviceNonce RequestDeviceSession = requestDeviceSession LoginCaveatID = loginCaveatID JsonContentType = jsonContentType SnapActionFields = snapActionFields ) // MockDefaultRetryStrategy mocks the retry strategy used by several store requests func MockDefaultRetryStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalDefaultRetryStrategy := defaultRetryStrategy defaultRetryStrategy = strategy t.AddCleanup(func() { defaultRetryStrategy = originalDefaultRetryStrategy }) } func MockConnCheckStrategy(t *testutil.BaseTest, strategy retry.Strategy) { originalConnCheckStrategy := connCheckStrategy connCheckStrategy = strategy t.AddCleanup(func() { connCheckStrategy = originalConnCheckStrategy }) } func (cm *CacheManager) CacheDir() string { return cm.cacheDir } func (cm *CacheManager) Cleanup() error { return cm.cleanup() } func (cm *CacheManager) Count() int { return cm.count() } func MockOsRemove(f func(name string) error) func() { oldOsRemove := osRemove osRemove = f return func() { osRemove = oldOsRemove } } func MockDownload(f func(ctx context.Context, name, sha3_384, downloadURL string, user *auth.UserState, s *Store, w io.ReadWriteSeeker, resume int64, pbar progress.Meter, dlOpts *DownloadOptions) error) (restore func()) { origDownload := download download = f return func() { download = origDownload } } func MockApplyDelta(f func(name string, deltaPath string, deltaInfo *snap.DeltaInfo, targetPath string, targetSha3_384 string) error) (restore func()) { origApplyDelta := applyDelta applyDelta = f return func() { applyDelta = origApplyDelta } } func (sto *Store) MockCacher(obs downloadCache) (restore func()) { oldCacher := sto.cacher sto.cacher = obs return func() { sto.cacher = oldCacher } } func (sto *Store) SetDeltaFormat(dfmt string) { sto.deltaFormat = dfmt } func (sto *Store) DownloadDelta(deltaName string, downloadInfo *snap.DownloadInfo, w io.ReadWriteSeeker, pbar progress.Meter, user *auth.UserState) error { return sto.downloadDelta(deltaName, downloadInfo, w, pbar, user) } func (sto *Store) DoRequest(ctx context.Context, client *http.Client, reqOptions *requestOptions, user *auth.UserState) (*http.Response, error) { return sto.doRequest(ctx, client, reqOptions, user) } func (sto *Store) Client() *http.Client { return sto.client } func (sto *Store) DetailFields() []string { return sto.detailFields } func (sto *Store) DecorateOrders(snaps []*snap.Info, user *auth.UserState) error { return sto.decorateOrders(snaps, user) } func (cfg *Config) SetBaseURL(u *url.URL) error { return cfg.setBaseURL(u) } func NewHashError(name, sha3_384, targetSha3_384 string) HashError { return HashError{name, sha3_384, targetSha3_384} } func NewRequestOptions(mth string, url *url.URL) *requestOptions { return &requestOptions{ Method: mth, URL: url, } } func MockRatelimitReader(f func(r io.Reader, bucket *ratelimit.Bucket) io.Reader) (restore func()) { oldRatelimitReader := ratelimitReader ratelimitReader = f return func() { ratelimitReader = oldRatelimitReader } }
kenvandine/snapd
store/export_test.go
GO
gpl-3.0
4,569
using System; using System.Threading; using System.Windows.Input; namespace WpfAsyncPack.Internal { internal sealed class CancelAsyncCommand : ICommand { private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private bool _isCommandExecuting; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public CancellationToken Token => _cancellationTokenSource.Token; void ICommand.Execute(object parameter) { _cancellationTokenSource.Cancel(); RaiseCanExecuteChanged(); } bool ICommand.CanExecute(object parameter) { return _isCommandExecuting && !_cancellationTokenSource.IsCancellationRequested; } public void NotifyCommandStarting() { _isCommandExecuting = true; if (_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource = new CancellationTokenSource(); RaiseCanExecuteChanged(); } } public void NotifyCommandFinished() { _isCommandExecuting = false; RaiseCanExecuteChanged(); } private static void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } } }
kirmir/WpfAsyncPack
WpfAsyncPack/Internal/CancelAsyncCommand.cs
C#
gpl-3.0
1,497
<?php /** * The file that defines the core plugin class * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @link http://stephanetauziede.com * @since 1.0.0 * * @package Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes */ /** * The core plugin class. * * This is used to define internationalization, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * @package Wp_Startup_Press_Room * @subpackage Wp_Startup_Press_Room/includes * @author Stephane Tauziede <stauziede@gmail.com> */ class Wp_Startup_Press_Room { /** * The loader that's responsible for maintaining and registering all hooks that power * the plugin. * * @since 1.0.0 * @access protected * @var Wp_Startup_Press_Room_Loader $loader Maintains and registers all hooks for the plugin. */ protected $loader; /** * The unique identifier of this plugin. * * @since 1.0.0 * @access protected * @var string $plugin_name The string used to uniquely identify this plugin. */ protected $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * @access protected * @var string $version The current version of the plugin. */ protected $version; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { $this->plugin_name = 'wp-startup-press-room'; $this->version = '1.0.0'; $this->load_dependencies(); $this->set_locale(); $this->define_admin_hooks(); $this->define_public_hooks(); } /** * Load the required dependencies for this plugin. * * Include the following files that make up the plugin: * * - Wp_Startup_Press_Room_Loader. Orchestrates the hooks of the plugin. * - Wp_Startup_Press_Room_i18n. Defines internationalization functionality. * - Wp_Startup_Press_Room_Admin. Defines all hooks for the admin area. * - Wp_Startup_Press_Room_Public. Defines all hooks for the public side of the site. * * Create an instance of the loader which will be used to register the hooks * with WordPress. * * @since 1.0.0 * @access private */ private function load_dependencies() { /** * The class responsible for orchestrating the actions and filters of the * core plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-startup-press-room-loader.php'; /** * The class responsible for defining internationalization functionality * of the plugin. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-startup-press-room-i18n.php'; /** * The class responsible for defining all actions that occur in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-admin.php'; /** * The class responsible for PR options page in the admin area. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-startup-press-room-options.php'; /** * The class responsible for defining all actions that occur in the public-facing * side of the site. */ require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-wp-startup-press-room-public.php'; $this->loader = new Wp_Startup_Press_Room_Loader(); // Required files for registering the post type and taxonomies. require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-registrations.php'; require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-post-type-metaboxes.php'; // Instantiate registration class, so we can add it as a dependency to main plugin class. $post_type_registrations = new PR_Post_Type_Registrations; // Register callback that is fired when the plugin is activated. register_activation_hook( __FILE__, array( $post_type, 'activate' ) ); // Initialize registrations for post-activation requests. $post_type_registrations->init(); // Initialize metaboxes //$post_type_metaboxes = new PR_Meta_Box; //$post_type_metaboxes->init(); } /** * Define the locale for this plugin for internationalization. * * Uses the Wp_Startup_Press_Room_i18n class in order to set the domain and to register the hook * with WordPress. * * @since 1.0.0 * @access private */ private function set_locale() { $plugin_i18n = new Wp_Startup_Press_Room_i18n(); $this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' ); } /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { $plugin_admin = new Wp_Startup_Press_Room_Admin( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' ); $this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' ); } /** * Register all of the hooks related to the public-facing functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_public_hooks() { $plugin_public = new Wp_Startup_Press_Room_Public( $this->get_plugin_name(), $this->get_version() ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' ); $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' ); } /** * Run the loader to execute all of the hooks with WordPress. * * @since 1.0.0 */ public function run() { $this->loader->run(); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define internationalization functionality. * * @since 1.0.0 * @return string The name of the plugin. */ public function get_plugin_name() { return $this->plugin_name; } /** * The reference to the class that orchestrates the hooks with the plugin. * * @since 1.0.0 * @return Wp_Startup_Press_Room_Loader Orchestrates the hooks of the plugin. */ public function get_loader() { return $this->loader; } /** * Retrieve the version number of the plugin. * * @since 1.0.0 * @return string The version number of the plugin. */ public function get_version() { return $this->version; } }
stauziede/WP-Startup-Press-Room
includes/class-wp-startup-press-room.php
PHP
gpl-3.0
6,889
package com.example.habitup.View; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.habitup.Model.Attributes; import com.example.habitup.Model.Habit; import com.example.habitup.R; import java.util.ArrayList; /** * This is the adapter for creating the habit list, which displays the habit name, and * it's schedule. * * @author Shari Barboza */ public class HabitListAdapter extends ArrayAdapter<Habit> { // The habits array private ArrayList<Habit> habits; public HabitListAdapter(Context context, int resource, ArrayList<Habit> habits) { super(context, resource, habits); this.habits = habits; } @Override public View getView(int position, View view, ViewGroup viewGroup) { View v = view; // Inflate a new view if (v == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); v = inflater.inflate(R.layout.habit_list_item, null); } // Get the habit Habit habit = habits.get(position); String attributeName = habit.getHabitAttribute(); String attributeColour = Attributes.getColour(attributeName); // Set the name of the habit TextView habitNameView = v.findViewById(R.id.habit_name); habitNameView.setText(habit.getHabitName()); habitNameView.setTextColor(Color.parseColor(attributeColour)); // Get habit schedule boolean[] schedule = habit.getHabitSchedule(); View monView = v.findViewById(R.id.mon_box); View tueView = v.findViewById(R.id.tue_box); View wedView = v.findViewById(R.id.wed_box); View thuView = v.findViewById(R.id.thu_box); View friView = v.findViewById(R.id.fri_box); View satView = v.findViewById(R.id.sat_box); View sunView = v.findViewById(R.id.sun_box); View[] textViews = {monView, tueView, wedView, thuView, friView, satView, sunView}; // Display days of the month for the habit's schedule for (int i = 1; i < schedule.length; i++) { if (schedule[i]) { textViews[i-1].setVisibility(View.VISIBLE); } else { textViews[i-1].setVisibility(View.GONE); } } return v; } }
CMPUT301F17T29/HabitUp
app/src/main/java/com/example/habitup/View/HabitListAdapter.java
Java
gpl-3.0
2,677
#!/usr/bin/env python # coding=utf-8 """30. Digit fifth powers https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: > 1634 = 14 \+ 64 \+ 34 \+ 44 > 8208 = 84 \+ 24 \+ 04 \+ 84 > 9474 = 94 \+ 44 \+ 74 \+ 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """
openqt/algorithms
projecteuler/pe030-digit-fifth-powers.py
Python
gpl-3.0
507
/* Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <mosra@centrum.cz> This file is part of Kompas. Kompas is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, as published by the Free Software Foundation. Kompas 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 version 3 for more details. */ #include "FilesystemCache.h" #include "Utility/Directory.h" #include "Utility/Endianness.h" using namespace std; using namespace Kompas::Utility; using namespace Kompas::Core; namespace Kompas { namespace Plugins { PLUGIN_REGISTER(Kompas::Plugins::FilesystemCache, "cz.mosra.Kompas.Core.AbstractCache/0.2") bool FilesystemCache::initializeCache(const std::string& url) { if(!_url.empty()) finalizeCache(); _url = url; string _file = Directory::join(_url, "index.kps"); if(Directory::fileExists(_file)) { ifstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot open cache index" << _file; return false; } char* buffer = new char[4]; /* Check file signature */ file.get(buffer, 4); if(string(buffer) != "CCH") { Error() << "Unknown Kompas cache signature" << buffer << "in" << _file; return false; } /* Check file version */ file.read(buffer, 1); if(buffer[0] != 1) { Error() << "Unsupported Kompas cache version" << buffer[0] << "in" << _file; return false; } /* Block size */ file.read(buffer, 4); _blockSize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Block count */ file.read(buffer, 4); _maxBlockCount = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Count of all entries */ file.read(buffer, 4); unsigned int count = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); _entries.reserve(count); /* Populate the hash table with entries */ for(unsigned int i = 0; i != count; ++i) { if(!file.good()) { Error() << "Incomplete cache index" << _file; return false; } Entry* entry = new Entry(); /* SHA-1, file size, key size and usage */ file.read(reinterpret_cast<char*>(&entry->sha1), 20); file.read(buffer, 4); entry->size = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); file.read(buffer, 4); file.read(reinterpret_cast<char*>(&entry->usage), 1); /* Key */ unsigned int keySize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); char* key = new char[keySize]; file.read(key, keySize); entry->key = string(key, keySize); delete[] key; /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } /* Add entry to entries table */ set(entry); } file.close(); } Debug() << "Initialized cache with block size" << _blockSize << "B," << _maxBlockCount << "blocks, containing" << _entries.size() << "entries of size" << _usedBlockCount << "blocks."; return true; } void FilesystemCache::finalizeCache() { if(_url.empty()) return; string _file = Directory::join(_url, "index.kps"); Directory::mkpath(Directory::path(_file)); ofstream file(_file.c_str(), ios::binary); if(!file.good()) { Error() << "Cannot write cache index" << _file; /* Avoid memory leak */ for(unordered_map<string, Entry*>::const_iterator it = _entries.begin(); it != _entries.end(); ++it) delete it->second; return; } unsigned int buffer; /* Write file signature, version, block size, block count and entry count */ file.write("CCH", 3); file.write("\1", 1); buffer = Endianness::littleEndian(static_cast<unsigned int>(_blockSize)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_maxBlockCount)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_entries.size())); file.write(reinterpret_cast<const char*>(&buffer), 4); /* Foreach all entries and write them to index */ if(_position != 0) { Entry* entry = _position; do { file.write(reinterpret_cast<const char*>(&entry->sha1), Sha1::DigestSize); buffer = Endianness::littleEndian<unsigned int>(entry->size); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian<unsigned int>(entry->key.size()); file.write(reinterpret_cast<const char*>(&buffer), 4); file.write(reinterpret_cast<const char*>(&entry->usage), 1); file.write(entry->key.c_str(), entry->key.size()); entry = entry->next; delete entry->previous; } while(entry != _position); } file.close(); _position = 0; _usedBlockCount = 0; _entries.clear(); _files.clear(); _url.clear(); } void FilesystemCache::setBlockSize(size_t size) { _blockSize = size; if(_entries.size() == 0) return; /* Rebuild files map */ _files.clear(); _usedBlockCount = 0; Entry* entry = _position; do { /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } entry = entry->next; } while(entry != _position); } void FilesystemCache::purge() { Debug() << "Cleaning cache."; for(unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.begin(); it != _files.end(); ++it) Directory::rm(fileUrl(it->first)); _entries.clear(); _files.clear(); _position = 0; _usedBlockCount = 0; optimize(); } void FilesystemCache::optimize() { size_t orphanEntryCount = 0; size_t orphanFileCount = 0; size_t orphanDirectoryCount = 0; /* Remove entries without files */ if(_position != 0) { Entry* entry = _position; do { Entry* next = entry->next; /* If the file doesn't exist, remove entry */ if(!Directory::fileExists(fileUrl(entry->sha1))) { ++orphanEntryCount; remove(_entries.find(entry->key)); } entry = next; } while(_position == 0 || entry != _position); } /* Delete files which are not in the file table */ Directory d(_url, Directory::SkipDotAndDotDot); for(Directory::const_iterator it = d.begin(); it != d.end(); ++it) { if(*it == "index.kps") continue; /* Subdirectory, open it and look */ if(it->size() == 2) { string subdir = Directory::join(_url, *it); bool used = false; Directory sd(subdir, Directory::SkipDotAndDotDot); /* Remove unused files */ for(Directory::const_iterator sit = sd.begin(); sit != sd.end(); ++sit) { if(sit->size() == 38) { Sha1::Digest sha1 = Sha1::Digest::fromHexString(*it + *sit); if(sha1 != Sha1::Digest() && _files.find(sha1) == _files.end()) { if(Directory::rm(Directory::join(subdir, *sit))) ++orphanFileCount; continue; } } used = true; } if(!used) { if(Directory::rm(subdir)) ++orphanDirectoryCount; } } } Debug() << "Optimization removed" << orphanEntryCount << "orphan entries," << orphanFileCount << "orphan files and" << orphanDirectoryCount << "orphan directories."; } string FilesystemCache::get(const std::string& key) { ++_getCount; /* Find the key in entry table */ unordered_map<string, Entry*>::iterator eit = _entries.find(key); if(eit == _entries.end()) { Debug() << "Cache miss."; return string(); } Entry* entry = eit->second; /* Hash found, open the file */ string _file = fileUrl(entry->sha1); ifstream file(_file, ios::binary); if(!file.is_open()) { Error() << "Cannot open cached file" << _file; return string(); } /* Increase usage count and return file contents */ ++entry->usage; char* buffer = new char[entry->size]; file.read(buffer, entry->size); string s(buffer, entry->size); delete[] buffer; ++_hitCount; Debug() << "Retrieved entry" << entry->sha1.hexString() << "from cache. Hit rate:" << ((double) _hitCount)/_getCount; return s; } bool FilesystemCache::set(const std::string& key, const std::string& data) { if(_url.empty()) return false; /* Hash of the data */ Sha1::Digest sha1 = Sha1::digest(data); /* Add the entry */ Entry* entry = new Entry(); entry->key = key; entry->sha1 = sha1; entry->size = data.size(); entry->usage = 0; /* Find the hash in file table, if it exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(sha1); if(it != _files.end()) { ++it->second; Debug() << "Entry" << sha1.hexString() << "already exists in cache."; /* If it doesn't exists, prepare free space and insert it */ } else { if(!reserveSpace(data.size())) return false; _usedBlockCount += blockCount(data.size()); _files.insert(pair<Sha1::Digest, unsigned int>(sha1, 1u)); if(!Directory::mkpath(filePath(sha1))) return false; string _file = fileUrl(sha1); ofstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot write cache file" << _file; return false; } file.write(data.c_str(), data.size()); file.close(); Debug() << "Added entry" << sha1.hexString() << "to cache."; } set(entry); return true; } void FilesystemCache::set(Entry* entry) { /* Find the key in entry table and remove it if it already exists */ unordered_map<string, Entry*>::iterator eit = _entries.find(entry->key); if(eit != _entries.end()) remove(eit); /* First item in the cache, initialize circular linked list */ if(_position == 0) { entry->next = entry; entry->previous = entry; _position = entry; } else { entry->next = _position; entry->previous = _position->previous; _position->previous->next = entry; _position->previous = entry; } _entries.insert(pair<string, Entry*>(entry->key, entry)); } void FilesystemCache::remove(const unordered_map<string, Entry*>::iterator& eit) { Entry* entry = eit->second; /* Disconnect the entry from circular linked list and remove it from the table */ if(entry->next == entry) _position = 0; else { entry->next->previous = entry->previous; entry->previous->next = entry->next; if(_position == entry) _position = _position->next; } _entries.erase(eit); /* Find the hash in file table, decrease usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); /* If the file is not used anymore, remove it and decrease used size */ if(it != _files.end() && --it->second == 0) { Directory::rm(fileUrl(entry->sha1)); Directory::rm(filePath(entry->sha1)); _files.erase(it); _usedBlockCount -= blockCount(entry->size); } Debug() << "Removed entry" << entry->sha1.hexString() << "from cache, freed" << blockCount(entry->size) << "blocks."; delete entry; } bool FilesystemCache::reserveSpace(int required) { /* If we need more space than is available, don't do anything */ if(blockCount(required) > _maxBlockCount) { Error() << "Cannot reserve" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return false; } /* Go through the cycle and exponentially decrease usage count */ while(_usedBlockCount+blockCount(required) > _maxBlockCount) { _position->usage >>= 1; /* If the usage decreased to zero, remove the entry */ if(_position->usage == 0) remove(_entries.find(_position->key)); /* Otherwise advance to next entry */ else _position = _position->next; } Debug() << "Reserved" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return true; } string FilesystemCache::filePath(const Sha1::Digest& sha1) const { return Directory::join(_url, sha1.hexString().substr(0, 2)); } string FilesystemCache::fileUrl(const Sha1::Digest& sha1) const { return Directory::join(filePath(sha1), sha1.hexString().substr(2)); } }}
mosra/kompas-plugins
src/FilesystemCache/FilesystemCache.cpp
C++
gpl-3.0
13,964
package org.elsys.InternetProgramming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServerHandler { private Socket socket; public ServerHandler(String serverHost, int serverPort) { try { this.socket = new Socket(serverHost, serverPort); } catch (IOException e) { e.printStackTrace(); } } public void sendDateToServer(String date) { try { final OutputStream outputStream = this.socket.getOutputStream(); final PrintWriter out = new PrintWriter(outputStream); out.println(date); out.flush(); } catch (IOException e) { e.printStackTrace(); } } public int getCountFromServer() { try { final InputStream inputStream = this.socket.getInputStream(); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader reader = new BufferedReader(inputStreamReader); final String line = reader.readLine(); final int result = Integer.parseInt(line); return result; } catch (IOException e) { e.printStackTrace(); } return 0; } public void closeConnection() { try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
edudev/internet_programming
Homework2/workspace/DateFormatterClient/src/org/elsys/InternetProgramming/ServerHandler.java
Java
gpl-3.0
1,328
import sys, math from test import goertzel import wave import pyaudio import Queue import numpy as np if len(sys.argv) < 2: print "Usage: %s <filename> " % sys.argv[0] sys.exit(1) filename = sys.argv[1] w = wave.open(filename) fs = w.getframerate() width = w.getsampwidth() chunkDuration = .2 #.2 second chunks chunk = int(chunkDuration*fs) window = np.blackman(chunk) p = pyaudio.PyAudio() stream = p.open(format = p.get_format_from_width(w.getsampwidth()), channels = w.getnchannels(),rate = fs, output=True) #read .2 second chunk data = w.readframes(chunk) chunk_data = [] #find the frequencies of each chunk print "Running calculations on wav file" num = 0 while data != '': print "Calculating Chunk " + str(num) stream.write(data) indata = np.array(wave.struct.unpack("%dh"%(len(data)/width),\ data)) freqs , results = goertzel(indata,fs, (1036,1058), (1567,1569), (2082,2104)) chunk_data.append((freqs,results)) data = w.readframes(chunk) num+=.2 stream.close() p.terminate() #finished getting data from chunks, now to parse the data hi = [] lo = [] mid = [] #average first second of audio to get frequency baselines for i in range (5): a = chunk_data[i][0] b = chunk_data[i][1] for j in range(len(a)): if a[j] > 1700: hi.append(b[j]) elif a[j] < 1300: lo.append(b[j]) else: mid.append(b[j]) hi_average = sum(hi)/float(len(hi)) lo_average = sum(lo)/float(len(lo)) mid_average = sum(mid)/float(len(mid)) """ Determine the frequency in each .2 second chunk that has the highest amplitude increase from its average, then determine the frequency of that second of data by the median frequency of its 5 chunks """ #looks for start signal in last 3 seconds of audio def signal_found(arr): lst = arr[-15:] first = 0 second = 0 third = 0 for i in range(0,5): if lst[i]=="mid": first += 1 for i in range(5,10): if lst[i]=="mid": second += 1 for i in range(10,15): if lst[i]=="mid": third += 1 if first >= 5 and second >= 5 and third >= 5: return True else: return False #gets freq of 1 second of audio def get_freq(arr): lo_count = 0 hi_count = 0 mid_count = 0 for i in arr: if i=="lo": lo_count+=1 if i=="hi": hi_count+=1 if i=="mid": mid_count+=1 if mid_count > hi_count and mid_count > lo_count: return 2 if lo_count>hi_count: return 0 else: return 1 start = False freq_list = [] offset = 0 bits = [] for i in range(5,len(chunk_data)): a = chunk_data[i][0] b = chunk_data[i][1] hi_amp = [] lo_amp = [] mid_amp = [] #get averages for each freq for j in range(len(a)): if a[j] > 1700: hi_amp.append(b[j]) elif a[j] < 1300: lo_amp.append(b[j]) else: mid_amp.append(b[j]) hi_av = sum(hi_amp)/float(len(hi_amp)) lo_av = sum(lo_amp)/float(len(lo_amp)) mid_av = sum(mid_amp)/float(len(mid_amp)) #get freq of this chunk diff = [lo_av-lo_average,mid_av-mid_average,hi_av-hi_average] index = diff.index(max(diff)) if(index==0): freq_list.append("lo") if(index==1): freq_list.append("mid") if(index==2): freq_list.append("hi") print(freq_list[len(freq_list)-1]) if len(freq_list) > 5: if start: if len(freq_list)%5 == offset: bit = get_freq(freq_list[-5:]) if bit != 2: bits.append(bit) else: print "Stop Signal Detected" break elif len(freq_list) >= 15: if signal_found(freq_list): print "signal found" start = True offset = len(freq_list)%5 print bits
jloloew/AirBridge
parse.py
Python
gpl-3.0
3,509
// Decompiled with JetBrains decompiler // Type: StartupSceneAnimDriver // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll using System.Collections; using System.Diagnostics; using UnityEngine; public class StartupSceneAnimDriver : MonoBehaviour { public WBSpriteText LoadingString; public StartupSceneAnimDriver() { base.\u002Ector(); } [DebuggerHidden] private IEnumerator Start() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new StartupSceneAnimDriver.\u003CStart\u003Ec__Iterator95() { \u003C\u003Ef__this = this }; } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/Assembly-CSharp/StartupSceneAnimDriver.cs
C#
gpl-3.0
859
using System; using System.Collections.Generic; using System.Linq; using Minedrink_UWP.View; using Windows.ApplicationModel; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; using System.Diagnostics; using Windows.ApplicationModel.Core; using Windows.Networking; using Minedrink_UWP.Model; using Windows.Networking.Connectivity; using Windows.Networking.Sockets; using System.IO; using Windows.Storage.Streams; using System.Threading.Tasks; // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板 namespace Minedrink_UWP { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public Rect TogglePaneButtonRect { get; private set; } private bool isPaddingAdd = false; private List<NavMenuItem> navlist = new List<NavMenuItem>( new[] { new NavMenuItem() { Symbol = Symbol.Globe, Label = "总览", DestPage = typeof(OverviewPage), }, new NavMenuItem() { Symbol = Symbol.Admin, Label = "配置", DestPage = typeof(ConfigPage), }, new NavMenuItem() { Symbol = Symbol.PhoneBook, Label = "监控", DestPage = typeof(MonitorPage), } }); public static MainPage Current = null; public MainPage() { this.InitializeComponent(); this.Loaded += (sender, args) => { Current = this; this.CheckTogglePaneButtonSizeChanged(); var titleBar = Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar; titleBar.IsVisibleChanged += TitleBar_IsVisibleChanged; }; this.RootSplitView.RegisterPropertyChangedCallback(SplitView.DisplayModeProperty, (s, a) => { //确保当SplitView的显示模式改变时,更新TogglePaneButton的尺寸 this.CheckTogglePaneButtonSizeChanged(); }); SystemNavigationManager.GetForCurrentView().BackRequested += SyatemNavigationMaganger_BackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; NavMenuList.ItemsSource = navlist; } private void SyatemNavigationMaganger_BackRequested(object sender, BackRequestedEventArgs e) { bool handle = e.Handled; this.BackRequested(ref handle); e.Handled = handle; } /// <summary> /// 处理返回按键 /// </summary> /// <param name="handle"></param> private void BackRequested(ref bool handle) { if (this.AppFrame == null) { return; } if (this.AppFrame.CanGoBack && !handle) { handle = true; this.AppFrame.GoBack(); } } /// <summary> /// 当窗口标题栏可见性改变时调用,例如Loading完成或进入平板模式, /// 确保标题栏和App内容间的top padding正确 /// Invoked when window title bar visibility changes, such as after loading or in tablet mode /// Ensures correct padding at window top, between title bar and app content /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void TitleBar_IsVisibleChanged(Windows.ApplicationModel.Core.CoreApplicationViewTitleBar sender, object args) { if (!this.isPaddingAdd && sender.IsVisible) { //在标题和内容间增加额外的Padding double extraPadding = (Double)App.Current.Resources["DesktopWindowTopPadding"]; this.isPaddingAdd = true; Thickness margin = NavMenuList.Margin; NavMenuList.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = AppFrame.Margin; //AppFrame.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = TogglePaneButton.Margin; TogglePaneButton.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); } } /// <summary> /// Check for the conditions where the navigation pane does not occupy the space under the floating /// hamburger button and trigger the event. /// </summary> private void CheckTogglePaneButtonSizeChanged() { if (RootSplitView.DisplayMode == SplitViewDisplayMode.Inline || RootSplitView.DisplayMode == SplitViewDisplayMode.Overlay) { var transform = this.TogglePaneButton.TransformToVisual(this); var rect = transform.TransformBounds(new Rect(0, 0, this.TogglePaneButton.ActualWidth, this.TogglePaneButton.ActualHeight)); this.TogglePaneButtonRect = rect; } else { this.TogglePaneButtonRect = new Rect(); } var handler = this.TogglePaneButtonRectChanged; if (handler != null) { // handler(this, this.TogglePaneButtonRect); handler.DynamicInvoke(this, this.TogglePaneButtonRect); } } //private void MainPage_Loaded(object sender, RoutedEventArgs e) //{ // throw new NotImplementedException(); //} public Frame AppFrame { get { return this.frame; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainPage_KeyDown(object sender, KeyRoutedEventArgs e) { FocusNavigationDirection direction = FocusNavigationDirection.None; switch (e.Key) { case Windows.System.VirtualKey.Left: case Windows.System.VirtualKey.GamepadDPadLeft: case Windows.System.VirtualKey.GamepadLeftThumbstickLeft: case Windows.System.VirtualKey.NavigationLeft: direction = FocusNavigationDirection.Left; break; case Windows.System.VirtualKey.Right: case Windows.System.VirtualKey.GamepadDPadRight: case Windows.System.VirtualKey.GamepadLeftThumbstickRight: case Windows.System.VirtualKey.NavigationRight: direction = FocusNavigationDirection.Right; break; case Windows.System.VirtualKey.Up: case Windows.System.VirtualKey.GamepadDPadUp: case Windows.System.VirtualKey.GamepadLeftThumbstickUp: case Windows.System.VirtualKey.NavigationUp: direction = FocusNavigationDirection.Up; break; case Windows.System.VirtualKey.Down: case Windows.System.VirtualKey.GamepadDPadDown: case Windows.System.VirtualKey.GamepadLeftThumbstickDown: case Windows.System.VirtualKey.NavigationDown: direction = FocusNavigationDirection.Down; break; } if (direction != FocusNavigationDirection.None) { var contorl = FocusManager.FindNextFocusableElement(direction) as Control; if (contorl != null) { contorl.Focus(FocusState.Keyboard); e.Handled = true; } } } /// <summary> /// Hides divider when nav pane is closed. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void RootSplitView_PaneClosed(SplitView sender, object args) { NavPaneDivider.Visibility = Visibility.Collapsed; // Prevent focus from moving to elements when they're not visible on screen FeedbackNavPaneButton.IsTabStop = false; SettingsNavPaneButton.IsTabStop = false; } /// <summary> ///通过使用每个项目的关联标签在每个容器上设置AutomationProperties.Name来启用每个导航菜单项上的辅助功能。 /// Enable accessibility on each nav menu item by setting the AutomationProperties.Name on each container /// using the associated Label of each item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void NavMenuList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { if (!args.InRecycleQueue && args.Item != null && args.Item is NavMenuItem) { args.ItemContainer.SetValue(AutomationProperties.NameProperty, ((NavMenuItem)args.Item).Label); } else { args.ItemContainer.ClearValue(AutomationProperties.NameProperty); } } /// <summary> /// 选中导航按钮项后调用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NavMenuList_ItemInvoked(object sender, ListViewItem e) { foreach (var i in navlist) { i.IsSelected = false; } var item = (NavMenuItem)((NavMenuListView)sender).ItemFromContainer(e); if (item != null) { item.IsSelected = true; if (item.DestPage != null && item.DestPage != this.AppFrame.CurrentSourcePageType) { this.AppFrame.Navigate(item.DestPage, item.Arguments); } } } public void NavMenuList_Init() { navlist.First().IsSelected = true; } /// <summary> /// Ensures the nav menu reflects reality when navigation is triggered outside of /// the nav menu buttons.确保导航菜单在导航按钮之外触发正确 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frame_Navigating(object sender, NavigatingCancelEventArgs e) { //处理返回逻辑 if (e.NavigationMode == NavigationMode.Back) { var item = (from p in this.navlist where p.DestPage == e.SourcePageType select p).SingleOrDefault(); if (item == null && this.AppFrame.BackStackDepth > 0) { // 在页面进入到子页面的情况下,我们将返回到BackStack中最近的一级导航菜单项 // In cases where a page drills into sub-pages then we'll highlight the most recent // navigation menu item that appears in the BackStack foreach (var entry in this.AppFrame.BackStack.Reverse()) { item = (from p in this.navlist where p.DestPage == entry.SourcePageType select p).SingleOrDefault(); if (item != null) { break; } } } foreach (var i in navlist) { i.IsSelected = false; } if (item != null) { item.IsSelected = true; } var container = (ListViewItem)NavMenuList.ContainerFromItem(item); //当更新项目的选择状态时,它阻止它进行键盘焦点。 如果用户正在通过键盘调用后退按钮,导致所选择的导航菜单项目改变,则焦点将保留在后退按钮上。 //While updating the selection state of the item prevent it from taking keyboard focus. //If a user is invoking the back button via the keyboard causing the selected nav menu item to change then focus will remain on the back button. if (container != null) { container.IsTabStop = false; } NavMenuList.SetSelectedItem(container); if (container != null) { container.IsTabStop = true; } } } private void TogglePaneButton_Unchecked(object sender, RoutedEventArgs e) { this.CheckTogglePaneButtonSizeChanged(); } private void TogglePaneButton_Checked(object sender, RoutedEventArgs e) { NavPaneDivider.Visibility = Visibility.Visible; this.CheckTogglePaneButtonSizeChanged(); FeedbackNavPaneButton.IsTabStop = true; SettingsNavPaneButton.IsTabStop = true; } //private async void StartListener() //{ // //覆盖这里的监听器是安全的,因为它将被删除,一旦它的所有引用都消失了。 // //然而,在许多情况下,这是一个危险的模式,半随机地覆盖数据(每次用户点击按钮), // //所以我们在这里阻止它。 // if (CoreApplication.Properties.ContainsKey("listener")) // { // Debug.WriteLine("监听器已存在"); // return; // } // CoreApplication.Properties.Remove("serverAddress"); // CoreApplication.Properties.Remove("adapter"); // //LocalHostItem selectedLocalHost = null; // //selectedLocalHost = new LocalHostItem(NetworkInformation.GetHostNames().First()); // //Debug.WriteLine("建立地址:" + selectedLocalHost); // //用户选择了一个地址。 为演示目的,我们确保连接将使用相同的地址。 // //CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); // StreamSocketListener listener = new StreamSocketListener(); // listener.ConnectionReceived += Listener_ConnectionReceived; // //如果需要,调整监听器的控制选项,然后再进行绑定操作。这些选项将被自动应用到连接的StreamSockets, // //这些连接是由传入的连接引起的(即作为ConnectionReceived事件处理程序的参数传递的)。 // //参考StreamSocketListenerControl类'MSDN 有关控制选项的完整列表的文档。 // listener.Control.KeepAlive = false; // //保存Socket,以便随后使用 // CoreApplication.Properties.Add("listener", listener); // //开始监听操作 // try // { // await listener.BindServiceNameAsync("8080"); // Debug.WriteLine("Listening......"); // } // catch (Exception) // { // throw; // } //} //private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) //{ // //DataReader reader = new DataReader(args.Socket.InputStream); // //try // //{ // // while (true) // // { // // // Read first 4 bytes (length of the subsequent string). // // uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); // // if (sizeFieldCount != sizeof(uint)) // // { // // // The underlying socket was closed before we were able to read the whole data. // // return; // // } // // // Read the string. // // uint stringLength = reader.ReadUInt32(); // // uint actualStringLength = await reader.LoadAsync(stringLength); // // if (stringLength != actualStringLength) // // { // // // The underlying socket was closed before we were able to read the whole data. // // return; // // } // // } // //} // //catch (Exception exception) // //{ // //} // //从远程客户端读取信息 // Stream inStream = args.Socket.InputStream.AsStreamForRead(); // StreamReader reader = new StreamReader(inStream); // //将信息送回 // Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); // StreamWriter writer = new StreamWriter(outStream); // while (true) // { // string inStr = await reader.ReadLineAsync(); // string outStr = null; // Debug.WriteLine("IN:" + inStr); // if (inStr.StartsWith("#")) // { // string codeStr = inStr.Substring(0, 8); // CommCode code = CommHandle.StringConvertToEnum(codeStr); // switch (code) // { // case CommCode.TCPCONN: // outStr = TCPCOMMHandle(); // break; // case CommCode.AS: // break; // case CommCode.ERROR: // Debug.WriteLine("错误的指令:" + codeStr); // break; // default: // break; // } // } // //TODO:断开连接后会引发System.NullReferenceException // if (outStr != null) // { // await writer.WriteLineAsync(inStr); // await writer.FlushAsync(); // } // //await Task.Delay(100); // } //} /// <summary> /// An event to notify listeners when the hamburger button may occlude other content in the app. /// The custom "PageHeader" user control is using this. /// </summary> public event TypedEventHandler<MainPage, Rect> TogglePaneButtonRectChanged; /// <summary> /// Public method to allow pages to open SplitView's pane. /// Used for custom app shortcuts like navigating left from page's left-most item /// </summary> public void OpenNavePane() { TogglePaneButton.IsChecked = true; NavPaneDivider.Visibility = Visibility.Visible; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // Save application state and stop any background activity deferral.Complete(); } private string TCPCOMMHandle() { string result = "#TCPOK**"; return result; } } public enum NotifyType { StatusMessage, ErrorMessage }; //private void UpdateStatus(string strMessage, NotifyType type) //{ // switch (type) // { // case NotifyType.StatusMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green); // break; // case NotifyType.ErrorMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red); // break; // } // StatusBlock.Text = strMessage; // // Collapse the StatusBlock if it has no text to conserve real estate. // StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed; // if (StatusBlock.Text != String.Empty) // { // StatusBorder.Visibility = Visibility.Visible; // StatusPanel.Visibility = Visibility.Visible; // } // else // { // StatusBorder.Visibility = Visibility.Collapsed; // StatusPanel.Visibility = Visibility.Collapsed; // } //} }
SongOfSaya/Minedrink
Minedrink_UWP/Minedrink_UWP/MainPage.xaml.cs
C#
gpl-3.0
21,385
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for C++ expressions. // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/TemplateDeduction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/STLExtras.h" using namespace clang; using namespace sema; ParsedType Sema::getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectTypePtr, bool EnteringContext) { // Determine where to perform name lookup. // FIXME: This area of the standard is very messy, and the current // wording is rather unclear about which scopes we search for the // destructor name; see core issues 399 and 555. Issue 399 in // particular shows where the current description of destructor name // lookup is completely out of line with existing practice, e.g., // this appears to be ill-formed: // // namespace N { // template <typename T> struct S { // ~S(); // }; // } // // void f(N::S<int>* s) { // s->N::S<int>::~S(); // } // // See also PR6358 and PR6359. // For this reason, we're currently only doing the C++03 version of this // code; the C++0x version has to wait until we get a proper spec. QualType SearchType; DeclContext *LookupCtx = 0; bool isDependent = false; bool LookInScope = false; // If we have an object type, it's because we are in a // pseudo-destructor-expression or a member access expression, and // we know what type we're looking for. if (ObjectTypePtr) SearchType = GetTypeFromParser(ObjectTypePtr); if (SS.isSet()) { NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); bool AlreadySearched = false; bool LookAtPrefix = true; // C++ [basic.lookup.qual]p6: // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, // the type-names are looked up as types in the scope designated by the // nested-name-specifier. In a qualified-id of the form: // // ::[opt] nested-name-specifier ̃ class-name // // where the nested-name-specifier designates a namespace scope, and in // a qualified-id of the form: // // ::opt nested-name-specifier class-name :: ̃ class-name // // the class-names are looked up as types in the scope designated by // the nested-name-specifier. // // Here, we check the first case (completely) and determine whether the // code below is permitted to look at the prefix of the // nested-name-specifier. DeclContext *DC = computeDeclContext(SS, EnteringContext); if (DC && DC->isFileContext()) { AlreadySearched = true; LookupCtx = DC; isDependent = false; } else if (DC && isa<CXXRecordDecl>(DC)) LookAtPrefix = false; // The second case from the C++03 rules quoted further above. NestedNameSpecifier *Prefix = 0; if (AlreadySearched) { // Nothing left to do. } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { CXXScopeSpec PrefixSS; PrefixSS.setScopeRep(Prefix); LookupCtx = computeDeclContext(PrefixSS, EnteringContext); isDependent = isDependentScopeSpecifier(PrefixSS); } else if (ObjectTypePtr) { LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); } else { LookupCtx = computeDeclContext(SS, EnteringContext); isDependent = LookupCtx && LookupCtx->isDependentContext(); } LookInScope = false; } else if (ObjectTypePtr) { // C++ [basic.lookup.classref]p3: // If the unqualified-id is ~type-name, the type-name is looked up // in the context of the entire postfix-expression. If the type T // of the object expression is of a class type C, the type-name is // also looked up in the scope of class C. At least one of the // lookups shall find a name that refers to (possibly // cv-qualified) T. LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); assert((isDependent || !SearchType->isIncompleteType()) && "Caller should have completed object type"); LookInScope = true; } else { // Perform lookup into the current scope (only). LookInScope = true; } LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); for (unsigned Step = 0; Step != 2; ++Step) { // Look for the name first in the computed lookup context (if we // have one) and, if that fails to find a match, in the sope (if // we're allowed to look there). Found.clear(); if (Step == 0 && LookupCtx) LookupQualifiedName(Found, LookupCtx); else if (Step == 1 && LookInScope && S) LookupName(Found, S); else continue; // FIXME: Should we be suppressing ambiguities here? if (Found.isAmbiguous()) return ParsedType(); if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { QualType T = Context.getTypeDeclType(Type); if (SearchType.isNull() || SearchType->isDependentType() || Context.hasSameUnqualifiedType(T, SearchType)) { // We found our type! return ParsedType::make(T); } } // If the name that we found is a class template name, and it is // the same name as the template name in the last part of the // nested-name-specifier (if present) or the object type, then // this is the destructor for that class. // FIXME: This is a workaround until we get real drafting for core // issue 399, for which there isn't even an obvious direction. if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { QualType MemberOfType; if (SS.isSet()) { if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { // Figure out the type of the context, if it has one. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) MemberOfType = Context.getTypeDeclType(Record); } } if (MemberOfType.isNull()) MemberOfType = SearchType; if (MemberOfType.isNull()) continue; // We're referring into a class template specialization. If the // class template we found is the same as the template being // specialized, we found what we are looking for. if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { if (Spec->getSpecializedTemplate()->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); } continue; } // We're referring to an unresolved class template // specialization. Determine whether we class template we found // is the same as the template being specialized or, if we don't // know which template is being specialized, that it at least // has the same name. if (const TemplateSpecializationType *SpecType = MemberOfType->getAs<TemplateSpecializationType>()) { TemplateName SpecName = SpecType->getTemplateName(); // The class template we found is the same template being // specialized. if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); continue; } // The class template we found has the same name as the // (dependent) template name being specialized. if (DependentTemplateName *DepTemplate = SpecName.getAsDependentTemplateName()) { if (DepTemplate->isIdentifier() && DepTemplate->getIdentifier() == Template->getIdentifier()) return ParsedType::make(MemberOfType); continue; } } } } if (isDependent) { // We didn't find our type, but that's okay: it's dependent // anyway. NestedNameSpecifier *NNS = 0; SourceRange Range; if (SS.isSet()) { NNS = (NestedNameSpecifier *)SS.getScopeRep(); Range = SourceRange(SS.getRange().getBegin(), NameLoc); } else { NNS = NestedNameSpecifier::Create(Context, &II); Range = SourceRange(NameLoc); } QualType T = CheckTypenameType(ETK_None, NNS, II, SourceLocation(), Range, NameLoc); return ParsedType::make(T); } if (ObjectTypePtr) Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) << &II; else Diag(NameLoc, diag::err_destructor_class_name); return ParsedType(); } /// \brief Build a C++ typeid expression with a type operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc) { // C++ [expr.typeid]p4: // The top-level cv-qualifiers of the lvalue expression or the type-id // that is the operand of typeid are always ignored. // If the type of the type-id is a class type or a reference to a class // type, the class shall be completely-defined. Qualifiers Quals; QualType T = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), Quals); if (T->getAs<RecordType>() && RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) return ExprError(); return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, SourceRange(TypeidLoc, RParenLoc))); } /// \brief Build a C++ typeid expression with an expression operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *E, SourceLocation RParenLoc) { bool isUnevaluatedOperand = true; if (E && !E->isTypeDependent()) { QualType T = E->getType(); if (const RecordType *RecordT = T->getAs<RecordType>()) { CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); // C++ [expr.typeid]p3: // [...] If the type of the expression is a class type, the class // shall be completely-defined. if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) return ExprError(); // C++ [expr.typeid]p3: // When typeid is applied to an expression other than an glvalue of a // polymorphic class type [...] [the] expression is an unevaluated // operand. [...] if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { isUnevaluatedOperand = false; // We require a vtable to query the type at run time. MarkVTableUsed(TypeidLoc, RecordD); } } // C++ [expr.typeid]p4: // [...] If the type of the type-id is a reference to a possibly // cv-qualified type, the result of the typeid expression refers to a // std::type_info object representing the cv-unqualified referenced // type. Qualifiers Quals; QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); if (!Context.hasSameType(T, UnqualT)) { T = UnqualT; ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)); } } // If this is an unevaluated operand, clear out the set of // declaration references we have been computing and eliminate any // temporaries introduced in its computation. if (isUnevaluatedOperand) ExprEvalContexts.back().Context = Unevaluated; return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, SourceRange(TypeidLoc, RParenLoc))); } /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); ExprResult Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { // Find the std::type_info type. if (!StdNamespace) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); LookupQualifiedName(R, getStdNamespace()); RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); if (!TypeInfoRecordDecl) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); if (isType) { // The operand is a type; handle it as such. TypeSourceInfo *TInfo = 0; QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), &TInfo); if (T.isNull()) return ExprError(); if (!TInfo) TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); } // The operand is an expression. return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); } /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { assert((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"); return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc)); } /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); } /// ActOnCXXThrow - Parse throw expressions. ExprResult Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) return ExprError(); return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); } /// CheckCXXThrowOperand - Validate the operand of a throw. bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { // C++ [except.throw]p3: // A throw-expression initializes a temporary object, called the exception // object, the type of which is determined by removing any top-level // cv-qualifiers from the static type of the operand of throw and adjusting // the type from "array of T" or "function returning T" to "pointer to T" // or "pointer to function returning T", [...] if (E->getType().hasQualifiers()) ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, CastCategory(E)); DefaultFunctionArrayConversion(E); // If the type of the exception would be an incomplete type or a pointer // to an incomplete type other than (cv) void the program is ill-formed. QualType Ty = E->getType(); bool isPointer = false; if (const PointerType* Ptr = Ty->getAs<PointerType>()) { Ty = Ptr->getPointeeType(); isPointer = true; } if (!isPointer || !Ty->isVoidType()) { if (RequireCompleteType(ThrowLoc, Ty, PDiag(isPointer ? diag::err_throw_incomplete_ptr : diag::err_throw_incomplete) << E->getSourceRange())) return true; if (RequireNonAbstractType(ThrowLoc, E->getType(), PDiag(diag::err_throw_abstract_type) << E->getSourceRange())) return true; } // Initialize the exception result. This implicitly weeds out // abstract types or types with inaccessible copy constructors. // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34. InitializedEntity Entity = InitializedEntity::InitializeException(ThrowLoc, E->getType(), /*NRVO=*/false); ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(), Owned(E)); if (Res.isInvalid()) return true; E = Res.takeAs<Expr>(); // If the exception has class type, we need additional handling. const RecordType *RecordTy = Ty->getAs<RecordType>(); if (!RecordTy) return false; CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); // If we are throwing a polymorphic class type or pointer thereof, // exception handling will make use of the vtable. MarkVTableUsed(ThrowLoc, RD); // If the class has a non-trivial destructor, we must be able to call it. if (RD->hasTrivialDestructor()) return false; CXXDestructorDecl *Destructor = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); if (!Destructor) return false; MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_exception) << Ty); return false; } ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { /// C++ 9.3.2: In the body of a non-static member function, the keyword this /// is a non-lvalue expression whose value is the address of the object for /// which the function is called. DeclContext *DC = getFunctionLevelDeclContext(); if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) if (MD->isInstance()) return Owned(new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context), /*isImplicit=*/false)); return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); } /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep, SourceLocation LParenLoc, MultiExprArg exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { if (!TypeRep) return ExprError(); TypeSourceInfo *TInfo; QualType Ty = GetTypeFromParser(TypeRep, &TInfo); if (!TInfo) TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); unsigned NumExprs = exprs.size(); Expr **Exprs = (Expr**)exprs.get(); SourceLocation TyBeginLoc = TypeRange.getBegin(); SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { exprs.release(); return Owned(CXXUnresolvedConstructExpr::Create(Context, TypeRange.getBegin(), Ty, LParenLoc, Exprs, NumExprs, RParenLoc)); } if (Ty->isArrayType()) return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange); if (!Ty->isVoidType() && RequireCompleteType(TyBeginLoc, Ty, PDiag(diag::err_invalid_incomplete_type_use) << FullRange)) return ExprError(); if (RequireNonAbstractType(TyBeginLoc, Ty, diag::err_allocation_of_abstract_type)) return ExprError(); // C++ [expr.type.conv]p1: // If the expression list is a single expression, the type conversion // expression is equivalent (in definedness, and if defined in meaning) to the // corresponding cast expression. // if (NumExprs == 1) { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath, /*FunctionalStyle=*/true)) return ExprError(); exprs.release(); return Owned(CXXFunctionalCastExpr::Create(Context, Ty.getNonLValueExprType(Context), TInfo, TyBeginLoc, Kind, Exprs[0], &BasePath, RParenLoc)); } if (Ty->isRecordType()) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); InitializationKind Kind = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), LParenLoc, RParenLoc) : InitializationKind::CreateValue(TypeRange.getBegin(), LParenLoc, RParenLoc); InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); // FIXME: Improve AST representation? return move(Result); } // C++ [expr.type.conv]p1: // If the expression list specifies more than a single value, the type shall // be a class with a suitably declared constructor. // if (NumExprs > 1) return ExprError(Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) << FullRange); assert(NumExprs == 0 && "Expected 0 expressions"); // C++ [expr.type.conv]p2: // The expression T(), where T is a simple-type-specifier for a non-array // complete object type or the (possibly cv-qualified) void type, creates an // rvalue of the specified type, which is value-initialized. // exprs.release(); return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc)); } /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: /// @code new (memory) int[size][4] @endcode /// or /// @code ::new Foo(23, "hello") @endcode /// For the interpretation of this heap of arguments, consult the base version. ExprResult Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { Expr *ArraySize = 0; // If the specified type is an array, unwrap it and save the expression. if (D.getNumTypeObjects() > 0 && D.getTypeObject(0).Kind == DeclaratorChunk::Array) { DeclaratorChunk &Chunk = D.getTypeObject(0); if (Chunk.Arr.hasStatic) return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) << D.getSourceRange()); if (!Chunk.Arr.NumElts) return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) << D.getSourceRange()); ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); D.DropFirstTypeObject(); } // Every dimension shall be of constant size. if (ArraySize) { for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) break; DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; if (Expr *NumElts = (Expr *)Array.NumElts) { if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && !NumElts->isIntegerConstantExpr(Context)) { Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) << NumElts->getSourceRange(); return ExprError(); } } } } //FIXME: Store TypeSourceInfo in CXXNew expression. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); QualType AllocType = TInfo->getType(); if (D.isInvalidType()) return ExprError(); SourceRange R = TInfo->getTypeLoc().getSourceRange(); return BuildCXXNew(StartLoc, UseGlobal, PlacementLParen, move(PlacementArgs), PlacementRParen, TypeIdParens, AllocType, D.getSourceRange().getBegin(), R, ArraySize, ConstructorLParen, move(ConstructorArgs), ConstructorRParen); } ExprResult Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, SourceLocation TypeLoc, SourceRange TypeRange, Expr *ArraySize, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) return ExprError(); // Per C++0x [expr.new]p5, the type being constructed may be a // typedef of an array type. if (!ArraySize) { if (const ConstantArrayType *Array = Context.getAsConstantArrayType(AllocType)) { ArraySize = IntegerLiteral::Create(Context, Array->getSize(), Context.getSizeType(), TypeRange.getEnd()); AllocType = Array->getElementType(); } } QualType ResultType = Context.getPointerType(AllocType); // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral // or enumeration type with a non-negative value." if (ArraySize && !ArraySize->isTypeDependent()) { QualType SizeType = ArraySize->getType(); ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, PDiag(diag::err_array_size_not_integral), PDiag(diag::err_array_size_incomplete_type) << ArraySize->getSourceRange(), PDiag(diag::err_array_size_explicit_conversion), PDiag(diag::note_array_size_conversion), PDiag(diag::err_array_size_ambiguous_conversion), PDiag(diag::note_array_size_conversion), PDiag(getLangOptions().CPlusPlus0x? 0 : diag::ext_array_size_conversion)); if (ConvertedSize.isInvalid()) return ExprError(); ArraySize = ConvertedSize.take(); SizeType = ArraySize->getType(); if (!SizeType->isIntegralOrEnumerationType()) return ExprError(); // Let's see if this is a constant < 0. If so, we reject it out of hand. // We don't care about special rules, so we tell the machinery it's not // evaluated - it gives us a result in more cases. if (!ArraySize->isValueDependent()) { llvm::APSInt Value; if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { if (Value < llvm::APSInt( llvm::APInt::getNullValue(Value.getBitWidth()), Value.isUnsigned())) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange()); if (!AllocType->isDependentType()) { unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { Diag(ArraySize->getSourceRange().getBegin(), diag::err_array_too_large) << Value.toString(10) << ArraySize->getSourceRange(); return ExprError(); } } } else if (TypeIdParens.isValid()) { // Can't have dynamic array size when the type-id is in parentheses. Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) << ArraySize->getSourceRange() << FixItHint::CreateRemoval(TypeIdParens.getBegin()) << FixItHint::CreateRemoval(TypeIdParens.getEnd()); TypeIdParens = SourceRange(); } } ImpCastExprToType(ArraySize, Context.getSizeType(), CK_IntegralCast); } FunctionDecl *OperatorNew = 0; FunctionDecl *OperatorDelete = 0; Expr **PlaceArgs = (Expr**)PlacementArgs.get(); unsigned NumPlaceArgs = PlacementArgs.size(); if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && FindAllocationFunctions(StartLoc, SourceRange(PlacementLParen, PlacementRParen), UseGlobal, AllocType, ArraySize, PlaceArgs, NumPlaceArgs, OperatorNew, OperatorDelete)) return ExprError(); llvm::SmallVector<Expr *, 8> AllPlaceArgs; if (OperatorNew) { // Add default arguments, if any. const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1, PlaceArgs, NumPlaceArgs, AllPlaceArgs, CallType)) return ExprError(); NumPlaceArgs = AllPlaceArgs.size(); if (NumPlaceArgs > 0) PlaceArgs = &AllPlaceArgs[0]; } bool Init = ConstructorLParen.isValid(); // --- Choosing a constructor --- CXXConstructorDecl *Constructor = 0; Expr **ConsArgs = (Expr**)ConstructorArgs.get(); unsigned NumConsArgs = ConstructorArgs.size(); ASTOwningVector<Expr*> ConvertedConstructorArgs(*this); // Array 'new' can't have any initializers. if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { SourceRange InitRange(ConsArgs[0]->getLocStart(), ConsArgs[NumConsArgs - 1]->getLocEnd()); Diag(StartLoc, diag::err_new_array_init_args) << InitRange; return ExprError(); } if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { // C++0x [expr.new]p15: // A new-expression that creates an object of type T initializes that // object as follows: InitializationKind Kind // - If the new-initializer is omitted, the object is default- // initialized (8.5); if no initialization is performed, // the object has indeterminate value = !Init? InitializationKind::CreateDefault(TypeLoc) // - Otherwise, the new-initializer is interpreted according to the // initialization rules of 8.5 for direct-initialization. : InitializationKind::CreateDirect(TypeLoc, ConstructorLParen, ConstructorRParen); InitializedEntity Entity = InitializedEntity::InitializeNew(StartLoc, AllocType); InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, move(ConstructorArgs)); if (FullInit.isInvalid()) return ExprError(); // FullInit is our initializer; walk through it to determine if it's a // constructor call, which CXXNewExpr handles directly. if (Expr *FullInitExpr = (Expr *)FullInit.get()) { if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) FullInitExpr = Binder->getSubExpr(); if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(FullInitExpr)) { Constructor = Construct->getConstructor(); for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), AEnd = Construct->arg_end(); A != AEnd; ++A) ConvertedConstructorArgs.push_back(A->Retain()); } else { // Take the converted initializer. ConvertedConstructorArgs.push_back(FullInit.release()); } } else { // No initialization required. } // Take the converted arguments and use them for the new expression. NumConsArgs = ConvertedConstructorArgs.size(); ConsArgs = (Expr **)ConvertedConstructorArgs.take(); } // Mark the new and delete operators as referenced. if (OperatorNew) MarkDeclarationReferenced(StartLoc, OperatorNew); if (OperatorDelete) MarkDeclarationReferenced(StartLoc, OperatorDelete); // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) PlacementArgs.release(); ConstructorArgs.release(); // FIXME: The TypeSourceInfo should also be included in CXXNewExpr. return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, TypeIdParens, ArraySize, Constructor, Init, ConsArgs, NumConsArgs, OperatorDelete, ResultType, StartLoc, Init ? ConstructorRParen : TypeRange.getEnd())); } /// CheckAllocatedType - Checks that a type is suitable as the allocated type /// in a new-expression. /// dimension off and stores the size expression in ArraySize. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R) { // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an // abstract class type or array thereof. if (AllocType->isFunctionType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 0 << R; else if (AllocType->isReferenceType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 1 << R; else if (!AllocType->isDependentType() && RequireCompleteType(Loc, AllocType, PDiag(diag::err_new_incomplete_type) << R)) return true; else if (RequireNonAbstractType(Loc, AllocType, diag::err_allocation_of_abstract_type)) return true; return false; } /// \brief Determine whether the given function is a non-placement /// deallocation function. static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { if (FD->isInvalidDecl()) return false; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) return Method->isUsualDeallocationFunction(); return ((FD->getOverloadedOperator() == OO_Delete || FD->getOverloadedOperator() == OO_Array_Delete) && FD->getNumParams() == 1); } /// FindAllocationFunctions - Finds the overloads of operator new and delete /// that are appropriate for the allocation. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, Expr **PlaceArgs, unsigned NumPlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete) { // --- Choosing an allocation function --- // C++ 5.3.4p8 - 14 & 18 // 1) If UseGlobal is true, only look in the global scope. Else, also look // in the scope of the allocated class. // 2) If an array size is given, look for operator new[], else look for // operator new. // 3) The first argument is always size_t. Append the arguments from the // placement form. llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); // We don't care about the actual value of this argument. // FIXME: Should the Sema create the expression and embed it in the syntax // tree? Or should the consumer just recalculate the value? IntegerLiteral Size(Context, llvm::APInt::getNullValue( Context.Target.getPointerWidth(0)), Context.getSizeType(), SourceLocation()); AllocArgs[0] = &Size; std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); // C++ [expr.new]p8: // If the allocated type is a non-array type, the allocation // function’s name is operator new and the deallocation function’s // name is operator delete. If the allocated type is an array // type, the allocation function’s name is operator new[] and the // deallocation function’s name is operator delete[]. DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_New : OO_New); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_Delete : OO_Delete); QualType AllocElemType = Context.getBaseElementType(AllocType); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *Record = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), Record, /*AllowMissing=*/true, OperatorNew)) return true; } if (!OperatorNew) { // Didn't find a member overload. Look for a global one. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), TUDecl, /*AllowMissing=*/false, OperatorNew)) return true; } // We don't need an operator delete if we're running under // -fno-exceptions. if (!getLangOptions().Exceptions) { OperatorDelete = 0; return false; } // FindAllocationOverload can change the passed in arguments, so we need to // copy them back. if (NumPlaceArgs > 0) std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); // C++ [expr.new]p19: // // If the new-expression begins with a unary :: operator, the // deallocation function’s name is looked up in the global // scope. Otherwise, if the allocated type is a class type T or an // array thereof, the deallocation function’s name is looked up in // the scope of T. If this lookup fails to find the name, or if // the allocated type is not a class type or array thereof, the // deallocation function’s name is looked up in the global scope. LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *RD = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); LookupQualifiedName(FoundDelete, RD); } if (FoundDelete.isAmbiguous()) return true; // FIXME: clean up expressions? if (FoundDelete.empty()) { DeclareGlobalNewDelete(); LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); } FoundDelete.suppressDiagnostics(); llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; if (NumPlaceArgs > 0) { // C++ [expr.new]p20: // A declaration of a placement deallocation function matches the // declaration of a placement allocation function if it has the // same number of parameters and, after parameter transformations // (8.3.5), all parameter types except the first are // identical. [...] // // To perform this comparison, we compute the function type that // the deallocation function should have, and use that type both // for template argument deduction and for comparison purposes. QualType ExpectedFunctionType; { const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); llvm::SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context.VoidPtrTy); for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) ArgTypes.push_back(Proto->getArgType(I)); ExpectedFunctionType = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), ArgTypes.size(), Proto->isVariadic(), 0, false, false, 0, 0, FunctionType::ExtInfo()); } for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { FunctionDecl *Fn = 0; if (FunctionTemplateDecl *FnTmpl = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { // Perform template argument deduction to try to match the // expected function type. TemplateDeductionInfo Info(Context, StartLoc); if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) continue; } else Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } else { // C++ [expr.new]p20: // [...] Any non-placement deallocation function matches a // non-placement allocation function. [...] for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) if (isNonPlacementDeallocationFunction(Fn)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } // C++ [expr.new]p20: // [...] If the lookup finds a single matching deallocation // function, that function will be called; otherwise, no // deallocation function will be called. if (Matches.size() == 1) { OperatorDelete = Matches[0].second; // C++0x [expr.new]p20: // If the lookup finds the two-parameter form of a usual // deallocation function (3.7.4.2) and that function, considered // as a placement deallocation function, would have been // selected as a match for the allocation function, the program // is ill-formed. if (NumPlaceArgs && getLangOptions().CPlusPlus0x && isNonPlacementDeallocationFunction(OperatorDelete)) { Diag(StartLoc, diag::err_placement_new_non_placement_delete) << SourceRange(PlaceArgs[0]->getLocStart(), PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); Diag(OperatorDelete->getLocation(), diag::note_previous_decl) << DeleteName; } else { CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), Matches[0].first); } } return false; } /// FindAllocationOverload - Find an fitting overload for the allocation /// function in the specified scope. bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, DeclarationName Name, Expr** Args, unsigned NumArgs, DeclContext *Ctx, bool AllowMissing, FunctionDecl *&Operator) { LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); LookupQualifiedName(R, Ctx); if (R.empty()) { if (AllowMissing) return false; return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; } if (R.isAmbiguous()) return true; R.suppressDiagnostics(); OverloadCandidateSet Candidates(StartLoc); for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); Alloc != AllocEnd; ++Alloc) { // Even member operator new/delete are implicitly treated as // static, so don't use AddMemberCandidate. NamedDecl *D = (*Alloc)->getUnderlyingDecl(); if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), /*ExplicitTemplateArgs=*/0, Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); continue; } FunctionDecl *Fn = cast<FunctionDecl>(D); AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); } // Do the resolution. OverloadCandidateSet::iterator Best; switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { case OR_Success: { // Got one! FunctionDecl *FnDecl = Best->Function; // The first argument is size_t, and the first parameter must be size_t, // too. This is checked on declaration and can be assumed. (It can't be // asserted on, though, since invalid decls are left in there.) // Watch out for variadic allocator function. unsigned NumArgsInFnDecl = FnDecl->getNumParams(); for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { ExprResult Result = PerformCopyInitialization(InitializedEntity::InitializeParameter( FnDecl->getParamDecl(i)), SourceLocation(), Owned(Args[i]->Retain())); if (Result.isInvalid()) return true; Args[i] = Result.takeAs<Expr>(); } Operator = FnDecl; CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); return false; } case OR_No_Viable_Function: Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; case OR_Ambiguous: Diag(StartLoc, diag::err_ovl_ambiguous_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); return true; case OR_Deleted: Diag(StartLoc, diag::err_ovl_deleted_call) << Best->Function->isDeleted() << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; } assert(false && "Unreachable, bad result from BestViableFunction"); return true; } /// DeclareGlobalNewDelete - Declare the global forms of operator new and /// delete. These are: /// @code /// void* operator new(std::size_t) throw(std::bad_alloc); /// void* operator new[](std::size_t) throw(std::bad_alloc); /// void operator delete(void *) throw(); /// void operator delete[](void *) throw(); /// @endcode /// Note that the placement and nothrow forms of new are *not* implicitly /// declared. Their use requires including \<new\>. void Sema::DeclareGlobalNewDelete() { if (GlobalNewDeleteDeclared) return; // C++ [basic.std.dynamic]p2: // [...] The following allocation and deallocation functions (18.4) are // implicitly declared in global scope in each translation unit of a // program // // void* operator new(std::size_t) throw(std::bad_alloc); // void* operator new[](std::size_t) throw(std::bad_alloc); // void operator delete(void*) throw(); // void operator delete[](void*) throw(); // // These implicit declarations introduce only the function names operator // new, operator new[], operator delete, operator delete[]. // // Here, we need to refer to std::bad_alloc, so we will implicitly declare // "std" or "bad_alloc" as necessary to form the exception specification. // However, we do not make these implicit declarations visible to name // lookup. if (!StdBadAlloc) { // The "std::bad_alloc" class has not yet been declared, so build it // implicitly. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, getOrCreateStdNamespace(), SourceLocation(), &PP.getIdentifierTable().get("bad_alloc"), SourceLocation(), 0); getStdBadAlloc()->setImplicit(true); } GlobalNewDeleteDeclared = true; QualType VoidPtr = Context.getPointerType(Context.VoidTy); QualType SizeT = Context.getSizeType(); bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Delete), Context.VoidTy, VoidPtr); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), Context.VoidTy, VoidPtr); } /// DeclareGlobalAllocationFunction - Declares a single implicit global /// allocation function if it doesn't already exist. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, QualType Argument, bool AddMallocAttr) { DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); // Check if this function is already declared. { DeclContext::lookup_iterator Alloc, AllocEnd; for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); Alloc != AllocEnd; ++Alloc) { // Only look at non-template functions, as it is the predefined, // non-templated allocation function we are trying to declare here. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { QualType InitialParamType = Context.getCanonicalType( Func->getParamDecl(0)->getType().getUnqualifiedType()); // FIXME: Do we need to check for default arguments here? if (Func->getNumParams() == 1 && InitialParamType == Argument) { if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); return; } } } } QualType BadAllocType; bool HasBadAllocExceptionSpec = (Name.getCXXOverloadedOperator() == OO_New || Name.getCXXOverloadedOperator() == OO_Array_New); if (HasBadAllocExceptionSpec) { assert(StdBadAlloc && "Must have std::bad_alloc declared"); BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); } QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, true, false, HasBadAllocExceptionSpec? 1 : 0, &BadAllocType, FunctionType::ExtInfo()); FunctionDecl *Alloc = FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, FnType, /*TInfo=*/0, SC_None, SC_None, false, true); Alloc->setImplicit(); if (AddMallocAttr) Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 0, Argument, /*TInfo=*/0, SC_None, SC_None, 0); Alloc->setParams(&Param, 1); // FIXME: Also add this declaration to the IdentifierResolver, but // make sure it is at the end of the chain to coincide with the // global scope. Context.getTranslationUnitDecl()->addDecl(Alloc); } bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator) { LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); // Try to find operator delete/operator delete[] in class scope. LookupQualifiedName(Found, RD); if (Found.isAmbiguous()) return true; Found.suppressDiagnostics(); llvm::SmallVector<DeclAccessPair,4> Matches; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) { NamedDecl *ND = (*F)->getUnderlyingDecl(); // Ignore template operator delete members from the check for a usual // deallocation function. if (isa<FunctionTemplateDecl>(ND)) continue; if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) Matches.push_back(F.getPair()); } // There's exactly one suitable operator; pick it. if (Matches.size() == 1) { Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), Matches[0]); return false; // We found multiple suitable operators; complain about the ambiguity. } else if (!Matches.empty()) { Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) << Name << RD; for (llvm::SmallVectorImpl<DeclAccessPair>::iterator F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // We did find operator delete/operator delete[] declarations, but // none of them were suitable. if (!Found.empty()) { Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) << Name << RD; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); Expr* DeallocArgs[1]; DeallocArgs[0] = &Null; if (FindAllocationOverload(StartLoc, SourceRange(), Name, DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, Operator)) return true; assert(Operator && "Did not find a deallocation function!"); return false; } /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: /// @code ::delete ptr; @endcode /// or /// @code delete [] ptr; @endcode ExprResult Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Ex) { // C++ [expr.delete]p1: // The operand shall have a pointer type, or a class type having a single // conversion function to a pointer type. The result has type void. // // DR599 amends "pointer type" to "pointer to object type" in both cases. FunctionDecl *OperatorDelete = 0; if (!Ex->isTypeDependent()) { QualType Type = Ex->getType(); if (const RecordType *Record = Type->getAs<RecordType>()) { if (RequireCompleteType(StartLoc, Type, PDiag(diag::err_delete_incomplete_class_type))) return ExprError(); llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); for (UnresolvedSetImpl::iterator I = Conversions->begin(), E = Conversions->end(); I != E; ++I) { NamedDecl *D = I.getDecl(); if (isa<UsingShadowDecl>(D)) D = cast<UsingShadowDecl>(D)->getTargetDecl(); // Skip over templated conversion functions; they aren't considered. if (isa<FunctionTemplateDecl>(D)) continue; CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); QualType ConvType = Conv->getConversionType().getNonReferenceType(); if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) ObjectPtrConversions.push_back(Conv); } if (ObjectPtrConversions.size() == 1) { // We have a single conversion to a pointer-to-object type. Perform // that conversion. // TODO: don't redo the conversion calculation. if (!PerformImplicitConversion(Ex, ObjectPtrConversions.front()->getConversionType(), AA_Converting)) { Type = Ex->getType(); } } else if (ObjectPtrConversions.size() > 1) { Diag(StartLoc, diag::err_ambiguous_delete_operand) << Type << Ex->getSourceRange(); for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) NoteOverloadCandidate(ObjectPtrConversions[i]); return ExprError(); } } if (!Type->isPointerType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); if (Pointee->isVoidType() && !isSFINAEContext()) { // The C++ standard bans deleting a pointer to a non-object type, which // effectively bans deletion of "void*". However, most compilers support // this, so we treat it as a warning unless we're in a SFINAE context. Diag(StartLoc, diag::ext_delete_void_ptr_operand) << Type << Ex->getSourceRange(); } else if (Pointee->isFunctionType() || Pointee->isVoidType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); else if (!Pointee->isDependentType() && RequireCompleteType(StartLoc, Pointee, PDiag(diag::warn_delete_incomplete) << Ex->getSourceRange())) return ExprError(); // C++ [expr.delete]p2: // [Note: a pointer to a const type can be the operand of a // delete-expression; it is not necessary to cast away the constness // (5.2.11) of the pointer expression before it is used as the operand // of the delete-expression. ] ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), CK_NoOp); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( ArrayForm ? OO_Array_Delete : OO_Delete); QualType PointeeElem = Context.getBaseElementType(Pointee); if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (!UseGlobal && FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) return ExprError(); if (!RD->hasTrivialDestructor()) if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) MarkDeclarationReferenced(StartLoc, const_cast<CXXDestructorDecl*>(Dtor)); } if (!OperatorDelete) { // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, &Ex, 1, TUDecl, /*AllowMissing=*/false, OperatorDelete)) return ExprError(); } MarkDeclarationReferenced(StartLoc, OperatorDelete); // FIXME: Check access and ambiguity of operator delete and destructor. } return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, OperatorDelete, Ex, StartLoc)); } /// \brief Check the use of the given variable as a C++ condition in an if, /// while, do-while, or switch statement. ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, bool ConvertToBoolean) { QualType T = ConditionVar->getType(); // C++ [stmt.select]p2: // The declarator shall not specify a function or an array. if (T->isFunctionType()) return ExprError(Diag(ConditionVar->getLocation(), diag::err_invalid_use_of_function_type) << ConditionVar->getSourceRange()); else if (T->isArrayType()) return ExprError(Diag(ConditionVar->getLocation(), diag::err_invalid_use_of_array_type) << ConditionVar->getSourceRange()); Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, ConditionVar->getLocation(), ConditionVar->getType().getNonReferenceType()); if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) return ExprError(); return Owned(Condition); } /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { // C++ 6.4p4: // The value of a condition that is an initialized declaration in a statement // other than a switch statement is the value of the declared variable // implicitly converted to type bool. If that conversion is ill-formed, the // program is ill-formed. // The value of a condition that is an expression is the value of the // expression, implicitly converted to bool. // return PerformContextuallyConvertToBool(CondExpr); } /// Helper function to determine whether this is the (deprecated) C++ /// conversion from a string literal to a pointer to non-const char or /// non-const wchar_t (for narrow and wide string literals, /// respectively). bool Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { // Look inside the implicit cast, if it exists. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) From = Cast->getSubExpr(); // A string literal (2.13.4) that is not a wide string literal can // be converted to an rvalue of type "pointer to char"; a wide // string literal can be converted to an rvalue of type "pointer // to wchar_t" (C++ 4.2p2). if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) if (const BuiltinType *ToPointeeType = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { // This conversion is considered only when there is an // explicit appropriate pointer target type (C++ 4.2p2). if (!ToPtrType->getPointeeType().hasQualifiers() && ((StrLit->isWide() && ToPointeeType->isWideCharType()) || (!StrLit->isWide() && (ToPointeeType->getKind() == BuiltinType::Char_U || ToPointeeType->getKind() == BuiltinType::Char_S)))) return true; } return false; } static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, Expr *From) { switch (Kind) { default: assert(0 && "Unhandled cast kind!"); case CK_ConstructorConversion: { ASTOwningVector<Expr*> ConstructorArgs(S); if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), MultiExprArg(&From, 1), CastLoc, ConstructorArgs)) return ExprError(); ExprResult Result = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (Result.isInvalid()) return ExprError(); return S.MaybeBindToTemporary(Result.takeAs<Expr>()); } case CK_UserDefinedConversion: { assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); // Create an implicit call expr that calls it. // FIXME: pass the FoundDecl for the user-defined conversion here CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method); return S.MaybeBindToTemporary(CE); } } } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType using the pre-computed implicit /// conversion sequence ICS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Action is the kind of conversion we're performing, /// used in the error message. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, bool IgnoreBaseAccess) { switch (ICS.getKind()) { case ImplicitConversionSequence::StandardConversion: if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, IgnoreBaseAccess)) return true; break; case ImplicitConversionSequence::UserDefinedConversion: { FunctionDecl *FD = ICS.UserDefined.ConversionFunction; CastKind CastKind = CK_Unknown; QualType BeforeToType; if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { CastKind = CK_UserDefinedConversion; // If the user-defined conversion is specified by a conversion function, // the initial standard conversion sequence converts the source type to // the implicit object parameter of the conversion function. BeforeToType = Context.getTagDeclType(Conv->getParent()); } else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { CastKind = CK_ConstructorConversion; // Do no conversion if dealing with ... for the first conversion. if (!ICS.UserDefined.EllipsisConversion) { // If the user-defined conversion is specified by a constructor, the // initial standard conversion sequence converts the source type to the // type required by the argument of the constructor BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); } } else assert(0 && "Unknown conversion function kind!"); // Whatch out for elipsis conversion. if (!ICS.UserDefined.EllipsisConversion) { if (PerformImplicitConversion(From, BeforeToType, ICS.UserDefined.Before, AA_Converting, IgnoreBaseAccess)) return true; } ExprResult CastArg = BuildCXXCastArgument(*this, From->getLocStart(), ToType.getNonReferenceType(), CastKind, cast<CXXMethodDecl>(FD), From); if (CastArg.isInvalid()) return true; From = CastArg.takeAs<Expr>(); return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, AA_Converting, IgnoreBaseAccess); } case ImplicitConversionSequence::AmbiguousConversion: ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), PDiag(diag::err_typecheck_ambiguous_condition) << From->getSourceRange()); return true; case ImplicitConversionSequence::EllipsisConversion: assert(false && "Cannot perform an ellipsis conversion"); return false; case ImplicitConversionSequence::BadConversion: return true; } // Everything went well. return false; } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType by following the standard /// conversion sequence SCS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Flavor is the context in which we're performing this /// conversion, for use in error messages. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, bool IgnoreBaseAccess) { // Overall FIXME: we are recomputing too many types here and doing far too // much extra work. What this means is that we need to keep track of more // information that is computed when we try the implicit conversion initially, // so that we don't need to recompute anything here. QualType FromType = From->getType(); if (SCS.CopyConstructor) { // FIXME: When can ToType be a reference type? assert(!ToType->isReferenceType()); if (SCS.Second == ICK_Derived_To_Base) { ASTOwningVector<Expr*> ConstructorArgs(*this); if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), MultiExprArg(*this, &From, 1), /*FIXME:ConstructLoc*/SourceLocation(), ConstructorArgs)) return true; ExprResult FromResult = BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } ExprResult FromResult = BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, MultiExprArg(*this, &From, 1), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } // Resolve overloaded function references. if (Context.hasSameType(FromType, Context.OverloadTy)) { DeclAccessPair Found; FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true, Found); if (!Fn) return true; if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) return true; From = FixOverloadedFunctionReference(From, Found, Fn); FromType = From->getType(); } // Perform the first implicit conversion. switch (SCS.First) { case ICK_Identity: case ICK_Lvalue_To_Rvalue: // Nothing to do. break; case ICK_Array_To_Pointer: FromType = Context.getArrayDecayedType(FromType); ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); break; case ICK_Function_To_Pointer: FromType = Context.getPointerType(FromType); ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); break; default: assert(false && "Improper first standard conversion"); break; } // Perform the second implicit conversion switch (SCS.Second) { case ICK_Identity: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (CheckExceptionSpecCompatibility(From, ToType)) return true; // Nothing else to do. break; case ICK_NoReturn_Adjustment: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), CK_NoOp); break; case ICK_Integral_Promotion: case ICK_Integral_Conversion: ImpCastExprToType(From, ToType, CK_IntegralCast); break; case ICK_Floating_Promotion: case ICK_Floating_Conversion: ImpCastExprToType(From, ToType, CK_FloatingCast); break; case ICK_Complex_Promotion: case ICK_Complex_Conversion: ImpCastExprToType(From, ToType, CK_Unknown); break; case ICK_Floating_Integral: if (ToType->isRealFloatingType()) ImpCastExprToType(From, ToType, CK_IntegralToFloating); else ImpCastExprToType(From, ToType, CK_FloatingToIntegral); break; case ICK_Compatible_Conversion: ImpCastExprToType(From, ToType, CK_NoOp); break; case ICK_Pointer_Conversion: { if (SCS.IncompatibleObjC) { // Diagnose incompatible Objective-C conversions Diag(From->getSourceRange().getBegin(), diag::ext_typecheck_convert_incompatible_pointer) << From->getType() << ToType << Action << From->getSourceRange(); } CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Pointer_Member: { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Boolean_Conversion: { CastKind Kind = CK_Unknown; if (FromType->isMemberPointerType()) Kind = CK_MemberPointerToBoolean; ImpCastExprToType(From, Context.BoolTy, Kind); break; } case ICK_Derived_To_Base: { CXXCastPath BasePath; if (CheckDerivedToBaseConversion(From->getType(), ToType.getNonReferenceType(), From->getLocStart(), From->getSourceRange(), &BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType.getNonReferenceType(), CK_DerivedToBase, CastCategory(From), &BasePath); break; } case ICK_Vector_Conversion: ImpCastExprToType(From, ToType, CK_BitCast); break; case ICK_Vector_Splat: ImpCastExprToType(From, ToType, CK_VectorSplat); break; case ICK_Complex_Real: ImpCastExprToType(From, ToType, CK_Unknown); break; case ICK_Lvalue_To_Rvalue: case ICK_Array_To_Pointer: case ICK_Function_To_Pointer: case ICK_Qualification: case ICK_Num_Conversion_Kinds: assert(false && "Improper second standard conversion"); break; } switch (SCS.Third) { case ICK_Identity: // Nothing to do. break; case ICK_Qualification: { // The qualification keeps the category of the inner expression, unless the // target type isn't a reference. ExprValueKind VK = ToType->isReferenceType() ? CastCategory(From) : VK_RValue; ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK_NoOp, VK); if (SCS.DeprecatedStringLiteralToCharPtr) Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) << ToType.getNonReferenceType(); break; } default: assert(false && "Improper third standard conversion"); break; } return false; } ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, ParsedType Ty, SourceLocation RParen) { QualType T = GetTypeFromParser(Ty); // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html // all traits except __is_class, __is_enum and __is_union require a the type // to be complete. if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { if (RequireCompleteType(KWLoc, T, diag::err_incomplete_type_used_in_type_trait_expr)) return ExprError(); } // There is no point in eagerly computing the value. The traits are designed // to be used from type trait templates, so Ty will be a template parameter // 99% of the time. return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, RParen, Context.BoolTy)); } QualType Sema::CheckPointerToMemberOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { const char *OpSpelling = isIndirect ? "->*" : ".*"; // C++ 5.5p2 // The binary operator .* [p3: ->*] binds its second operand, which shall // be of type "pointer to member of T" (where T is a completely-defined // class type) [...] QualType RType = rex->getType(); const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); if (!MemPtr) { Diag(Loc, diag::err_bad_memptr_rhs) << OpSpelling << RType << rex->getSourceRange(); return QualType(); } QualType Class(MemPtr->getClass(), 0); if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete)) return QualType(); // C++ 5.5p2 // [...] to its first operand, which shall be of class T or of a class of // which T is an unambiguous and accessible base class. [p3: a pointer to // such a class] QualType LType = lex->getType(); if (isIndirect) { if (const PointerType *Ptr = LType->getAs<PointerType>()) LType = Ptr->getPointeeType().getNonReferenceType(); else { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << 1 << LType << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); return QualType(); } } if (!Context.hasSameUnqualifiedType(Class, LType)) { // If we want to check the hierarchy, we need a complete type. if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect)) { return QualType(); } CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); // FIXME: Would it be useful to print full ambiguity paths, or is that // overkill? if (!IsDerivedFrom(LType, Class, Paths) || Paths.isAmbiguous(Context.getCanonicalType(Class))) { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect << lex->getType(); return QualType(); } // Cast LHS to type of use. QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; ExprValueKind VK = isIndirect ? VK_RValue : CastCategory(lex); CXXCastPath BasePath; BuildBasePathArray(Paths, BasePath); ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); } if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) { // Diagnose use of pointer-to-member type which when used as // the functional cast in a pointer-to-member expression. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; return QualType(); } // C++ 5.5p2 // The result is an object or a function of the type specified by the // second operand. // The cv qualifiers are the union of those in the pointer and the left side, // in accordance with 5.5p5 and 5.2.5. // FIXME: This returns a dereferenced member function pointer as a normal // function type. However, the only operation valid on such functions is // calling them. There's also a GCC extension to get a function pointer to the // thing, which is another complication, because this type - unlike the type // that is the result of this expression - takes the class as the first // argument. // We probably need a "MemberFunctionClosureType" or something like that. QualType Result = MemPtr->getPointeeType(); Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); return Result; } /// \brief Try to convert a type to another according to C++0x 5.16p3. /// /// This is part of the parameter validation for the ? operator. If either /// value operand is a class type, the two operands are attempted to be /// converted to each other. This function does the conversion in one direction. /// It returns true if the program is ill-formed and has already been diagnosed /// as such. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType) { HaveConversion = false; ToType = To->getType(); InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), SourceLocation()); // C++0x 5.16p3 // The process for determining whether an operand expression E1 of type T1 // can be converted to match an operand expression E2 of type T2 is defined // as follows: // -- If E2 is an lvalue: bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); if (ToIsLvalue) { // E1 can be converted to match E2 if E1 can be implicitly converted to // type "lvalue reference to T2", subject to the constraint that in the // conversion the reference must bind directly to E1. QualType T = Self.Context.getLValueReferenceType(ToType); InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.isDirectReferenceBinding()) { ToType = T; HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } // -- If E2 is an rvalue, or if the conversion above cannot be done: // -- if E1 and E2 have class type, and the underlying class types are // the same or one is a base class of the other: QualType FTy = From->getType(); QualType TTy = To->getType(); const RecordType *FRec = FTy->getAs<RecordType>(); const RecordType *TRec = TTy->getAs<RecordType>(); bool FDerivedFromT = FRec && TRec && FRec != TRec && Self.IsDerivedFrom(FTy, TTy); if (FRec && TRec && (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { // E1 can be converted to match E2 if the class of T2 is the // same type as, or a base class of, the class of T1, and // [cv2 > cv1]. if (FRec == TRec || FDerivedFromT) { if (TTy.isAtLeastAsQualifiedAs(FTy)) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.getKind() != InitializationSequence::FailedSequence) { HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } } return false; } // -- Otherwise: E1 can be converted to match E2 if E1 can be // implicitly converted to the type that expression E2 would have // if E2 were converted to an rvalue (or the type it has, if E2 is // an rvalue). // // This actually refers very narrowly to the lvalue-to-rvalue conversion, not // to the array-to-pointer or function-to-pointer conversions. if (!TTy->getAs<TagType>()) TTy = TTy.getUnqualifiedType(); InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; ToType = TTy; if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); return false; } /// \brief Try to find a common type for two according to C++0x 5.16p5. /// /// This is part of the parameter validation for the ? operator. If either /// value operand is a class type, overload resolution is used to find a /// conversion to a common type. static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, SourceLocation Loc) { Expr *Args[2] = { LHS, RHS }; OverloadCandidateSet CandidateSet(Loc); Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); OverloadCandidateSet::iterator Best; switch (CandidateSet.BestViableFunction(Self, Loc, Best)) { case OR_Success: // We found a match. Perform the conversions on the arguments and move on. if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], Best->Conversions[0], Sema::AA_Converting) || Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], Best->Conversions[1], Sema::AA_Converting)) break; return false; case OR_No_Viable_Function: Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return true; case OR_Ambiguous: Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); // FIXME: Print the possible common types by printing the return types of // the viable candidates. break; case OR_Deleted: assert(false && "Conditional operator has only built-in overloads"); break; } return true; } /// \brief Perform an "extended" implicit conversion as returned by /// TryClassUnification. static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), SourceLocation()); InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); if (Result.isInvalid()) return true; E = Result.takeAs<Expr>(); return false; } /// \brief Check the operands of ?: under C++ semantics. /// /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y /// extension. In this case, LHS == Cond. (But they're not aliases.) QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, SourceLocation QuestionLoc) { // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ // interface pointers. // C++0x 5.16p1 // The first expression is contextually converted to bool. if (!Cond->isTypeDependent()) { if (CheckCXXBooleanCondition(Cond)) return QualType(); } // Either of the arguments dependent? if (LHS->isTypeDependent() || RHS->isTypeDependent()) return Context.DependentTy; // C++0x 5.16p2 // If either the second or the third operand has type (cv) void, ... QualType LTy = LHS->getType(); QualType RTy = RHS->getType(); bool LVoid = LTy->isVoidType(); bool RVoid = RTy->isVoidType(); if (LVoid || RVoid) { // ... then the [l2r] conversions are performed on the second and third // operands ... DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // ... and one of the following shall hold: // -- The second or the third operand (but not both) is a throw- // expression; the result is of the type of the other and is an rvalue. bool LThrow = isa<CXXThrowExpr>(LHS); bool RThrow = isa<CXXThrowExpr>(RHS); if (LThrow && !RThrow) return RTy; if (RThrow && !LThrow) return LTy; // -- Both the second and third operands have type void; the result is of // type void and is an rvalue. if (LVoid && RVoid) return Context.VoidTy; // Neither holds, error. Diag(QuestionLoc, diag::err_conditional_void_nonvoid) << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // Neither is void. // C++0x 5.16p3 // Otherwise, if the second and third operand have different types, and // either has (cv) class type, and attempt is made to convert each of those // operands to the other. if (!Context.hasSameType(LTy, RTy) && (LTy->isRecordType() || RTy->isRecordType())) { ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; // These return true if a single direction is already ambiguous. QualType L2RType, R2LType; bool HaveL2R, HaveR2L; if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) return QualType(); if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) return QualType(); // If both can be converted, [...] the program is ill-formed. if (HaveL2R && HaveR2L) { Diag(QuestionLoc, diag::err_conditional_ambiguous) << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // If exactly one conversion is possible, that conversion is applied to // the chosen operand and the converted operands are used in place of the // original operands for the remainder of this section. if (HaveL2R) { if (ConvertForConditional(*this, LHS, L2RType)) return QualType(); LTy = LHS->getType(); } else if (HaveR2L) { if (ConvertForConditional(*this, RHS, R2LType)) return QualType(); RTy = RHS->getType(); } } // C++0x 5.16p4 // If the second and third operands are lvalues and have the same type, // the result is of that type [...] bool Same = Context.hasSameType(LTy, RTy); if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && RHS->isLvalue(Context) == Expr::LV_Valid) return LTy; // C++0x 5.16p5 // Otherwise, the result is an rvalue. If the second and third operands // do not have the same type, and either has (cv) class type, ... if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { // ... overload resolution is used to determine the conversions (if any) // to be applied to the operands. If the overload resolution fails, the // program is ill-formed. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) return QualType(); } // C++0x 5.16p6 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard // conversions are performed on the second and third operands. DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // After those conversions, one of the following shall hold: // -- The second and third operands have the same type; the result // is of that type. If the operands have class type, the result // is a prvalue temporary of the result type, which is // copy-initialized from either the second operand or the third // operand depending on the value of the first operand. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { if (LTy->isRecordType()) { // The operands have class type. Make a temporary copy. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); ExprResult LHSCopy = PerformCopyInitialization(Entity, SourceLocation(), Owned(LHS)); if (LHSCopy.isInvalid()) return QualType(); ExprResult RHSCopy = PerformCopyInitialization(Entity, SourceLocation(), Owned(RHS)); if (RHSCopy.isInvalid()) return QualType(); LHS = LHSCopy.takeAs<Expr>(); RHS = RHSCopy.takeAs<Expr>(); } return LTy; } // Extension: conditional operator involving vector types. if (LTy->isVectorType() || RTy->isVectorType()) return CheckVectorOperands(QuestionLoc, LHS, RHS); // -- The second and third operands have arithmetic or enumeration type; // the usual arithmetic conversions are performed to bring them to a // common type, and the result is of that type. if (LTy->isArithmeticType() && RTy->isArithmeticType()) { UsualArithmeticConversions(LHS, RHS); return LHS->getType(); } // -- The second and third operands have pointer type, or one has pointer // type and the other is a null pointer constant; pointer conversions // and qualification conversions are performed to bring them to their // composite pointer type. The result is of the composite pointer type. // -- The second and third operands have pointer to member type, or one has // pointer to member type and the other is a null pointer constant; // pointer to member conversions and qualification conversions are // performed to bring them to a common type, whose cv-qualification // shall match the cv-qualification of either the second or the third // operand. The result is of the common type. bool NonStandardCompositeType = false; QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, isSFINAEContext()? 0 : &NonStandardCompositeType); if (!Composite.isNull()) { if (NonStandardCompositeType) Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands_nonstandard) << LTy << RTy << Composite << LHS->getSourceRange() << RHS->getSourceRange(); return Composite; } // Similarly, attempt to find composite type of two objective-c pointers. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); if (!Composite.isNull()) return Composite; Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } /// \brief Find a merged pointer type and convert the two expressions to it. /// /// This finds the composite pointer type (or member pointer type) for @p E1 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this /// type and returns it. /// It does not emit diagnostics. /// /// \param Loc The location of the operator requiring these two expressions to /// be converted to the composite pointer type. /// /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find /// a non-standard (but still sane) composite type to which both expressions /// can be converted. When such a type is chosen, \c *NonStandardCompositeType /// will be set true. QualType Sema::FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool *NonStandardCompositeType) { if (NonStandardCompositeType) *NonStandardCompositeType = false; assert(getLangOptions().CPlusPlus && "This function assumes C++"); QualType T1 = E1->getType(), T2 = E2->getType(); if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && !T2->isAnyPointerType() && !T2->isMemberPointerType()) return QualType(); // C++0x 5.9p2 // Pointer conversions and qualification conversions are performed on // pointer operands to bring them to their composite pointer type. If // one operand is a null pointer constant, the composite pointer type is // the type of the other operand. if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T2->isMemberPointerType()) ImpCastExprToType(E1, T2, CK_NullToMemberPointer); else ImpCastExprToType(E1, T2, CK_IntegralToPointer); return T2; } if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T1->isMemberPointerType()) ImpCastExprToType(E2, T1, CK_NullToMemberPointer); else ImpCastExprToType(E2, T1, CK_IntegralToPointer); return T1; } // Now both have to be pointers or member pointers. if ((!T1->isPointerType() && !T1->isMemberPointerType()) || (!T2->isPointerType() && !T2->isMemberPointerType())) return QualType(); // Otherwise, of one of the operands has type "pointer to cv1 void," then // the other has type "pointer to cv2 T" and the composite pointer type is // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. // Otherwise, the composite pointer type is a pointer type similar to the // type of one of the operands, with a cv-qualification signature that is // the union of the cv-qualification signatures of the operand types. // In practice, the first part here is redundant; it's subsumed by the second. // What we do here is, we build the two possible composite types, and try the // conversions in both directions. If only one works, or if the two composite // types are the same, we have succeeded. // FIXME: extended qualifiers? typedef llvm::SmallVector<unsigned, 4> QualifierVector; QualifierVector QualifierUnion; typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> ContainingClassVector; ContainingClassVector MemberOfClass; QualType Composite1 = Context.getCanonicalType(T1), Composite2 = Context.getCanonicalType(T2); unsigned NeedConstBefore = 0; do { const PointerType *Ptr1, *Ptr2; if ((Ptr1 = Composite1->getAs<PointerType>()) && (Ptr2 = Composite2->getAs<PointerType>())) { Composite1 = Ptr1->getPointeeType(); Composite2 = Ptr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (NonStandardCompositeType && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); continue; } const MemberPointerType *MemPtr1, *MemPtr2; if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && (MemPtr2 = Composite2->getAs<MemberPointerType>())) { Composite1 = MemPtr1->getPointeeType(); Composite2 = MemPtr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (NonStandardCompositeType && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), MemPtr2->getClass())); continue; } // FIXME: block pointer types? // Cannot unwrap any more types. break; } while (true); if (NeedConstBefore && NonStandardCompositeType) { // Extension: Add 'const' to qualifiers that come before the first qualifier // mismatch, so that our (non-standard!) composite type meets the // requirements of C++ [conv.qual]p4 bullet 3. for (unsigned I = 0; I != NeedConstBefore; ++I) { if ((QualifierUnion[I] & Qualifiers::Const) == 0) { QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; *NonStandardCompositeType = true; } } } // Rewrap the composites as pointers or member pointers with the union CVRs. ContainingClassVector::reverse_iterator MOC = MemberOfClass.rbegin(); for (QualifierVector::reverse_iterator I = QualifierUnion.rbegin(), E = QualifierUnion.rend(); I != E; (void)++I, ++MOC) { Qualifiers Quals = Qualifiers::fromCVRMask(*I); if (MOC->first && MOC->second) { // Rebuild member pointer type Composite1 = Context.getMemberPointerType( Context.getQualifiedType(Composite1, Quals), MOC->first); Composite2 = Context.getMemberPointerType( Context.getQualifiedType(Composite2, Quals), MOC->second); } else { // Rebuild pointer type Composite1 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); Composite2 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); } } // Try to convert to the first composite pointer type. InitializedEntity Entity1 = InitializedEntity::InitializeTemporary(Composite1); InitializationKind Kind = InitializationKind::CreateCopy(Loc, SourceLocation()); InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); if (E1ToC1 && E2ToC1) { // Conversion to Composite1 is viable. if (!Context.hasSameType(Composite1, Composite2)) { // Composite2 is a different type from Composite1. Check whether // Composite2 is also viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); if (E1ToC2 && E2ToC2) { // Both Composite1 and Composite2 are viable and are different; // this is an ambiguity. return QualType(); } } // Convert E1 to Composite1 ExprResult E1Result = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite1 ExprResult E2Result = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite1; } // Check whether Composite2 is viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); if (!E1ToC2 || !E2ToC2) return QualType(); // Convert E1 to Composite2 ExprResult E1Result = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite2 ExprResult E2Result = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite2; } ExprResult Sema::MaybeBindToTemporary(Expr *E) { if (!Context.getLangOptions().CPlusPlus) return Owned(E); assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); const RecordType *RT = E->getType()->getAs<RecordType>(); if (!RT) return Owned(E); // If this is the result of a call or an Objective-C message send expression, // our source might actually be a reference, in which case we shouldn't bind. if (CallExpr *CE = dyn_cast<CallExpr>(E)) { if (CE->getCallReturnType()->isReferenceType()) return Owned(E); } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { if (const ObjCMethodDecl *MD = ME->getMethodDecl()) { if (MD->getResultType()->isReferenceType()) return Owned(E); } } // That should be enough to guarantee that this type is complete. // If it has a trivial destructor, we can avoid the extra copy. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (RD->isInvalidDecl() || RD->hasTrivialDestructor()) return Owned(E); CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); ExprTemporaries.push_back(Temp); if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_temp) << E->getType()); } // FIXME: Add the temporary to the temporaries vector. return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); } Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { assert(SubExpr && "sub expression can't be null!"); // Check any implicit conversions within the expression. CheckImplicitConversions(SubExpr); unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); if (ExprTemporaries.size() == FirstTemporary) return SubExpr; Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, &ExprTemporaries[FirstTemporary], ExprTemporaries.size() - FirstTemporary); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) { if (SubExpr.isInvalid()) return ExprError(); return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); } FullExpr Sema::CreateFullExpr(Expr *SubExpr) { unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; CXXTemporary **Temporaries = NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor) { // Since this might be a postfix expression, get rid of ParenListExprs. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); if (Result.isInvalid()) return ExprError(); Base = Result.get(); QualType BaseType = Base->getType(); MayBePseudoDestructor = false; if (BaseType->isDependentType()) { // If we have a pointer to a dependent type and are using the -> operator, // the object type is the type that the pointer points to. We might still // have enough information about that type to do something useful. if (OpKind == tok::arrow) if (const PointerType *Ptr = BaseType->getAs<PointerType>()) BaseType = Ptr->getPointeeType(); ObjectType = ParsedType::make(BaseType); MayBePseudoDestructor = true; return Owned(Base); } // C++ [over.match.oper]p8: // [...] When operator->returns, the operator-> is applied to the value // returned, with the original second operand. if (OpKind == tok::arrow) { // The set of types we've considered so far. llvm::SmallPtrSet<CanQualType,8> CTypes; llvm::SmallVector<SourceLocation, 8> Locations; CTypes.insert(Context.getCanonicalType(BaseType)); while (BaseType->isRecordType()) { Result = BuildOverloadedArrowExpr(S, Base, OpLoc); if (Result.isInvalid()) return ExprError(); Base = Result.get(); if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) Locations.push_back(OpCall->getDirectCallee()->getLocation()); BaseType = Base->getType(); CanQualType CBaseType = Context.getCanonicalType(BaseType); if (!CTypes.insert(CBaseType)) { Diag(OpLoc, diag::err_operator_arrow_circular); for (unsigned i = 0; i < Locations.size(); i++) Diag(Locations[i], diag::note_declared_at); return ExprError(); } } if (BaseType->isPointerType()) BaseType = BaseType->getPointeeType(); } // We could end up with various non-record types here, such as extended // vector types or Objective-C interfaces. Just return early and let // ActOnMemberReferenceExpr do the work. if (!BaseType->isRecordType()) { // C++ [basic.lookup.classref]p2: // [...] If the type of the object expression is of pointer to scalar // type, the unqualified-id is looked up in the context of the complete // postfix-expression. // // This also indicates that we should be parsing a // pseudo-destructor-name. ObjectType = ParsedType(); MayBePseudoDestructor = true; return Owned(Base); } // The object type must be complete (or dependent). if (!BaseType->isDependentType() && RequireCompleteType(OpLoc, BaseType, PDiag(diag::err_incomplete_member_access))) return ExprError(); // C++ [basic.lookup.classref]p2: // If the id-expression in a class member access (5.2.5) is an // unqualified-id, and the type of the object expression is of a class // type C (or of pointer to a class type C), the unqualified-id is looked // up in the scope of class C. [...] ObjectType = ParsedType::make(BaseType); return move(Base); } ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr) { SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) << isa<CXXPseudoDestructorExpr>(MemExpr) << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); return ActOnCallExpr(/*Scope*/ 0, MemExpr, /*LPLoc*/ ExpectedLParenLoc, MultiExprArg(), /*CommaLocs*/ 0, /*RPLoc*/ ExpectedLParenLoc); } ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeTypeInfo, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage Destructed, bool HasTrailingLParen) { TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!Base->isTypeDependent()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) << ObjectType << Base->getSourceRange(); return ExprError(); } // C++ [expr.pseudo]p2: // [...] The cv-unqualified versions of the object type and of the type // designated by the pseudo-destructor-name shall be the same type. if (DestructedTypeInfo) { QualType DestructedType = DestructedTypeInfo->getType(); SourceLocation DestructedTypeStart = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) << ObjectType << DestructedType << Base->getSourceRange() << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); // Recover by setting the destructed type to the object type. DestructedType = ObjectType; DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); } } // C++ [expr.pseudo]p2: // [...] Furthermore, the two type-names in a pseudo-destructor-name of the // form // // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name // // shall designate the same scalar type. if (ScopeTypeInfo) { QualType ScopeType = ScopeTypeInfo->getType(); if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), diag::err_pseudo_dtor_type_mismatch) << ObjectType << ScopeType << Base->getSourceRange() << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); ScopeType = QualType(); ScopeTypeInfo = 0; } } Expr *Result = new (Context) CXXPseudoDestructorExpr(Context, Base, OpKind == tok::arrow, OpLoc, SS.getScopeRep(), SS.getRange(), ScopeTypeInfo, CCLoc, TildeLoc, Destructed); if (HasTrailingLParen) return Owned(Result); return DiagnoseDtorReference(Destructed.getLocation(), Result); } ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName, bool HasTrailingLParen) { assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid first type name in pseudo-destructor"); assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid second type name in pseudo-destructor"); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!ObjectType->isDependentType()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } // Compute the object type that we should use for name lookup purposes. Only // record types and dependent types matter. ParsedType ObjectTypePtrForLookup; if (!SS.isSet()) { if (const Type *T = ObjectType->getAs<RecordType>()) ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0)); else if (ObjectType->isDependentType()) ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); } // Convert the name of the type being destructed (following the ~) into a // type (with source-location information). QualType DestructedType; TypeSourceInfo *DestructedTypeInfo = 0; PseudoDestructorTypeStorage Destructed; if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*SecondTypeName.Identifier, SecondTypeName.StartLocation, S, &SS, true, ObjectTypePtrForLookup); if (!T && ((SS.isSet() && !computeDeclContext(SS, false)) || (!SS.isSet() && ObjectType->isDependentType()))) { // The name of the type being destroyed is a dependent name, and we // couldn't find anything useful in scope. Just store the identifier and // it's location, and we'll perform (qualified) name lookup again at // template instantiation time. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, SecondTypeName.StartLocation); } else if (!T) { Diag(SecondTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << SecondTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); } else { // Resolve the template-id to a type. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); } // If we've performed some kind of recovery, (re-)build the type source // information. if (!DestructedType.isNull()) { if (!DestructedTypeInfo) DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, SecondTypeName.StartLocation); Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); } // Convert the name of the scope type (the type prior to '::') into a type. TypeSourceInfo *ScopeTypeInfo = 0; QualType ScopeType; if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.Identifier) { if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*FirstTypeName.Identifier, FirstTypeName.StartLocation, S, &SS, false, ObjectTypePtrForLookup); if (!T) { Diag(FirstTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << FirstTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Just drop this type. It's unnecessary anyway. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); } else { // Resolve the template-id to a type. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by dropping this type. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); } } if (!ScopeType.isNull() && !ScopeTypeInfo) ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, FirstTypeName.StartLocation); return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, ScopeTypeInfo, CCLoc, TildeLoc, Destructed, HasTrailingLParen); } CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXMethodDecl *Method) { if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, FoundDecl, Method)) assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); MemberExpr *ME = new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, SourceLocation(), Method->getType()); QualType ResultType = Method->getCallResultType(); MarkDeclarationReferenced(Exp->getLocStart(), Method); CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, Exp->getLocEnd()); return CE; } ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { if (!FullExpr) return ExprError(); return MaybeCreateCXXExprWithTemporaries(FullExpr); }
chriskmanx/qmole
QMOLEDEV/llvm-2.8/tools/clang-2.8/lib/Sema/SemaExprCXX.cpp
C++
gpl-3.0
124,344
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.virtualization; import java.io.IOException; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class FloatSerializer implements ObjectSerializer<Float> { @Override public int typeValue() { return SerializationConstants.OBJECT_TYPE_FLOAT; } @Override public ReferenceType defaultReferenceType() { return ReferenceType.OBJECT; } @Override public boolean defaultStoreReference() { return true; } @Override public void write(Float value, VirtualizationOutput out) throws IOException { out.writeFloat(value); } @Override public Float read(VirtualizationInput in) throws IOException { return in.readFloat(); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/virtualization/FloatSerializer.java
Java
gpl-3.0
1,687
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Session */ require_once 'Zend/Session.php'; /** * @see Zend_Controller_Action_Helper_Abstract */ require_once 'Zend/Controller/Action/Helper/Abstract.php'; /** * Flash Messenger - implement session-based messages * * @uses Zend_Controller_Action_Helper_Abstract * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FlashMessenger.php 23775 2011-03-01 17:25:24Z ralph $ */ class Zend_Controller_Action_Helper_FlashMessengerType extends Zend_Controller_Action_Helper_Abstract implements IteratorAggregate, Countable { /** * $_messages - Messages from previous request * * @var array */ static protected $_messages = array(); /** * $_session - Zend_Session storage object * * @var Zend_Session */ static protected $_session = null; /** * $_messageAdded - Wether a message has been previously added * * @var boolean */ static protected $_messageAdded = false; /** * $_namespace - Instance namespace, default is 'default' * * @var string */ protected $_namespace = 'default'; /** * __construct() - Instance constructor, needed to get iterators, etc * * @param string $namespace * @return void */ public function __construct() { if (!self::$_session instanceof Zend_Session_Namespace) { self::$_session = new Zend_Session_Namespace($this->getName()); foreach (self::$_session as $namespace => $messages) { self::$_messages[$namespace] = $messages; unset(self::$_session->{$namespace}); } } } /** * postDispatch() - runs after action is dispatched, in this * case, it is resetting the namespace in case we have forwarded to a different * action, Flashmessage will be 'clean' (default namespace) * * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function postDispatch() { $this->resetNamespace(); return $this; } /** * setNamespace() - change the namespace messages are added to, useful for * per action controller messaging between requests * * @param string $namespace * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function setNamespace($namespace = 'default') { $this->_namespace = $namespace; return $this; } /** * resetNamespace() - reset the namespace to the default * * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function resetNamespace() { $this->setNamespace(); return $this; } /** * addMessage() - Add a message to flash message * * @param string $message * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function addMessage($message) { if (self::$_messageAdded === false) { self::$_session->setExpirationHops(1, null, true); } if (!is_array(self::$_session->{$this->_namespace})) { self::$_session->{$this->_namespace} = array(); } self::$_session->{$this->_namespace}[] = $message; return $this; } /** * hasMessages() - Wether a specific namespace has messages * * @return boolean */ public function hasMessages() { return isset(self::$_messages[$this->_namespace]); } /** * getMessages() - Get messages from a specific namespace * * @return array */ public function getMessages() { if ($this->hasMessages()) { return self::$_messages[$this->_namespace]; } return array(); } /** * Clear all messages from the previous request & current namespace * * @return boolean True if messages were cleared, false if none existed */ public function clearMessages() { if ($this->hasMessages()) { unset(self::$_messages[$this->_namespace]); return true; } return false; } /** * hasCurrentMessages() - check to see if messages have been added to current * namespace within this request * * @return boolean */ public function hasCurrentMessages() { return isset(self::$_session->{$this->_namespace}); } /** * getCurrentMessages() - get messages that have been added to the current * namespace within this request * * @return array */ public function getCurrentMessages() { if ($this->hasCurrentMessages()) { return self::$_session->{$this->_namespace}; } return array(); } /** * clear messages from the current request & current namespace * * @return boolean */ public function clearCurrentMessages() { if ($this->hasCurrentMessages()) { unset(self::$_session->{$this->_namespace}); return true; } return false; } /** * getIterator() - complete the IteratorAggregate interface, for iterating * * @return ArrayObject */ public function getIterator() { if ($this->hasMessages()) { return new ArrayObject($this->getMessages()); } return new ArrayObject(); } /** * count() - Complete the countable interface * * @return int */ public function count() { if ($this->hasMessages()) { return count($this->getMessages()); } return 0; } /** * Strategy pattern: proxy to addMessage() * * @param string $message * @return void */ public function direct($message) { return $this->addMessage($message); } }
culturagovbr/portal-vale-cultura
projeto/library/Zend/Controller/Action/Helper/FlashMessengerType.php
PHP
gpl-3.0
6,914
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'author'=>'Auteur', 'bbcode'=>'BBCode is <b><u>AAN</u></b>', 'cancel'=>'annuleren', 'comm'=>'reactie', 'comment'=>'<a href="$url">[1] reactie</a>, laatst door $lastposter - $lastdate', 'comments'=>'<a href="$url">[$anzcomments] reacties</a>, laatst door $lastposter - $lastdate', 'date'=>'Datum', 'delete'=>'verwijder', 'delete_selected'=>'verwijder geselecteerden', 'edit'=>'bewerk', 'enter_title'=>'Je moet een titel invullen!', 'enter_text'=>'Je moet tekst invullen', 'go'=>'Ga!', 'headline'=>'Titel', 'html'=>'HTML is <b><u>AAN</u></b>', 'intern'=>'intern', 'languages'=>'Talen', 'link'=>'Link', 'links'=>'Links', 'new_post'=>'Nieuw Bericht', 'new_window'=>'nieuw venster', 'news'=>'Nieuws', 'news_archive'=>'Archief', 'no'=>'nee', 'no_access'=>'geen toegang', 'no_comment'=>'<a href="$url">geen reacties</a>', 'no_comments'=>'sta commentaar niet toe', 'no_topnews'=>'geen top nieuws', 'options'=>'opties', 'post_languages'=>'Nieuws in <select name="language_count" onchange="update_textarea(this.options[this.selectedIndex].value)">$selects</select> talen', 'post_news'=>'plaats nieuws', 'preview'=>'preview', 'publish_now'=>'plaats nu', 'publish_selected'=>'plaats geselecteerden', 'really_delete'=>'Dit Nieuws echt verwijderen?', 'rubric'=>'Rubriek', 'save_news'=>'opslaan', 'select_all'=>'selecteer allen', 'self'=>'zelf venster', 'show_news'=>'bekijk nieuws', 'smilies'=>'Smileys zijn <b><u>AAN</u></b>', 'sort'=>'Sorteer:', 'title_unpublished_news'=>'<h2>ONGEPUCLICEERD NIEUWS:</h2>', 'topnews'=>'top nieuws', 'unpublish'=>'onpubliceer', 'unpublish_selected'=>'onpubliceer geselecteerden', 'unpublished_news'=>'onpubliceer nieuws', 'upload_images'=>'upload afbeeldingen', 'user_comments'=>'sta gebruikers commentaar toe', 'view_more'=>'zie meer...', 'visitor_comments'=>'sta bezoekers commentaar toe', 'written_by'=>'geschreven door', 'yes'=>'ja' ); ?>
webSPELL/webSPELL
languages/nl/news.php
PHP
gpl-3.0
3,801
package com.ouser.module; import java.util.HashMap; import java.util.Map; import com.ouser.util.StringUtil; import android.os.Bundle; /** * 照片 * @author hanlixin * */ public class Photo { public enum Size { Small(80, 0), /** 小列表,菜单 */ Normal(100, 1), /** profile */ Large(134, 2), /** 大列表 */ XLarge(640, 3); /** 大图 */ private int size = 0; private int key = 0; Size(int size, int key) { this.size = size; this.key = key; } public int getSize() { return size; } int getKey() { return key; } static Size fromKey(int key) { for(Size s : Size.values()) { if(s.getKey() == key) { return s; } } return null; } } private String url = ""; private int resId = 0; private Map<Size, String> paths = new HashMap<Size, String>(); private Map<Size, Integer> tryTimes = new HashMap<Size, Integer>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; this.tryTimes.clear(); } public int getResId() { return resId; } public void setResId(int res) { this.resId = res; } public void setPath(String path, Size size) { paths.put(size, path); } public String getPath(Size size) { if(paths.containsKey(size)) { return paths.get(size); } return ""; } public void setTryTime(int value, Size size) { tryTimes.put(size, value); } public int getTryTime(Size size) { if(tryTimes.containsKey(size)) { return tryTimes.get(size); } return 0; } public boolean isEmpty() { return StringUtil.isEmpty(url) && resId == 0; } public boolean isSame(Photo p) { return p.url.equals(this.url) || ( this.resId != 0 && p.resId == this.resId); } public Bundle toBundle() { StringBuilder sbPath = new StringBuilder(); for(Map.Entry<Size, String> entry : paths.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } StringBuilder sbTryTime = new StringBuilder(); for(Map.Entry<Size, Integer> entry : tryTimes.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } Bundle bundle = new Bundle(); bundle.putString("url", url); bundle.putInt("resid", resId); bundle.putString("path", sbPath.toString()); bundle.putString("trytime", sbTryTime.toString()); return bundle; } public void fromBundle(Bundle bundle) { url = bundle.getString("url"); resId = bundle.getInt("resid"); String strPath = bundle.getString("path"); String strTryTime = bundle.getString("trytime"); this.paths.clear(); for(String str : strPath.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.paths.put(Size.fromKey(Integer.parseInt(values[0])), values[1]); } this.tryTimes.clear(); for(String str : strTryTime.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.tryTimes.put(Size.fromKey(Integer.parseInt(values[0])), Integer.parseInt(values[1])); } } }
tassadar2002/ouser
src/com/ouser/module/Photo.java
Java
gpl-3.0
3,179
package bdv.server; import bdv.db.UserController; import bdv.model.DataSet; import bdv.util.Render; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.log.Log; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; /** * Author: HongKee Moon (moon@mpi-cbg.de), Scientific Computing Facility * Organization: MPI-CBG Dresden * Date: December 2016 */ public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final ContextHandlerCollection publicDatasetHandlers, final ContextHandlerCollection privateDatasetHandlers, final String thumbnailsDirectoryName ) throws IOException, URISyntaxException { super( server, publicDatasetHandlers, privateDatasetHandlers, thumbnailsDirectoryName ); setContextPath( "/private/user/*" ); } @Override public void doHandle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response ) throws IOException, ServletException { // System.out.println(target); Principal principal = request.getUserPrincipal(); // System.out.println( principal.getName() ); if ( null == request.getQueryString() ) { list( baseRequest, response, principal.getName() ); } else { // System.out.println(request.getQueryString()); updateDataSet( baseRequest, request, response, principal.getName() ); } } private void updateDataSet( Request baseRequest, HttpServletRequest request, HttpServletResponse response, String userId ) throws IOException { final String op = request.getParameter( "op" ); if ( null != op ) { if ( op.equals( "addDS" ) ) { final String dataSetName = request.getParameter( "name" ); final String tags = request.getParameter( "tags" ); final String description = request.getParameter( "description" ); final String file = request.getParameter( "file" ); final boolean isPublic = Boolean.parseBoolean( request.getParameter( "public" ) ); // System.out.println( "name: " + dataSetName ); // System.out.println( "tags: " + tags ); // System.out.println( "description: " + description ); // System.out.println( "file: " + file ); // System.out.println( "isPublic: " + isPublic ); final DataSet ds = new DataSet( dataSetName, file, tags, description, isPublic ); // Add it the database UserController.addDataSet( userId, ds ); // Add new CellHandler depending on public property addDataSet( ds, baseRequest, response ); } else if ( op.equals( "removeDS" ) ) { final long dsId = Long.parseLong( request.getParameter( "dataset" ) ); // Remove it from the database UserController.removeDataSet( userId, dsId ); // Remove the CellHandler removeDataSet( dsId, baseRequest, response ); } else if ( op.equals( "updateDS" ) ) { // UpdateDS uses x-editable // Please, refer http://vitalets.github.io/x-editable/docs.html final String field = request.getParameter( "name" ); final long dataSetId = Long.parseLong( request.getParameter( "pk" ) ); final String value = request.getParameter( "value" ); // Update the database final DataSet ds = UserController.getDataSet( userId, dataSetId ); if ( field.equals( "dataSetName" ) ) { ds.setName( value ); } else if ( field.equals( "dataSetDescription" ) ) { ds.setDescription( value ); } // Update DataBase UserController.updateDataSet( userId, ds ); // Update the CellHandler updateHandler( ds, baseRequest, response ); // System.out.println( field + ":" + value ); } else if ( op.equals( "addTag" ) || op.equals( "removeTag" ) ) { processTag( op, baseRequest, request, response ); } else if ( op.equals( "setPublic" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final boolean checked = Boolean.parseBoolean( request.getParameter( "checked" ) ); final DataSet ds = UserController.getDataSet( userId, dataSetId ); ds.setPublic( checked ); UserController.updateDataSet( userId, ds ); ds.setPublic( !checked ); updateHandlerVisibility( ds, checked, baseRequest, response ); } else if ( op.equals( "addSharedUser" ) || op.equals( "removeSharedUser" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final String sharedUserId = request.getParameter( "userId" ); if ( op.equals( "addSharedUser" ) ) { // System.out.println("Add a shared user"); UserController.addReadableSharedUser( userId, dataSetId, sharedUserId ); } else if ( op.equals( "removeSharedUser" ) ) { // System.out.println("Remove the shared user"); UserController.removeReadableSharedUser( userId, dataSetId, sharedUserId ); } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); ow.write( "Success: " ); ow.close(); } } } private void updateHandlerVisibility( DataSet ds, boolean newVisibility, Request baseRequest, HttpServletResponse response ) throws IOException { String dsName = ds.getName(); boolean ret = removeCellHandler( ds.getIndex() ); if ( ret ) { ds.setPublic( newVisibility ); final boolean isPublic = newVisibility; final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); ret = false; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is removed." ); } else { ow.write( "Error: " + dsName + " cannot be removed." ); } ow.close(); } private void updateHandler( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; String dsName = ""; for ( final Handler handler : server.getChildHandlersByClass( CellHandler.class ) ) { final CellHandler contextHandler = ( CellHandler ) handler; if ( contextHandler.getDataSet().getIndex() == ds.getIndex() ) { final DataSet dataSet = contextHandler.getDataSet(); dataSet.setName( ds.getName() ); dataSet.setDescription( ds.getDescription() ); ret = true; dsName = ds.getName(); break; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is updated." ); } else { ow.write( "Error: " + dsName + " cannot be updated." ); } ow.close(); } private void removeDataSet( long dsId, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = removeCellHandler( dsId ); response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsId + " is removed." ); } else { ow.write( "Error: " + dsId + " cannot be removed." ); } ow.close(); } private void addDataSet( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; if ( !ds.getXmlPath().isEmpty() && !ds.getName().isEmpty() ) { final boolean isPublic = ds.isPublic(); final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); } ret = true; } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) ow.write( "Success: " + ds.getName() + " is added." ); else ow.write( "Error: " + ds.getName() + " cannot be added." ); ow.close(); } private void list( final Request baseRequest, final HttpServletResponse response, final String userId ) throws IOException { response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); getHtmlDatasetList( ow, userId ); ow.close(); } private void getHtmlDatasetList( final PrintWriter out, final String userId ) throws IOException { final List< DataSet >[] dataSets = UserController.getDataSets( userId ); final List< DataSet > myDataSetList = dataSets[ 0 ]; final List< DataSet > sharedDataSetList = dataSets[ 1 ]; final STGroup g = new STRawGroupDir( "templates", '$', '$' ); final ST userPage = g.getInstanceOf( "userPage" ); final STGroup g2 = new STRawGroupDir( "templates", '~', '~' ); final ST userPageJS = g2.getInstanceOf( "userPageJS" ); final StringBuilder dsString = new StringBuilder(); for ( DataSet ds : myDataSetList ) { StringBuilder sharedUserString = new StringBuilder(); final ST dataSetTr = g.getInstanceOf( "privateDataSetTr" ); for ( String sharedUser : ds.getSharedUsers() ) { final ST userToBeRemoved = g.getInstanceOf( "userToBeRemoved" ); userToBeRemoved.add( "dataSetId", ds.getIndex() ); userToBeRemoved.add( "sharedUserId", sharedUser ); sharedUserString.append( userToBeRemoved.render() ); } if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", ds.getTags().stream().collect( Collectors.joining( "," ) ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", sharedUserString.toString() ); dsString.append( dataSetTr.render() ); } if ( sharedDataSetList != null ) { for ( DataSet ds : sharedDataSetList ) { final ST dataSetTr = g.getInstanceOf( "sharedDataSetTr" ); if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", Render.createTagsLabel( ds ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", ds.getOwner() ); dsString.append( dataSetTr.render() ); } } userPage.add( "userId", userId ); userPage.add( "dataSetTr", dsString.toString() ); userPage.add( "JS", userPageJS.render() ); out.write( userPage.render() ); out.close(); } }
hkmoon/bigdataviewer-server
src/main/java/bdv/server/UserPageHandler.java
Java
gpl-3.0
13,172
/* * Copyright 2006, 2007 Alessandro Chiari. * * This file is part of BrewPlus. * * BrewPlus 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. * * BrewPlus 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 BrewPlus; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package jmash; import jmash.interfaces.XmlAble; import org.apache.log4j.Logger; import org.jdom.Element; /** * * @author Alessandro */ public class YeastType implements XmlAble { private static Logger LOGGER = Logger.getLogger(YeastType.class); /** Creates a new instance of YeastType */ public YeastType() { } private String nome; private String codice; private String produttore; private String forma; private String categoria; private String descrizione; private String attenuazioneMed; private String attenuazioneMin; private String attenuazioneMax; private String temperaturaMin; private String temperaturaMax; private String temperaturaMaxFerm; private static String campiXml[] = { "nome", "codice", "produttore", "forma", "categoria", "attenuazioneMed", "attenuazioneMin", "attenuazioneMax", "temperaturaMin", "temperaturaMax", "descrizione"}; public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getProduttore() { return this.produttore; } public void setProduttore(String produttore) { this.produttore = produttore; } public String getForma() { return this.forma; } public void setForma(String forma) { this.forma = forma; } public String getCategoria() { return this.categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getAttenuazioneMin() { return this.attenuazioneMin; } public void setAttenuazioneMin(String attenuazioneMin) { this.attenuazioneMin = attenuazioneMin; } public String getAttenuazioneMax() { return this.attenuazioneMax; } public void setAttenuazioneMax(String attenuazioneMax) { this.attenuazioneMax = attenuazioneMax; } public String getTemperaturaMin() { return this.temperaturaMin; } public void setTemperaturaMin(String temperaturaMin) { this.temperaturaMin = temperaturaMin; } public String getTemperaturaMax() { return this.temperaturaMax; } public void setTemperaturaMax(String temperaturaMax) { this.temperaturaMax = temperaturaMax; } public String getAttenuazioneMed() { if (attenuazioneMed != null && !"".equals(attenuazioneMed)) { return this.attenuazioneMed; } else if (getAttenuazioneMin() != null && !"".equals(getAttenuazioneMin()) && getAttenuazioneMax() != null && !"".equals(getAttenuazioneMax())) { return (String.valueOf((Integer.valueOf(getAttenuazioneMin())+Integer.valueOf(getAttenuazioneMax()))/2)); } return this.attenuazioneMed; } public void setAttenuazioneMed(String attenuazioneMed) { this.attenuazioneMed = attenuazioneMed; } public String getTemperaturaMaxFerm() { return temperaturaMaxFerm; } public void setTemperaturaMaxFerm(String temperaturaMaxFerm) { this.temperaturaMaxFerm = temperaturaMaxFerm; } public static String[] getCampiXml() { return campiXml; } public static void setCampiXml(String[] aCampiXml) { campiXml = aCampiXml; } @Override public Element toXml() { try { return Utils.toXml(this, campiXml); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } return null; } @Override public String getTag() { return "yeasts"; } @Override public String[] getXmlFields() { return campiXml; } }
rekhyt75/BrewPlus-IFDB
brewplus/brewplus-ifdb/src/main/java/jmash/YeastType.java
Java
gpl-3.0
4,355
/* * Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "cros_gralloc_helpers.h" #include <cstdlib> #include <cutils/log.h> #include <fcntl.h> #include <xf86drm.h> uint64_t cros_gralloc_convert_flags(int flags) { uint64_t usage = DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_CURSOR) usage |= DRV_BO_USE_CURSOR; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_RARELY) usage |= DRV_BO_USE_SW_READ_RARELY; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_OFTEN) usage |= DRV_BO_USE_SW_READ_OFTEN; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_RARELY) usage |= DRV_BO_USE_SW_WRITE_RARELY; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_OFTEN) usage |= DRV_BO_USE_SW_WRITE_OFTEN; if (flags & GRALLOC_USAGE_HW_TEXTURE) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_RENDER) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_2D) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_COMPOSER) /* HWC wants to use display hardware, but can defer to OpenGL. */ usage |= DRV_BO_USE_SCANOUT | DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_FB) usage |= DRV_BO_USE_SCANOUT; if (flags & GRALLOC_USAGE_EXTERNAL_DISP) /* We're ignoring this flag until we decide what to with display link */ usage |= DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_PROTECTED) usage |= DRV_BO_USE_PROTECTED; if (flags & GRALLOC_USAGE_HW_VIDEO_ENCODER) /*HACK: See b/30054495 */ usage |= DRV_BO_USE_SW_READ_OFTEN; if (flags & GRALLOC_USAGE_HW_CAMERA_WRITE) usage |= DRV_BO_USE_HW_CAMERA_WRITE; if (flags & GRALLOC_USAGE_HW_CAMERA_READ) usage |= DRV_BO_USE_HW_CAMERA_READ; if (flags & GRALLOC_USAGE_HW_CAMERA_ZSL) usage |= DRV_BO_USE_HW_CAMERA_ZSL; if (flags & GRALLOC_USAGE_RENDERSCRIPT) usage |= DRV_BO_USE_RENDERSCRIPT; return usage; } drv_format_t cros_gralloc_convert_format(int format) { /* * Conversion from HAL to fourcc-based DRV formats based on * platform_android.c in mesa. */ switch (format) { case HAL_PIXEL_FORMAT_BGRA_8888: return DRV_FORMAT_ARGB8888; case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED: return DRV_FORMAT_FLEX_IMPLEMENTATION_DEFINED; case HAL_PIXEL_FORMAT_RGB_565: return DRV_FORMAT_RGB565; case HAL_PIXEL_FORMAT_RGB_888: return DRV_FORMAT_RGB888; case HAL_PIXEL_FORMAT_RGBA_8888: return DRV_FORMAT_ABGR8888; case HAL_PIXEL_FORMAT_RGBX_8888: return DRV_FORMAT_XBGR8888; case HAL_PIXEL_FORMAT_YCbCr_420_888: return DRV_FORMAT_FLEX_YCbCr_420_888; case HAL_PIXEL_FORMAT_YV12: return DRV_FORMAT_YVU420; } return DRV_FORMAT_NONE; } static int32_t cros_gralloc_query_rendernode(struct driver **drv, const char *name) { /* TODO(gsingh): Enable render nodes on udl/evdi. */ int fd; drmVersionPtr version; char const *str = "%s/renderD%d"; int32_t num_nodes = 63; int32_t min_node = 128; int32_t max_node = (min_node + num_nodes); for (int i = min_node; i < max_node; i++) { char *node; if (asprintf(&node, str, DRM_DIR_NAME, i) < 0) continue; fd = open(node, O_RDWR, 0); free(node); if (fd < 0) continue; version = drmGetVersion(fd); if (version && name && !strcmp(version->name, name)) { drmFreeVersion(version); continue; } drmFreeVersion(version); *drv = drv_create(fd); if (*drv) return CROS_GRALLOC_ERROR_NONE; } return CROS_GRALLOC_ERROR_NO_RESOURCES; } int32_t cros_gralloc_rendernode_open(struct driver **drv) { int32_t ret; ret = cros_gralloc_query_rendernode(drv, NULL); /* Look for vgem driver if no hardware is found. */ if (ret) ret = cros_gralloc_query_rendernode(drv, "vgem"); return ret; } int32_t cros_gralloc_validate_handle(struct cros_gralloc_handle *hnd) { if (!hnd || hnd->magic != cros_gralloc_magic()) return CROS_GRALLOC_ERROR_BAD_HANDLE; return CROS_GRALLOC_ERROR_NONE; } void cros_gralloc_log(const char *prefix, const char *file, int line, const char *format, ...) { va_list args; va_start(args, format); ALOGE("%s - [%s(%d)]", prefix, basename(file), line); __android_log_vprint(ANDROID_LOG_ERROR, prefix, format, args); va_end(args); }
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/minigbm/src/cros_gralloc/cros_gralloc_helpers.cc
C++
gpl-3.0
4,210
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { observer } from 'mobx-react'; import { Button, GasPriceEditor } from '~/ui'; import TransactionMainDetails from '../TransactionMainDetails'; import TransactionPendingForm from '../TransactionPendingForm'; import styles from './transactionPending.css'; import * as tUtil from '../util/transaction'; @observer export default class TransactionPending extends Component { static contextTypes = { api: PropTypes.object.isRequired }; static propTypes = { className: PropTypes.string, date: PropTypes.instanceOf(Date).isRequired, focus: PropTypes.bool, gasLimit: PropTypes.object, id: PropTypes.object.isRequired, isSending: PropTypes.bool.isRequired, isTest: PropTypes.bool.isRequired, nonce: PropTypes.number, onConfirm: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, store: PropTypes.object.isRequired, transaction: PropTypes.shape({ data: PropTypes.string, from: PropTypes.string.isRequired, gas: PropTypes.object.isRequired, gasPrice: PropTypes.object.isRequired, to: PropTypes.string, value: PropTypes.object.isRequired }).isRequired }; static defaultProps = { focus: false }; gasStore = new GasPriceEditor.Store(this.context.api, { gas: this.props.transaction.gas.toFixed(), gasLimit: this.props.gasLimit, gasPrice: this.props.transaction.gasPrice.toFixed() }); componentWillMount () { const { store, transaction } = this.props; const { from, gas, gasPrice, to, value } = transaction; const fee = tUtil.getFee(gas, gasPrice); // BigNumber object const gasPriceEthmDisplay = tUtil.getEthmFromWeiDisplay(gasPrice); const gasToDisplay = tUtil.getGasDisplay(gas); const totalValue = tUtil.getTotalValue(fee, value); this.setState({ gasPriceEthmDisplay, totalValue, gasToDisplay }); this.gasStore.setEthValue(value); store.fetchBalances([from, to]); } render () { return this.gasStore.isEditing ? this.renderGasEditor() : this.renderTransaction(); } renderTransaction () { const { className, focus, id, isSending, isTest, store, transaction } = this.props; const { totalValue } = this.state; const { from, value } = transaction; const fromBalance = store.balances[from]; return ( <div className={ `${styles.container} ${className}` }> <TransactionMainDetails className={ styles.transactionDetails } from={ from } fromBalance={ fromBalance } gasStore={ this.gasStore } id={ id } isTest={ isTest } totalValue={ totalValue } transaction={ transaction } value={ value } /> <TransactionPendingForm address={ from } focus={ focus } isSending={ isSending } onConfirm={ this.onConfirm } onReject={ this.onReject } /> </div> ); } renderGasEditor () { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ); } onConfirm = (data) => { const { id, transaction } = this.props; const { password, wallet } = data; const { gas, gasPrice } = this.gasStore.overrideTransaction(transaction); this.props.onConfirm({ gas, gasPrice, id, password, wallet }); } onReject = () => { this.props.onReject(this.props.id); } toggleGasEditor = () => { this.gasStore.setEditing(false); } }
jesuscript/parity
js/src/views/Signer/components/TransactionPending/transactionPending.js
JavaScript
gpl-3.0
4,499
from controllers.job_ctrl import JobController from models.job_model import JobModel from views.job_view import JobView class MainController(object): def __init__(self, main_model): self.main_view = None self.main_model = main_model self.main_model.begin_job_fetch.connect(self.on_begin_job_fetch) self.main_model.update_job_fetch_progress.connect(self.on_job_fetch_update) self.main_model.fetched_job.connect(self.on_fetched_job) def init_ui(self, main_view): self.main_view = main_view self.init_hotkeys() def init_hotkeys(self): self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "J"], self.main_view.focus_job_num_edit) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "O"], self.main_view.open_current_job_folder) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "B"], self.main_view.open_current_job_basecamp) self.main_model.hotkey_model.start_detection() def fetch_job(self): job_num = self.main_view.job_num if self.main_model.job_exists(job_num): self.main_view.show_job_already_exists_dialog() return self.main_model.fetch_job(job_num) def cancel_job_fetch(self): self.main_model.cancel_job_fetch() def on_begin_job_fetch(self, max): self.main_view.show_job_fetch_progress_dialog(max) def on_job_fetch_update(self, progress): self.main_view.update_job_fetch_progress_dialog(progress) def on_fetched_job(self, job_num, base_folder): job = JobModel(job_num, base_folder, self.main_model.settings_model.basecamp_email, self.main_model.settings_model.basecamp_password, self.main_model.settings_model.google_maps_js_api_key, self.main_model.settings_model.google_maps_static_api_key, self.main_model.settings_model.google_earth_exe_path, self.main_model.settings_model.scene_exe_path) self.main_model.jobs[job.job_num] = job found = bool(job.base_folder) self.main_view.close_job_fetch_progress_dialog() if not found: open_anyway = self.main_view.show_job_not_found_dialog() if not open_anyway: return job_view = JobView(JobController(job)) job_view.request_minimize.connect(self.main_view.close) self.main_view.add_tab(job_view, job.job_name) def remove_job(self, index): job_num = int(self.main_view.ui.jobs_tab_widget.tabText(index)[1:]) self.main_model.jobs.pop(job_num, None) self.main_view.remove_tab(index)
redline-forensics/auto-dm
controllers/main_ctrl.py
Python
gpl-3.0
2,757
<?php namespace ModulusAcl\Form; use ModulusForm\Form\FormDefault, Zend\Form\Element\Select; class Route extends FormDefault { public function addElements() { $this->add(array( 'name' => 'id', 'options' => array( 'label' => '', ), 'attributes' => array( 'type' => 'hidden' ), )); $this->add(array( 'name' => 'route', 'options' => array( 'label' => 'Rota: ', 'value_options' => array( ), ), 'type' => 'Zend\Form\Element\Select', 'attributes' => array( 'placeholder' => 'Selecione a url', ), )); $this->add(array( 'name' => 'displayName', 'options' => array( 'label' => 'Nome de exibição: ', ), 'type' => 'Zend\Form\Element\Text', 'attributes' => array( 'placeholder' => 'Entre com o nome', ), )); $this->add(array( 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'name' => 'role', 'options' => array( 'label' => 'Tipo de usuário: ', 'object_manager' => $this->getEntityManager(), 'target_class' => 'ModulusAcl\Entity\AclRole', 'find_method' => array( 'name' => 'findByActives', 'params' => array('criteria' => array()), ), 'property' => 'name', 'selected' =>1, 'empty_option' => '', ), )); $this->add(array( 'type' => 'ModulusForm\Form\Element\Toggle', 'name' => 'doLog', 'options' => array( 'label' => 'Log ao acessar? ', ), )); $this->add(new \Zend\Form\Element\Csrf('security')); $this->add(array( 'name' => 'submit', 'attributes' => array( 'value' => 'Salvar', 'type' => 'submit', 'class' => 'btn btn-primary', ), )); } }
ZF2-Modulus/ModulusAcl
src/ModulusAcl/Form/Route.php
PHP
gpl-3.0
2,291
package edu.stanford.nlp.mt.lm; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.Sequence; import edu.stanford.nlp.mt.util.TokenUtils; import edu.stanford.nlp.mt.util.Vocabulary; /** * KenLM language model support via JNI. * * @author daniel cer * @author Spence Green * @author Kenneth Heafield * */ public class KenLanguageModel implements LanguageModel<IString> { private static final Logger logger = LogManager.getLogger(KenLanguageModel.class.getName()); private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final KenLMState ZERO_LENGTH_STATE = new KenLMState(0.0f, EMPTY_INT_ARRAY, 0); public static final String KENLM_LIBRARY_NAME = "PhrasalKenLM"; static { try { System.loadLibrary(KENLM_LIBRARY_NAME); logger.info("Loaded KenLM JNI library."); } catch (java.lang.UnsatisfiedLinkError e) { logger.fatal("KenLM has not been compiled!", e); System.exit(-1); } } private final KenLM model; private final String name; private AtomicReference<int[]> istringIdToKenLMId; private final ReentrantLock preventDuplicateWork = new ReentrantLock(); /** * Constructor for multi-threaded queries. * * @param filename */ public KenLanguageModel(String filename) { model = new KenLM(filename); name = String.format("KenLM(%s)", filename); initializeIdTable(); } /** * Create the mapping between IString word ids and KenLM word ids. */ private void initializeIdTable() { // Don't remove this line!! Sanity check to make sure that start and end load before // building the index. logger.info("Special tokens: start: {} end: {}", TokenUtils.START_TOKEN, TokenUtils.END_TOKEN); int[] table = new int[Vocabulary.systemSize()]; for (int i = 0; i < table.length; ++i) { table[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId = new AtomicReference<int[]>(table); } /** * Maps the IString id to a kenLM id. If the IString * id is out of range, update the vocab mapping. * @param token * @return kenlm id of the string */ private int toKenLMId(IString token) { { int[] map = istringIdToKenLMId.get(); if (token.id < map.length) { return map[token.id]; } } // Rare event: we have to expand the vocabulary. // In principle, this doesn't need to be a lock, but it does // prevent unnecessary work duplication. if (preventDuplicateWork.tryLock()) { // This thread is responsible for updating the mapping. try { // Maybe another thread did the work for us? int[] oldTable = istringIdToKenLMId.get(); if (token.id < oldTable.length) { return oldTable[token.id]; } int[] newTable = new int[Vocabulary.systemSize()]; System.arraycopy(oldTable, 0, newTable, 0, oldTable.length); for (int i = oldTable.length; i < newTable.length; ++i) { newTable[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId.set(newTable); return newTable[token.id]; } finally { preventDuplicateWork.unlock(); } } // Another thread is working. Lookup directly. return model.index(token.toString()); } @Override public IString getStartToken() { return TokenUtils.START_TOKEN; } @Override public IString getEndToken() { return TokenUtils.END_TOKEN; } @Override public String getName() { return name; } @Override public int order() { return model.order(); } @Override public LMState score(Sequence<IString> sequence, int startIndex, LMState priorState) { if (sequence.size() == 0) { // Source deletion rule return priorState == null ? ZERO_LENGTH_STATE : priorState; } // Extract prior state final int[] state = priorState == null ? EMPTY_INT_ARRAY : ((KenLMState) priorState).getState(); final int[] ngramIds = makeKenLMInput(sequence, state); if (sequence.size() == 1 && priorState == null && sequence.get(0).equals(TokenUtils.START_TOKEN)) { // Special case: Source deletion rule (e.g., from the OOV model) at the start of a string assert ngramIds.length == 1; return new KenLMState(0.0f, ngramIds, ngramIds.length); } // Reverse the start index for KenLM final int kenLMStartIndex = ngramIds.length - state.length - startIndex - 1; assert kenLMStartIndex >= 0; // Execute the query (via JNI) and construct the return state final long got = model.scoreSeqMarshalled(ngramIds, kenLMStartIndex); return new KenLMState(KenLM.scoreFromMarshalled(got), ngramIds, KenLM.rightStateFromMarshalled(got)); } /** * Convert a Sequence and an optional state to an input for KenLM. * * @param sequence * @param priorState * @return */ private int[] makeKenLMInput(Sequence<IString> sequence, int[] priorState) { final int sequenceSize = sequence.size(); int[] ngramIds = new int[sequenceSize + priorState.length]; if (priorState.length > 0) { System.arraycopy(priorState, 0, ngramIds, sequenceSize, priorState.length); } for (int i = 0; i < sequenceSize; i++) { // Notice: ngramids are in reverse order vv. the Sequence ngramIds[sequenceSize-1-i] = toKenLMId(sequence.get(i)); } return ngramIds; } // TODO(spenceg) This never yielded an improvement.... // private static final int DEFAULT_CACHE_SIZE = 10000; // private static final ThreadLocal<KenLMCache> threadLocalCache = // new ThreadLocal<KenLMCache>(); // // private static class KenLMCache { // private final long[] keys; // private final long[] values; // private final int mask; // public KenLMCache(int size) { // this.keys = new long[size]; // this.values = new long[size]; // this.mask = size - 1; // } // // public Long get(int[] kenLMInput, int startIndex) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // return keys[k] == hashValue ? values[k] : null; // } // private int ideal(long hashed) { // return ((int)hashed) & mask; // } // public void insert(int[] kenLMInput, int startIndex, long value) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // keys[k] = hashValue; // values[k] = value; // } // } }
Andy-Peng/phrasal
src/edu/stanford/nlp/mt/lm/KenLanguageModel.java
Java
gpl-3.0
6,706
// Decompiled with JetBrains decompiler // Type: System.Xml.Linq.BaseUriAnnotation // Assembly: System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: D3650A80-743D-4EFB-8926-AE790E9DB30F // Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll namespace System.Xml.Linq { internal class BaseUriAnnotation { internal string baseUri; public BaseUriAnnotation(string baseUri) { this.baseUri = baseUri; } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Xml.Linq/System/Xml/Linq/BaseUriAnnotation.cs
C#
gpl-3.0
530
#!/usr/bin/python # # Problem: Making Chess Boards # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out from heapq import * def process(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: if g[i][j] == None: s[i][j] = 0 elif i == 0 or j == 0: s[i][j] = 1 elif g[i-1][j] != g[i][j] and g[i][j-1] != g[i][j] and \ g[i-1][j-1] == g[i][j]: s[i][j] = 1 + min(s[i-1][j], s[i][j-1], s[i-1][j-1]) else: s[i][j] = 1 heappush(q, (-s[i][j], i, j)) def clear(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: g[i][j] = None for case in range(int(raw_input())): m, n = map(int, raw_input().split()) v = [eval('0x'+raw_input()) for i in range(m)] g = map(lambda x: map(lambda y: (x>>y)%2, range(n)[::-1]), v) s = [[1 for i in range(n)] for j in range(m)] q = [] process(0, m, 0, n) b = [] while q: x, r, c = heappop(q) if x != 0 and s[r][c] == -x: b.append((-x, r, c)) clear(r+x+1, r+1, c+x+1, c+1) process(r+x+1, r-x+1, c+x+1, c-x+1) vs = sorted(list(set(map(lambda x: x[0], b))))[::-1] print "Case #%d: %d" % (case+1, len(vs)) for k in vs: print k, len(filter(lambda x: x[0] == k, b))
KirarinSnow/Google-Code-Jam
Round 1C 2010/C.py
Python
gpl-3.0
1,627
// Decompiled with JetBrains decompiler // Type: System.Boolean // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll using System.Runtime.InteropServices; namespace System { /// <summary> /// Represents a Boolean value. /// </summary> /// <filterpriority>1</filterpriority> [ComVisible(true)] [__DynamicallyInvokable] [Serializable] public struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool> { /// <summary> /// Represents the Boolean value true as a string. This field is read-only. /// </summary> /// <filterpriority>1</filterpriority> [__DynamicallyInvokable] public static readonly string TrueString = "True"; /// <summary> /// Represents the Boolean value false as a string. This field is read-only. /// </summary> /// <filterpriority>1</filterpriority> [__DynamicallyInvokable] public static readonly string FalseString = "False"; internal const int True = 1; internal const int False = 0; internal const string TrueLiteral = "True"; internal const string FalseLiteral = "False"; private bool m_value; /// <summary> /// Returns the hash code for this instance. /// </summary> /// /// <returns> /// A hash code for the current <see cref="T:System.Boolean"/>. /// </returns> /// <filterpriority>2</filterpriority> [__DynamicallyInvokable] public override int GetHashCode() { return !this ? 0 : 1; } /// <summary> /// Converts the value of this instance to its equivalent string representation (either "True" or "False"). /// </summary> /// /// <returns> /// <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. /// </returns> /// <filterpriority>2</filterpriority> [__DynamicallyInvokable] public override string ToString() { return !this ? "False" : "True"; } /// <summary> /// Converts the value of this instance to its equivalent string representation (either "True" or "False"). /// </summary> /// /// <returns> /// <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. /// </returns> /// <param name="provider">(Reserved) An <see cref="T:System.IFormatProvider"/> object. </param><filterpriority>2</filterpriority> public string ToString(IFormatProvider provider) { return !this ? "False" : "True"; } /// <summary> /// Returns a value indicating whether this instance is equal to a specified object. /// </summary> /// /// <returns> /// true if <paramref name="obj"/> is a <see cref="T:System.Boolean"/> and has the same value as this instance; otherwise, false. /// </returns> /// <param name="obj">An object to compare to this instance. </param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public override bool Equals(object obj) { if (!(obj is bool)) return false; return this == (bool) obj; } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="T:System.Boolean"/> object. /// </summary> /// /// <returns> /// true if <paramref name="obj"/> has the same value as this instance; otherwise, false. /// </returns> /// <param name="obj">A <see cref="T:System.Boolean"/> value to compare to this instance.</param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public bool Equals(bool obj) { return this == obj; } /// <summary> /// Compares this instance to a specified object and returns an integer that indicates their relationship to one another. /// </summary> /// /// <returns> /// A signed integer that indicates the relative order of this instance and <paramref name="obj"/>.Return Value Condition Less than zero This instance is false and <paramref name="obj"/> is true. Zero This instance and <paramref name="obj"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="obj"/> is false.-or- <paramref name="obj"/> is null. /// </returns> /// <param name="obj">An object to compare to this instance, or null. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not a <see cref="T:System.Boolean"/>. </exception><filterpriority>2</filterpriority> public int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is bool)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeBoolean")); if (this == (bool) obj) return 0; return !this ? -1 : 1; } /// <summary> /// Compares this instance to a specified <see cref="T:System.Boolean"/> object and returns an integer that indicates their relationship to one another. /// </summary> /// /// <returns> /// A signed integer that indicates the relative values of this instance and <paramref name="value"/>.Return Value Condition Less than zero This instance is false and <paramref name="value"/> is true. Zero This instance and <paramref name="value"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="value"/> is false. /// </returns> /// <param name="value">A <see cref="T:System.Boolean"/> object to compare to this instance. </param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public int CompareTo(bool value) { if (this == value) return 0; return !this ? -1 : 1; } /// <summary> /// Converts the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent, or throws an exception if the string is not equivalent to the value of <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. /// </summary> /// /// <returns> /// true if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> field; false if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.FalseString"/> field. /// </returns> /// <param name="value">A string containing the value to convert. </param><exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null. </exception><exception cref="T:System.FormatException"><paramref name="value"/> is not equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field. </exception><filterpriority>1</filterpriority> [__DynamicallyInvokable] public static bool Parse(string value) { if (value == null) throw new ArgumentNullException("value"); bool result = false; if (!bool.TryParse(value, out result)) throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); return result; } /// <summary> /// Tries to convert the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent. A return value indicates whether the conversion succeeded or failed. /// </summary> /// /// <returns> /// true if <paramref name="value"/> was converted successfully; otherwise, false. /// </returns> /// <param name="value">A string containing the value to convert. </param><param name="result">When this method returns, if the conversion succeeded, contains true if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.TrueString"/> or false if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.FalseString"/>. If the conversion failed, contains false. The conversion fails if <paramref name="value"/> is null or is not equivalent to the value of either the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field.</param><filterpriority>1</filterpriority> [__DynamicallyInvokable] public static bool TryParse(string value, out bool result) { result = false; if (value == null) return false; if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if ("False".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } value = bool.TrimWhiteSpaceAndNull(value); if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (!"False".Equals(value, StringComparison.OrdinalIgnoreCase)) return false; result = false; return true; } /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for value type <see cref="T:System.Boolean"/>. /// </summary> /// /// <returns> /// The enumerated constant, <see cref="F:System.TypeCode.Boolean"/>. /// </returns> /// <filterpriority>2</filterpriority> public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return this; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible) (bool) (this ? 1 : 0), type, provider); } private static string TrimWhiteSpaceAndNull(string value) { int startIndex = 0; int index = value.Length - 1; char ch = char.MinValue; while (startIndex < value.Length && (char.IsWhiteSpace(value[startIndex]) || (int) value[startIndex] == (int) ch)) ++startIndex; while (index >= startIndex && (char.IsWhiteSpace(value[index]) || (int) value[index] == (int) ch)) --index; return value.Substring(startIndex, index - startIndex + 1); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/mscorlib/System/Boolean.cs
C#
gpl-3.0
11,794
/* * Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer, * Rico Lieback, Sebastian Gabriel, Lothar Gesslein, * Alexander Rampp, Kai Weidner * * This file is part of the Physalix Enrollment System * * Foobar 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. * * Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package hsa.awp.usergui; import hsa.awp.event.model.Event; import hsa.awp.event.model.Occurrence; import hsa.awp.user.model.SingleUser; import hsa.awp.user.model.User; import hsa.awp.usergui.controller.IUserGuiController; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Panel showing detailed information about an {@link Event}. * * @author klassm */ public class EventDetailPanel extends Panel { /** * unique serialization id. */ private static final long serialVersionUID = 9180564827437598145L; /** * GuiController which feeds the Gui with Data. */ @SpringBean(name = "usergui.controller") private transient IUserGuiController controller; /** * Constructor. * * @param id wicket:id. * @param event event to show. */ public EventDetailPanel(String id, Event event) { super(id); List<SingleUser> teachers = new LinkedList<SingleUser>(); event = controller.getEventById(event.getId()); for (Long teacherId : event.getTeachers()) { User user = controller.getUserById(teacherId); if (user != null && user instanceof SingleUser) { teachers.add((SingleUser) user); } } Collections.sort(teachers, new Comparator<SingleUser>() { @Override public int compare(SingleUser o1, SingleUser o2) { return o1.getName().compareTo(o2.getName()); } }); StringBuffer teachersList = new StringBuffer(); if (teachers.size() == 0) { teachersList.append("keine"); } else { boolean first = true; for (SingleUser teacher : teachers) { if (first) { first = false; } else { teachersList.append(", "); } teachersList.append(teacher.getName()); } } WebMarkupContainer eventGeneral = new WebMarkupContainer("event.general"); add(eventGeneral); eventGeneral.add(new Label("event.general.caption", "Allgemeines")); eventGeneral.add(new Label("event.general.eventId", new Model<Integer>(event.getEventId()))); eventGeneral.add(new Label("event.general.subjectName", new Model<String>(event.getSubject().getName()))); eventGeneral.add(new Label("event.general.maxParticipants", new Model<Integer>(event.getMaxParticipants()))); Label teacherLabel = new Label("event.general.teachers", new Model<String>(teachersList.toString())); eventGeneral.add(teacherLabel); eventGeneral.add(new Label("event.general.eventDescription", new Model<String>(event.getDetailInformation()))); ExternalLink detailLink = new ExternalLink("event.general.link", event.getSubject().getLink()); eventGeneral.add(detailLink); detailLink.add(new Label("event.general.linkDesc", event.getSubject().getLink())); String description = event.getSubject().getDescription(); if (description == null || ((description = description.trim().replace("\n", "<br>")).equals(""))) { description = "keine"; } Label subjectDescription = new Label("event.general.subjectDescription", new Model<String>(description)); subjectDescription.setEscapeModelStrings(false); eventGeneral.add(subjectDescription); WebMarkupContainer eventTimetable = new WebMarkupContainer("event.timetable"); add(eventTimetable); eventTimetable.add(new Label("event.timetable.caption", "Stundenplan")); List<Occurrence> occurences; if (event.getTimetable() == null) { occurences = new LinkedList<Occurrence>(); } else { occurences = new LinkedList<Occurrence>(event.getTimetable().getOccurrences()); } eventTimetable.add(new ListView<Occurrence>("event.timetable.list", occurences) { /** * unique serialization id. */ private static final long serialVersionUID = -1041971433878928045L; @Override protected void populateItem(ListItem<Occurrence> item) { DateFormat singleFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); DateFormat dayFormat = new SimpleDateFormat("EEEE"); DateFormat timeFormat = new SimpleDateFormat("HH:mm"); String s; switch (item.getModelObject().getType()) { case SINGLE: s = "Einzeltermin vom " + singleFormat.format(item.getModelObject().getStartDate().getTime()); s += " bis " + singleFormat.format(item.getModelObject().getEndDate().getTime()); break; case PERIODICAL: s = "Wöchentlich am " + dayFormat.format(item.getModelObject().getStartDate().getTime()); s += " von " + timeFormat.format(item.getModelObject().getStartDate().getTime()) + " bis " + timeFormat.format(item.getModelObject().getEndDate().getTime()); break; default: s = ""; } item.add(new Label("event.timetable.list.occurrence", s)); } }); if (occurences.size() == 0) { eventTimetable.setVisible(false); } } }
physalix-enrollment/physalix
UserGui/src/main/java/hsa/awp/usergui/EventDetailPanel.java
Java
gpl-3.0
6,335
// Copyright (C) 2015 xaizek <xaizek@posteo.net> // // This file is part of dit. // // dit is free software: you can redistribute it and/or modify // it under the terms of version 3 of the GNU Affero General Public // License as published by the Free Software Foundation. // // dit 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 dit. If not, see <http://www.gnu.org/licenses/>. #include <cassert> #include <cstdlib> #include <functional> #include <ostream> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "Command.hpp" #include "Commands.hpp" #include "Config.hpp" #include "Dit.hpp" #include "Project.hpp" namespace fs = boost::filesystem; /** * @brief Usage message for "complete" command. */ const char *const USAGE = "Usage: complete <regular args>"; namespace { /** * @brief Implementation of "complete" command, which helps with completion. */ class CompleteCmd : public AutoRegisteredCommand<CompleteCmd> { public: /** * @brief Constructs the command implementation. */ CompleteCmd(); public: /** * @copydoc Command::run() */ virtual boost::optional<int> run( Dit &dit, const std::vector<std::string> &args) override; }; } CompleteCmd::CompleteCmd() : parent("complete", "perform command-line completion", USAGE) { } boost::optional<int> CompleteCmd::run(Dit &dit, const std::vector<std::string> &args) { std::ostringstream estream; int exitCode = dit.complete(args, out(), estream); if (!estream.str().empty()) { // Calling err() has side effects, so don't call unless error occurred. err() << estream.str(); } return exitCode; }
xaizek/dit
src/cmds/CompleteCmd.cpp
C++
gpl-3.0
1,964
namespace DemoWinForm { partial class frmMapFinder { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.comboBox7 = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.comboBox8 = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.comboBox9 = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBox5 = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBox6 = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.comboBox4 = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cmbCity = new System.Windows.Forms.ComboBox(); this.lblLandParcelCity = new System.Windows.Forms.Label(); this.cmbCountry = new System.Windows.Forms.ComboBox(); this.lblLandParcelCountry = new System.Windows.Forms.Label(); this.comboBox10 = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.comboBox11 = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.comboBox12 = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.comboBox13 = new System.Windows.Forms.ComboBox(); this.label13 = new System.Windows.Forms.Label(); this.comboBox14 = new System.Windows.Forms.ComboBox(); this.label14 = new System.Windows.Forms.Label(); this.comboBox15 = new System.Windows.Forms.ComboBox(); this.label15 = new System.Windows.Forms.Label(); this.comboBox16 = new System.Windows.Forms.ComboBox(); this.label16 = new System.Windows.Forms.Label(); this.comboBox17 = new System.Windows.Forms.ComboBox(); this.label17 = new System.Windows.Forms.Label(); this.comboBox18 = new System.Windows.Forms.ComboBox(); this.label18 = new System.Windows.Forms.Label(); this.comboBox19 = new System.Windows.Forms.ComboBox(); this.label19 = new System.Windows.Forms.Label(); this.comboBox20 = new System.Windows.Forms.ComboBox(); this.label20 = new System.Windows.Forms.Label(); this.spltMapFinder = new System.Windows.Forms.SplitContainer(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.comboBox21 = new System.Windows.Forms.ComboBox(); this.label21 = new System.Windows.Forms.Label(); this.comboBox22 = new System.Windows.Forms.ComboBox(); this.label22 = new System.Windows.Forms.Label(); this.comboBox23 = new System.Windows.Forms.ComboBox(); this.label23 = new System.Windows.Forms.Label(); this.comboBox24 = new System.Windows.Forms.ComboBox(); this.label24 = new System.Windows.Forms.Label(); this.comboBox25 = new System.Windows.Forms.ComboBox(); this.label25 = new System.Windows.Forms.Label(); this.comboBox26 = new System.Windows.Forms.ComboBox(); this.label26 = new System.Windows.Forms.Label(); this.comboBox27 = new System.Windows.Forms.ComboBox(); this.label27 = new System.Windows.Forms.Label(); this.comboBox28 = new System.Windows.Forms.ComboBox(); this.label28 = new System.Windows.Forms.Label(); this.comboBox29 = new System.Windows.Forms.ComboBox(); this.label29 = new System.Windows.Forms.Label(); this.comboBox30 = new System.Windows.Forms.ComboBox(); this.label30 = new System.Windows.Forms.Label(); this.comboBox31 = new System.Windows.Forms.ComboBox(); this.label31 = new System.Windows.Forms.Label(); this.mapbxMapFinder = new SharpMap.Forms.MapBox(); this.spltMapFinder.Panel1.SuspendLayout(); this.spltMapFinder.Panel2.SuspendLayout(); this.spltMapFinder.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // comboBox7 // this.comboBox7.FormattingEnabled = true; this.comboBox7.Location = new System.Drawing.Point(216, 291); this.comboBox7.Name = "comboBox7"; this.comboBox7.Size = new System.Drawing.Size(319, 21); this.comboBox7.TabIndex = 85; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(146, 291); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 13); this.label2.TabIndex = 86; this.label2.Text = "Location"; // // comboBox8 // this.comboBox8.FormattingEnabled = true; this.comboBox8.Location = new System.Drawing.Point(216, 237); this.comboBox8.Name = "comboBox8"; this.comboBox8.Size = new System.Drawing.Size(319, 21); this.comboBox8.TabIndex = 83; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(128, 237); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(70, 13); this.label3.TabIndex = 84; this.label3.Text = "Sub-Location"; // // comboBox9 // this.comboBox9.FormattingEnabled = true; this.comboBox9.Location = new System.Drawing.Point(216, 264); this.comboBox9.Name = "comboBox9"; this.comboBox9.Size = new System.Drawing.Size(319, 21); this.comboBox9.TabIndex = 81; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(154, 264); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 13); this.label4.TabIndex = 82; this.label4.Text = "County"; // // comboBox2 // this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(216, 210); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(319, 21); this.comboBox2.TabIndex = 79; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(150, 213); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 13); this.label1.TabIndex = 80; this.label1.Text = "Location"; // // comboBox5 // this.comboBox5.FormattingEnabled = true; this.comboBox5.Location = new System.Drawing.Point(216, 156); this.comboBox5.Name = "comboBox5"; this.comboBox5.Size = new System.Drawing.Size(319, 21); this.comboBox5.TabIndex = 77; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(159, 156); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(39, 13); this.label5.TabIndex = 78; this.label5.Text = "District"; // // comboBox6 // this.comboBox6.FormattingEnabled = true; this.comboBox6.Location = new System.Drawing.Point(216, 183); this.comboBox6.Name = "comboBox6"; this.comboBox6.Size = new System.Drawing.Size(319, 21); this.comboBox6.TabIndex = 75; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(155, 183); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(44, 13); this.label6.TabIndex = 76; this.label6.Text = "Division"; // // comboBox4 // this.comboBox4.FormattingEnabled = true; this.comboBox4.Location = new System.Drawing.Point(216, 101); this.comboBox4.Name = "comboBox4"; this.comboBox4.Size = new System.Drawing.Size(319, 21); this.comboBox4.TabIndex = 73; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(159, 104); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(39, 13); this.label10.TabIndex = 74; this.label10.Text = "District"; // // comboBox3 // this.comboBox3.FormattingEnabled = true; this.comboBox3.Location = new System.Drawing.Point(216, 128); this.comboBox3.Name = "comboBox3"; this.comboBox3.Size = new System.Drawing.Size(319, 21); this.comboBox3.TabIndex = 71; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(155, 131); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(44, 13); this.label9.TabIndex = 72; this.label9.Text = "Division"; // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(216, 74); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(319, 21); this.comboBox1.TabIndex = 69; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(149, 77); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(49, 13); this.label7.TabIndex = 70; this.label7.Text = "Province"; // // cmbCity // this.cmbCity.FormattingEnabled = true; this.cmbCity.Location = new System.Drawing.Point(216, 44); this.cmbCity.Name = "cmbCity"; this.cmbCity.Size = new System.Drawing.Size(319, 21); this.cmbCity.TabIndex = 66; // // lblLandParcelCity // this.lblLandParcelCity.AutoSize = true; this.lblLandParcelCity.Location = new System.Drawing.Point(170, 44); this.lblLandParcelCity.Name = "lblLandParcelCity"; this.lblLandParcelCity.Size = new System.Drawing.Size(24, 13); this.lblLandParcelCity.TabIndex = 68; this.lblLandParcelCity.Text = "City"; // // cmbCountry // this.cmbCountry.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCountry.FormattingEnabled = true; this.cmbCountry.Location = new System.Drawing.Point(216, 17); this.cmbCountry.MaxDropDownItems = 10; this.cmbCountry.Name = "cmbCountry"; this.cmbCountry.Size = new System.Drawing.Size(319, 21); this.cmbCountry.TabIndex = 65; // // lblLandParcelCountry // this.lblLandParcelCountry.AutoSize = true; this.lblLandParcelCountry.Location = new System.Drawing.Point(151, 17); this.lblLandParcelCountry.Name = "lblLandParcelCountry"; this.lblLandParcelCountry.Size = new System.Drawing.Size(43, 13); this.lblLandParcelCountry.TabIndex = 67; this.lblLandParcelCountry.Text = "Country"; this.lblLandParcelCountry.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // comboBox10 // this.comboBox10.FormattingEnabled = true; this.comboBox10.Location = new System.Drawing.Point(216, 291); this.comboBox10.Name = "comboBox10"; this.comboBox10.Size = new System.Drawing.Size(319, 21); this.comboBox10.TabIndex = 85; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(146, 291); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(48, 13); this.label8.TabIndex = 86; this.label8.Text = "Location"; // // comboBox11 // this.comboBox11.FormattingEnabled = true; this.comboBox11.Location = new System.Drawing.Point(216, 237); this.comboBox11.Name = "comboBox11"; this.comboBox11.Size = new System.Drawing.Size(319, 21); this.comboBox11.TabIndex = 83; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(128, 237); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(70, 13); this.label11.TabIndex = 84; this.label11.Text = "Sub-Location"; // // comboBox12 // this.comboBox12.FormattingEnabled = true; this.comboBox12.Location = new System.Drawing.Point(216, 264); this.comboBox12.Name = "comboBox12"; this.comboBox12.Size = new System.Drawing.Size(319, 21); this.comboBox12.TabIndex = 81; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(154, 264); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(40, 13); this.label12.TabIndex = 82; this.label12.Text = "County"; // // comboBox13 // this.comboBox13.FormattingEnabled = true; this.comboBox13.Location = new System.Drawing.Point(216, 210); this.comboBox13.Name = "comboBox13"; this.comboBox13.Size = new System.Drawing.Size(319, 21); this.comboBox13.TabIndex = 79; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(150, 213); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(48, 13); this.label13.TabIndex = 80; this.label13.Text = "Location"; // // comboBox14 // this.comboBox14.FormattingEnabled = true; this.comboBox14.Location = new System.Drawing.Point(216, 156); this.comboBox14.Name = "comboBox14"; this.comboBox14.Size = new System.Drawing.Size(319, 21); this.comboBox14.TabIndex = 77; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(159, 156); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(39, 13); this.label14.TabIndex = 78; this.label14.Text = "District"; // // comboBox15 // this.comboBox15.FormattingEnabled = true; this.comboBox15.Location = new System.Drawing.Point(216, 183); this.comboBox15.Name = "comboBox15"; this.comboBox15.Size = new System.Drawing.Size(319, 21); this.comboBox15.TabIndex = 75; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(155, 183); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(44, 13); this.label15.TabIndex = 76; this.label15.Text = "Division"; // // comboBox16 // this.comboBox16.FormattingEnabled = true; this.comboBox16.Location = new System.Drawing.Point(216, 101); this.comboBox16.Name = "comboBox16"; this.comboBox16.Size = new System.Drawing.Size(319, 21); this.comboBox16.TabIndex = 73; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(159, 104); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(39, 13); this.label16.TabIndex = 74; this.label16.Text = "District"; // // comboBox17 // this.comboBox17.FormattingEnabled = true; this.comboBox17.Location = new System.Drawing.Point(216, 128); this.comboBox17.Name = "comboBox17"; this.comboBox17.Size = new System.Drawing.Size(319, 21); this.comboBox17.TabIndex = 71; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(155, 131); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(44, 13); this.label17.TabIndex = 72; this.label17.Text = "Division"; // // comboBox18 // this.comboBox18.FormattingEnabled = true; this.comboBox18.Location = new System.Drawing.Point(216, 74); this.comboBox18.Name = "comboBox18"; this.comboBox18.Size = new System.Drawing.Size(319, 21); this.comboBox18.TabIndex = 69; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(149, 77); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(49, 13); this.label18.TabIndex = 70; this.label18.Text = "Province"; // // comboBox19 // this.comboBox19.FormattingEnabled = true; this.comboBox19.Location = new System.Drawing.Point(216, 44); this.comboBox19.Name = "comboBox19"; this.comboBox19.Size = new System.Drawing.Size(319, 21); this.comboBox19.TabIndex = 66; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(170, 44); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(24, 13); this.label19.TabIndex = 68; this.label19.Text = "City"; // // comboBox20 // this.comboBox20.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox20.FormattingEnabled = true; this.comboBox20.Location = new System.Drawing.Point(216, 17); this.comboBox20.MaxDropDownItems = 10; this.comboBox20.Name = "comboBox20"; this.comboBox20.Size = new System.Drawing.Size(319, 21); this.comboBox20.TabIndex = 65; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(151, 17); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(43, 13); this.label20.TabIndex = 67; this.label20.Text = "Country"; this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // spltMapFinder // this.spltMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.spltMapFinder.Location = new System.Drawing.Point(0, 0); this.spltMapFinder.Name = "spltMapFinder"; this.spltMapFinder.Orientation = System.Windows.Forms.Orientation.Horizontal; // // spltMapFinder.Panel1 // this.spltMapFinder.Panel1.Controls.Add(this.groupBox1); // // spltMapFinder.Panel2 // this.spltMapFinder.Panel2.Controls.Add(this.mapbxMapFinder); this.spltMapFinder.Size = new System.Drawing.Size(874, 548); this.spltMapFinder.SplitterDistance = 240; this.spltMapFinder.TabIndex = 0; // // groupBox1 // this.groupBox1.Controls.Add(this.comboBox21); this.groupBox1.Controls.Add(this.label21); this.groupBox1.Controls.Add(this.comboBox22); this.groupBox1.Controls.Add(this.label22); this.groupBox1.Controls.Add(this.comboBox23); this.groupBox1.Controls.Add(this.label23); this.groupBox1.Controls.Add(this.comboBox24); this.groupBox1.Controls.Add(this.label24); this.groupBox1.Controls.Add(this.comboBox25); this.groupBox1.Controls.Add(this.label25); this.groupBox1.Controls.Add(this.comboBox26); this.groupBox1.Controls.Add(this.label26); this.groupBox1.Controls.Add(this.comboBox27); this.groupBox1.Controls.Add(this.label27); this.groupBox1.Controls.Add(this.comboBox28); this.groupBox1.Controls.Add(this.label28); this.groupBox1.Controls.Add(this.comboBox29); this.groupBox1.Controls.Add(this.label29); this.groupBox1.Controls.Add(this.comboBox30); this.groupBox1.Controls.Add(this.label30); this.groupBox1.Controls.Add(this.comboBox31); this.groupBox1.Controls.Add(this.label31); this.groupBox1.Location = new System.Drawing.Point(2, 5); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(870, 217); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search Map"; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // // comboBox21 // this.comboBox21.FormattingEnabled = true; this.comboBox21.Location = new System.Drawing.Point(514, 135); this.comboBox21.Name = "comboBox21"; this.comboBox21.Size = new System.Drawing.Size(319, 21); this.comboBox21.TabIndex = 85; this.comboBox21.SelectedIndexChanged += new System.EventHandler(this.comboBox21_SelectedIndexChanged); // // label21 // this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(419, 135); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(92, 13); this.label21.TabIndex = 86; this.label21.Text = "Universal Address"; // // comboBox22 // this.comboBox22.FormattingEnabled = true; this.comboBox22.Location = new System.Drawing.Point(514, 81); this.comboBox22.Name = "comboBox22"; this.comboBox22.Size = new System.Drawing.Size(319, 21); this.comboBox22.TabIndex = 83; // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(438, 84); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(70, 13); this.label22.TabIndex = 84; this.label22.Text = "Sub-Location"; // // comboBox23 // this.comboBox23.FormattingEnabled = true; this.comboBox23.Location = new System.Drawing.Point(514, 108); this.comboBox23.Name = "comboBox23"; this.comboBox23.Size = new System.Drawing.Size(319, 21); this.comboBox23.TabIndex = 81; // // label23 // this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(468, 109); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(40, 13); this.label23.TabIndex = 82; this.label23.Text = "County"; // // comboBox24 // this.comboBox24.FormattingEnabled = true; this.comboBox24.Location = new System.Drawing.Point(514, 54); this.comboBox24.Name = "comboBox24"; this.comboBox24.Size = new System.Drawing.Size(319, 21); this.comboBox24.TabIndex = 79; // // label24 // this.label24.AutoSize = true; this.label24.Location = new System.Drawing.Point(460, 55); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(48, 13); this.label24.TabIndex = 80; this.label24.Text = "Location"; // // comboBox25 // this.comboBox25.FormattingEnabled = true; this.comboBox25.Location = new System.Drawing.Point(81, 166); this.comboBox25.Name = "comboBox25"; this.comboBox25.Size = new System.Drawing.Size(319, 21); this.comboBox25.TabIndex = 77; // // label25 // this.label25.AutoSize = true; this.label25.Location = new System.Drawing.Point(24, 166); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(39, 13); this.label25.TabIndex = 78; this.label25.Text = "District"; // // comboBox26 // this.comboBox26.FormattingEnabled = true; this.comboBox26.Location = new System.Drawing.Point(514, 27); this.comboBox26.Name = "comboBox26"; this.comboBox26.Size = new System.Drawing.Size(319, 21); this.comboBox26.TabIndex = 75; // // label26 // this.label26.AutoSize = true; this.label26.Location = new System.Drawing.Point(464, 29); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(44, 13); this.label26.TabIndex = 76; this.label26.Text = "Division"; // // comboBox27 // this.comboBox27.FormattingEnabled = true; this.comboBox27.Location = new System.Drawing.Point(81, 111); this.comboBox27.Name = "comboBox27"; this.comboBox27.Size = new System.Drawing.Size(319, 21); this.comboBox27.TabIndex = 73; // // label27 // this.label27.AutoSize = true; this.label27.Location = new System.Drawing.Point(24, 114); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(39, 13); this.label27.TabIndex = 74; this.label27.Text = "District"; // // comboBox28 // this.comboBox28.FormattingEnabled = true; this.comboBox28.Location = new System.Drawing.Point(81, 138); this.comboBox28.Name = "comboBox28"; this.comboBox28.Size = new System.Drawing.Size(319, 21); this.comboBox28.TabIndex = 71; // // label28 // this.label28.AutoSize = true; this.label28.Location = new System.Drawing.Point(20, 141); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(44, 13); this.label28.TabIndex = 72; this.label28.Text = "Division"; // // comboBox29 // this.comboBox29.FormattingEnabled = true; this.comboBox29.Location = new System.Drawing.Point(81, 84); this.comboBox29.Name = "comboBox29"; this.comboBox29.Size = new System.Drawing.Size(319, 21); this.comboBox29.TabIndex = 69; // // label29 // this.label29.AutoSize = true; this.label29.Location = new System.Drawing.Point(14, 87); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(49, 13); this.label29.TabIndex = 70; this.label29.Text = "Province"; // // comboBox30 // this.comboBox30.FormattingEnabled = true; this.comboBox30.Location = new System.Drawing.Point(81, 54); this.comboBox30.Name = "comboBox30"; this.comboBox30.Size = new System.Drawing.Size(319, 21); this.comboBox30.TabIndex = 66; // // label30 // this.label30.AutoSize = true; this.label30.Location = new System.Drawing.Point(35, 54); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(24, 13); this.label30.TabIndex = 68; this.label30.Text = "City"; // // comboBox31 // this.comboBox31.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox31.FormattingEnabled = true; this.comboBox31.Location = new System.Drawing.Point(81, 27); this.comboBox31.MaxDropDownItems = 10; this.comboBox31.Name = "comboBox31"; this.comboBox31.Size = new System.Drawing.Size(319, 21); this.comboBox31.TabIndex = 65; // // label31 // this.label31.AutoSize = true; this.label31.Location = new System.Drawing.Point(16, 27); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(43, 13); this.label31.TabIndex = 67; this.label31.Text = "Country"; this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // mapbxMapFinder // this.mapbxMapFinder.ActiveTool = SharpMap.Forms.MapBox.Tools.None; this.mapbxMapFinder.BackColor = System.Drawing.SystemColors.Info; this.mapbxMapFinder.Cursor = System.Windows.Forms.Cursors.Default; this.mapbxMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.mapbxMapFinder.FineZoomFactor = 10; this.mapbxMapFinder.Location = new System.Drawing.Point(0, 0); this.mapbxMapFinder.Name = "mapbxMapFinder"; this.mapbxMapFinder.QueryLayerIndex = 0; this.mapbxMapFinder.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.Size = new System.Drawing.Size(874, 304); this.mapbxMapFinder.TabIndex = 5; this.mapbxMapFinder.WheelZoomMagnitude = 2; // // frmMapFinder // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(874, 548); this.Controls.Add(this.spltMapFinder); this.Name = "frmMapFinder"; this.Text = "frmMapFinder"; this.Load += new System.EventHandler(this.frmMapFinder_Load); this.spltMapFinder.Panel1.ResumeLayout(false); this.spltMapFinder.Panel2.ResumeLayout(false); this.spltMapFinder.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox comboBox7; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox8; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox9; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBox5; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox comboBox6; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox comboBox4; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox comboBox3; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cmbCity; private System.Windows.Forms.Label lblLandParcelCity; private System.Windows.Forms.ComboBox cmbCountry; private System.Windows.Forms.Label lblLandParcelCountry; private System.Windows.Forms.ComboBox comboBox10; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox comboBox11; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox comboBox12; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox comboBox13; private System.Windows.Forms.Label label13; private System.Windows.Forms.ComboBox comboBox14; private System.Windows.Forms.Label label14; private System.Windows.Forms.ComboBox comboBox15; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox comboBox16; private System.Windows.Forms.Label label16; private System.Windows.Forms.ComboBox comboBox17; private System.Windows.Forms.Label label17; private System.Windows.Forms.ComboBox comboBox18; private System.Windows.Forms.Label label18; private System.Windows.Forms.ComboBox comboBox19; private System.Windows.Forms.Label label19; private System.Windows.Forms.ComboBox comboBox20; private System.Windows.Forms.Label label20; private System.Windows.Forms.SplitContainer spltMapFinder; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox comboBox21; private System.Windows.Forms.Label label21; private System.Windows.Forms.ComboBox comboBox22; private System.Windows.Forms.Label label22; private System.Windows.Forms.ComboBox comboBox23; private System.Windows.Forms.Label label23; private System.Windows.Forms.ComboBox comboBox24; private System.Windows.Forms.Label label24; private System.Windows.Forms.ComboBox comboBox25; private System.Windows.Forms.Label label25; private System.Windows.Forms.ComboBox comboBox26; private System.Windows.Forms.Label label26; private System.Windows.Forms.ComboBox comboBox27; private System.Windows.Forms.Label label27; private System.Windows.Forms.ComboBox comboBox28; private System.Windows.Forms.Label label28; private System.Windows.Forms.ComboBox comboBox29; private System.Windows.Forms.Label label29; private System.Windows.Forms.ComboBox comboBox30; private System.Windows.Forms.Label label30; private System.Windows.Forms.ComboBox comboBox31; private System.Windows.Forms.Label label31; private SharpMap.Forms.MapBox mapbxMapFinder; } }
anonymouskeyboard47/Tripodmaps
ShapeFileTools/frmMapFinder.Designer.cs
C#
gpl-3.0
38,884
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dialer.calllog; import android.content.Context; import android.content.res.Resources; import android.provider.CallLog.Calls; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.Log; import com.android.contacts.common.CallUtil; import com.android.dialer.PhoneCallDetails; import com.android.dialer.PhoneCallDetailsHelper; import com.android.dialer.R; /** * Helper class to fill in the views of a call log entry. */ /* package */class CallLogListItemHelper { private static final String TAG = "CallLogListItemHelper"; /** Helper for populating the details of a phone call. */ private final PhoneCallDetailsHelper mPhoneCallDetailsHelper; /** Helper for handling phone numbers. */ private final PhoneNumberDisplayHelper mPhoneNumberHelper; /** Resources to look up strings. */ private final Resources mResources; /** * Creates a new helper instance. * * @param phoneCallDetailsHelper used to set the details of a phone call * @param phoneNumberHelper used to process phone number */ public CallLogListItemHelper(PhoneCallDetailsHelper phoneCallDetailsHelper, PhoneNumberDisplayHelper phoneNumberHelper, Resources resources) { mPhoneCallDetailsHelper = phoneCallDetailsHelper; mPhoneNumberHelper = phoneNumberHelper; mResources = resources; } /** * Sets the name, label, and number for a contact. * * @param context The application context. * @param views the views to populate * @param details the details of a phone call needed to fill in the data */ public void setPhoneCallDetails( Context context, CallLogListItemViews views, PhoneCallDetails details) { mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); // Set the accessibility text for the contact badge views.quickContactView.setContentDescription(getContactBadgeDescription(details)); // Set the primary action accessibility description views.primaryActionView.setContentDescription(getCallDescription(context, details)); // Cache name or number of caller. Used when setting the content descriptions of buttons // when the actions ViewStub is inflated. views.nameOrNumber = this.getNameOrNumber(details); } /** * Sets the accessibility descriptions for the action buttons in the action button ViewStub. * * @param views The views associated with the current call log entry. */ public void setActionContentDescriptions(CallLogListItemViews views) { if (views.nameOrNumber == null) { Log.e(TAG, "setActionContentDescriptions; name or number is null."); } // Calling expandTemplate with a null parameter will cause a NullPointerException. // Although we don't expect a null name or number, it is best to protect against it. CharSequence nameOrNumber = views.nameOrNumber == null ? "" : views.nameOrNumber; views.callBackButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_call_back_action), nameOrNumber)); views.videoCallButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_video_call_action), nameOrNumber)); views.voicemailButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_voicemail_action), nameOrNumber)); views.detailsButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_details_action), nameOrNumber)); } /** * Returns the accessibility description for the contact badge for a call log entry. * * @param details Details of call. * @return Accessibility description. */ private CharSequence getContactBadgeDescription(PhoneCallDetails details) { return mResources.getString(R.string.description_contact_details, getNameOrNumber(details)); } /** * Returns the accessibility description of the "return call/call" action for a call log * entry. * Accessibility text is a combination of: * {Voicemail Prefix}. {Number of Calls}. {Caller information} {Phone Account}. * If most recent call is a voicemail, {Voicemail Prefix} is "New Voicemail.", otherwise "". * * If more than one call for the caller, {Number of Calls} is: * "{number of calls} calls.", otherwise "". * * The {Caller Information} references the most recent call associated with the caller. * For incoming calls: * If missed call: Missed call from {Name/Number} {Call Type} {Call Time}. * If answered call: Answered call from {Name/Number} {Call Type} {Call Time}. * * For outgoing calls: * If outgoing: Call to {Name/Number] {Call Type} {Call Time}. * * Where: * {Name/Number} is the name or number of the caller (as shown in call log). * {Call type} is the contact phone number type (eg mobile) or location. * {Call Time} is the time since the last call for the contact occurred. * * The {Phone Account} refers to the account/SIM through which the call was placed or received * in multi-SIM devices. * * Examples: * 3 calls. New Voicemail. Missed call from Joe Smith mobile 2 hours ago on SIM 1. * * 2 calls. Answered call from John Doe mobile 1 hour ago. * * @param context The application context. * @param details Details of call. * @return Return call action description. */ public CharSequence getCallDescription(Context context, PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); boolean isVoiceMail = lastCallType == Calls.VOICEMAIL_TYPE; // Get the name or number of the caller. final CharSequence nameOrNumber = getNameOrNumber(details); // Get the call type or location of the caller; null if not applicable final CharSequence typeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); // Get the time/date of the call final CharSequence timeOfCall = mPhoneCallDetailsHelper.getCallDate(details); SpannableStringBuilder callDescription = new SpannableStringBuilder(); // Prepend the voicemail indication. if (isVoiceMail) { callDescription.append(mResources.getString(R.string.description_new_voicemail)); } // Add number of calls if more than one. if (details.callTypes.length > 1) { callDescription.append(mResources.getString(R.string.description_num_calls, details.callTypes.length)); } // If call had video capabilities, add the "Video Call" string. if ((details.features & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO && CallUtil.isVideoEnabled(context)) { callDescription.append(mResources.getString(R.string.description_video_call)); } int stringID = getCallDescriptionStringID(details); String accountLabel = PhoneAccountUtils.getAccountLabel(context, details.accountHandle); // Use chosen string resource to build up the message. CharSequence onAccountLabel = accountLabel == null ? "" : TextUtils.expandTemplate( mResources.getString(R.string.description_phone_account), accountLabel); callDescription.append( TextUtils.expandTemplate( mResources.getString(stringID), nameOrNumber, // If no type or location can be determined, sub in empty string. typeOrLocation == null ? "" : typeOrLocation, timeOfCall, onAccountLabel)); return callDescription; } /** * Determine the appropriate string ID to describe a call for accessibility purposes. * * @param details Call details. * @return String resource ID to use. */ public int getCallDescriptionStringID(PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); int stringID; if (lastCallType == Calls.VOICEMAIL_TYPE || lastCallType == Calls.MISSED_TYPE) { //Message: Missed call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_missed_call; } else if (lastCallType == Calls.INCOMING_TYPE) { //Message: Answered call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_answered_call; } else { //Message: Call to <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, <PhoneAccount>. stringID = R.string.description_outgoing_call; } return stringID; } /** * Determine the call type for the most recent call. * @param callTypes Call types to check. * @return Call type. */ private int getLastCallType(int[] callTypes) { if (callTypes.length > 0) { return callTypes[0]; } else { return Calls.MISSED_TYPE; } } /** * Return the name or number of the caller specified by the details. * @param details Call details * @return the name (if known) of the caller, otherwise the formatted number. */ private CharSequence getNameOrNumber(PhoneCallDetails details) { final CharSequence recipient; if (!TextUtils.isEmpty(details.name)) { recipient = details.name; } else { recipient = mPhoneNumberHelper.getDisplayNumber(details.accountHandle, details.number, details.numberPresentation, details.formattedNumber); } return recipient; } }
s20121035/rk3288_android5.1_repo
packages/apps/Dialer/src/com/android/dialer/calllog/CallLogListItemHelper.java
Java
gpl-3.0
10,890
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ENetSharp { public class ENetList { public List<object> data = new List<object>(); internal int position; } public static class ENetListHelper { /// <summary> /// Removes everything from the list /// </summary> /// <param name="list">The target list</param> public static void enet_list_clear(ref ENetList list) { list.data.Clear(); } public static ENetList enet_list_insert(ref ENetList list, int position, object data) { list.data.Insert(position, data); return list; } public static ENetList enet_list_insert(ref ENetList list, object data) { list.data.Add(data); return list; } public static object enet_list_remove(ref ENetList list, int position) { var data = list.data[position]; list.data.RemoveAt(position); return data; } public static object enet_list_remove(ref ENetList list) { var item = list.data[list.position]; list.data.Remove(item); return item; } public static object enet_list_remove(ref ENetList list, object item) { list.data.Remove(item); return item; } public static void enet_list_remove(ref ENetList list, Predicate<object> items) { list.data.RemoveAll(items); } public static ENetList enet_list_move(ref ENetList list, int positionFirst, int positionLast) { object tmp = list.data[positionFirst]; list.data[positionFirst] = list.data[positionLast]; list.data[positionLast] = tmp; return list; } public static int enet_list_size(ref ENetList list) { return list.data.Count; } //#define enet_list_begin(list) ((list) -> sentinel.next) public static object enet_list_begin(ref ENetList list) { return list.data.First(); } //#define enet_list_end(list) (& (list) -> sentinel) public static object enet_list_end(ref ENetList list) { return list.data.Last(); } //#define enet_list_empty(list) (enet_list_begin (list) == enet_list_end (list)) public static bool enet_list_empty(ref ENetList list) { return !list.data.Any(); } //#define enet_list_next(iterator) ((iterator) -> next) public static object enet_list_next(ref ENetList list) { var d = list.data[list.position]; list.position++; return d; } //#define enet_list_previous(iterator) ((iterator) -> previous) public static object enet_list_previous(ref ENetList list) { var d = list.data[list.position]; list.position--; return d; } //#define enet_list_front(list) ((void *) (list) -> sentinel.next) public static object enet_list_front(ref ENetList list) { return list.data.First(); } //#define enet_list_back(list) ((void *) (list) -> sentinel.previous) public static object enet_list_back(ref ENetList list) { list.position--; return list.data[list.position]; } public static object enet_list_current(ref ENetList list) { return list.data[list.position]; } } }
eddy5641/ENetSharp
ENetSharp/ENetSharp/List.cs
C#
gpl-3.0
3,725
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <getopt.h> #include "upgma.h" #include "utils.h" #include "seq_utils.h" #include "sequence.h" #include "seq_reader.h" #include "node.h" #include "tree.h" #include "tree_utils.h" UPGMA::UPGMA (std::istream* pios):num_taxa_(0), num_char_(0), newickstring_(""), tree_(nullptr) { std::string alphaName; // not used, but required by reader seqs_ = ingest_alignment(pios, alphaName); num_taxa_ = static_cast<int>(seqs_.size()); num_char_ = static_cast<int>(seqs_[0].get_length()); // check that it is aligned (doesn't make sense otherwise) if (!is_aligned(seqs_)) { std::cerr << "Error: sequences are not aligned. Exiting." << std::endl; exit(0); } names_ = collect_names(seqs_); full_distmatrix_ = build_matrix(); } std::vector< std::vector<double> > UPGMA::build_matrix () { // 1) skip self comparisons // 2) only calculate one half of matrix (i.e., no duplicate calcs) auto nt = static_cast<size_t>(num_taxa_); std::vector< std::vector<double> > distances(nt, std::vector<double>(nt, 0.0)); double tempScore = 0.0; for (size_t i = 0; i < nt; i++) { std::string seq1 = seqs_[i].get_sequence(); for (size_t j = (i + 1); j < nt; j++) { std::string seq2 = seqs_[j].get_sequence(); // get distance tempScore = static_cast<double>(calc_hamming_dist(seq1, seq2)); // put scale in terms of number of sites. original version did not do this tempScore /= static_cast<double>(num_char_); // put in both top and bottom of matrix, even though only top is used distances[i][j] = distances[j][i] = tempScore; } } // just for debugging /* std::cout << "\t"; for (unsigned int i = 0; i < names_.size(); i++) { std::cout << names_[i] << "\t"; } std::cout << std::endl; for (int i = 0; i < num_taxa_; i++) { std::cout << names_[i] << "\t"; for (int j = 0; j < num_taxa_; j++) { std::cout << distances[i][j] << "\t"; } std::cout << std::endl; } */ return distances; } // find smallest pairwise distance // will always find this on the top half of the matrix i.e., mini1 < mini2 double UPGMA::get_smallest_distance (const std::vector< std::vector<double> >& dmatrix, unsigned long& mini1, unsigned long& mini2) { // super large value double minD = 99999999999.99; size_t numseqs = dmatrix.size(); for (size_t i = 0; i < (numseqs - 1); i++) { auto idx = static_cast<size_t>(std::min_element(dmatrix[i].begin() + (i + 1), dmatrix[i].end()) - dmatrix[i].begin()); if (dmatrix[i][idx] < minD) { minD = dmatrix[i][idx]; mini1 = i; mini2 = idx; } } return minD; } void UPGMA::construct_tree () { // location of minimum distance (top half) unsigned long ind1 = 0; unsigned long ind2 = 0; // initialize std::vector< std::vector<double> > dMatrix = full_distmatrix_; Node * anc = nullptr; // new node, ancestor of 2 clusters Node * left = nullptr; Node * right = nullptr; auto nt = static_cast<size_t>(num_taxa_); size_t numClusters = nt; // keep list of nodes left to be clustered. initially all terminal nodes std::vector<Node *> nodes(nt); for (size_t i = 0; i < nt; i++) { auto * nd = new Node(); nd->setName(names_[i]); nd->setHeight(0.0); nodes[i] = nd; } while (numClusters > 1) { // 1. get smallest distance present in the matrix double minD = get_smallest_distance(dMatrix, ind1, ind2); left = nodes[ind1]; right = nodes[ind2]; // 2. create new ancestor node anc = new Node(); // 3. add nodes in new cluster above as children to new ancestor anc->addChild(*left); // addChild calls setParent anc->addChild(*right); // 4. compute edgelengths: half of the distance // edgelengths must subtract the existing height double newHeight = 0.5 * minD; left->setBL(newHeight - left->getHeight()); right->setBL(newHeight - right->getHeight()); // make sure to set the height of anc for the next iteration to use anc->setHeight(newHeight); // 5. compute new distance matrix (1 fewer rows & columns) // new distances are proportional averages (size of clusters) // new cluster is placed first (row & column) std::vector<double> avdists(numClusters, 0.0); double Lweight = left->isExternal() ? 1.0 : static_cast<double>(left->getChildCount()); double Rweight = right->isExternal() ? 1.0 : static_cast<double>(right->getChildCount()); for (unsigned long i = 0; i < numClusters; i++) { avdists[i] = ((dMatrix[ind1][i] * Lweight) + (dMatrix[ind2][i] * Rweight)) / (Lweight + Rweight); } numClusters--; std::vector< std::vector<double> > newDistances(numClusters, std::vector<double>(numClusters, 0.0)); // put in distances to new clusters first double tempDist = 0.0; unsigned long count = 0; for (size_t i = 0; i < nodes.size(); i++) { if (i != ind1 && i != ind2) { count++; tempDist = avdists[i]; newDistances[0][count] = tempDist; newDistances[count][0] = tempDist; } } // now, fill in remaining unsigned long icount = 1; auto ndsize = nodes.size(); for (size_t i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { size_t jcount = 1; for (size_t j = 0; j < ndsize; j++) { if (j != ind1 && j != ind2) { newDistances[icount][jcount] = dMatrix[i][j]; newDistances[jcount][icount] = dMatrix[i][j]; jcount++; } } icount++; } } // replace distance matrix dMatrix = newDistances; // 6. finally, update node vector (1 shorter). new node always goes first) std::vector<Node *> newNodes(numClusters); newNodes[0] = anc; unsigned long counter = 1; for (unsigned long i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { newNodes[counter] = nodes[i]; counter++; } } // replace node vector nodes = newNodes; } tree_ = new Tree(anc); tree_->setEdgeLengthsPresent(true); // used by newick writer } std::string UPGMA::get_newick () { if (newickstring_.empty()) { construct_tree(); } newickstring_ = getNewickString(tree_); return newickstring_; } std::vector< std::vector<double> > UPGMA::get_matrix () const { return full_distmatrix_; }
FePhyFoFum/phyx
src/upgma.cpp
C++
gpl-3.0
7,194
from .gaussian_process import RandomFeatureGaussianProcess, mean_field_logits from .spectral_normalization import SpectralNormalization
gagnonlg/explore-ml
sngp/tf_import/__init__.py
Python
gpl-3.0
136
/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <info@ub.uni-leipzig.de> * * 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/> */ package de.ubleipzig.iiifproducer.template; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import de.ubleipzig.iiif.vocabulary.IIIFEnum; /** * TemplateService. * * @author christopher-johnson */ @JsonPropertyOrder({"@context", "@id", "profile"}) public class TemplateService { @JsonProperty("@context") private String context = IIIFEnum.IMAGE_CONTEXT.IRIString(); @JsonProperty("@id") private String id; @JsonProperty private String profile = IIIFEnum.SERVICE_PROFILE.IRIString(); /** * @param id String */ public TemplateService(final String id) { this.id = id; } }
ubleipzig/iiif-producer
templates/src/main/java/de/ubleipzig/iiifproducer/template/TemplateService.java
Java
gpl-3.0
1,444
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Hy.Common.Utility.Data; using System.Data.Common; using Hy.Check.Utility; namespace Hy.Check.UI.UC.Sundary { public class ResultDbOper { private IDbConnection m_ResultDbConn = null; public ResultDbOper(IDbConnection resultDb) { m_ResultDbConn = resultDb; } public DataTable GetAllResults() { DataTable res = new DataTable(); try { string strSql = string.Format("select RuleErrId,CheckType ,RuleInstID,RuleExeState,ErrorCount,TargetFeatClass1,GZBM,ErrorType from {0}", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public DataTable GetLayersResults() { DataTable res = new DataTable(); try { string strSql = string.Format("SELECT checkType,targetfeatclass1,sum(errorcount) as ErrCount,max(RuleErrID) as ruleId from {0} group by targetfeatclass1,checktype order by max(RuleErrID)", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public int GetResultsCount() { int count = 0; DbDataReader reader =null; try { string strSql = string.Format("select sum(errorcount) as cout from {0}", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); reader = AdoDbHelper.GetQueryReader(m_ResultDbConn, strSql) as DbDataReader; if (reader.HasRows) { reader.Read(); count = int.Parse(reader[0].ToString()); } return count; } catch { return count; } finally { reader.Close(); reader.Dispose(); } } } }
hy1314200/HyDM
DataCheck/Hy.Check.UI/UC/Sundary/ResultDbOper.cs
C#
gpl-3.0
2,274
<?php namespace MikroOdeme\Enum; /** * Mikro Odeme library in PHP. * * @package mikro-odeme * @version 0.1.0 * @author Hüseyin Emre Özdemir <h.emre.ozdemir@gmail.com> * @copyright Hüseyin Emre Özdemir <h.emre.ozdemir@gmail.com> * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0 * @link https://github.com/ozdemirr/mikro-odeme */ class PaymentTypeId { CONST TEK_CEKIM = 1; CONST AYLIK_ABONELIK = 2; CONST HAFTALIK_ABONELIK = 3; CONST IKI_AYLIK_ABONELIK = 4; CONST UC_AYLIK_ABONELIK = 5; CONST ALTI_AYLIK_ABONELIK = 6; CONST AYLIK_DENEMELI = 7; CONST HAFTALIK_DENEMELI = 8; CONST IKI_HAFTALIK_DENEMELI = 9; CONST UC_AYLIK_DENEMELI = 10; CONST ALTI_AYLIK_DENEMELI = 11; CONST OTUZ_GUNLUK = 13; }
ozdemirr/mikro-odeme
lib/MikroOdeme/Enum/PaymentTypeId.php
PHP
gpl-3.0
802
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace ChummerHub.Areas.Identity.Pages.Account.Manage { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel' public class DeletePersonalDataModel : PageModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel' { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<DeletePersonalDataModel> _logger; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' public DeletePersonalDataModel( #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<DeletePersonalDataModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' public InputModel Input { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' public class InputModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' { [Required] [DataType(DataType.Password)] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' public string Password { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' public bool RequirePassword { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnGet()' public async Task<IActionResult> OnGet() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnGet()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); return Page(); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnPostAsync()' public async Task<IActionResult> OnPostAsync() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnPostAsync()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "Password not correct."); return Page(); } } var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred deleteing user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return Redirect("~/"); } } }
chummer5a/chummer5a
ChummerHub/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs
C#
gpl-3.0
4,994
namespace Grove.Artifical.TargetingRules { using System; using System.Collections.Generic; using System.Linq; using Gameplay; using Gameplay.Effects; using Gameplay.Misc; using Gameplay.Targeting; public abstract class TargetingRule : MachinePlayRule { public int? TargetLimit; public bool ConsiderTargetingSelf = true; public override void Process(Artifical.ActivationContext c) { var excludeSelf = ConsiderTargetingSelf ? null : c.Card; var candidates = c.Selector.GenerateCandidates(c.TriggerMessage, excludeSelf); var parameters = new TargetingRuleParameters(candidates, c, Game); var targetsCombinations = (TargetLimit.HasValue ? SelectTargets(parameters).Take(TargetLimit.Value) : SelectTargets(parameters)) .ToList(); if (targetsCombinations.Count == 0) { if (c.CanCancel) { c.CancelActivation = true; return; } targetsCombinations = ForceSelectTargets(parameters) .Take(Ai.Parameters.TargetCount) .ToList(); } c.SetPossibleTargets(targetsCombinations); } protected abstract IEnumerable<Targets> SelectTargets(TargetingRuleParameters p); protected virtual IEnumerable<Targets> ForceSelectTargets(TargetingRuleParameters p) { return SelectTargets(p); } protected IEnumerable<T> None<T>() { yield break; } protected IList<Targets> Group(IEnumerable<Card> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Player> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Effect> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Card> candidates1, IEnumerable<Card> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { return Group(candidates1.Cast<ITarget>().ToList(), candidates2.Cast<ITarget>().ToList(), add1, add2); } protected IList<Targets> Group(IList<ITarget> candidates1, IList<ITarget> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { var results = new List<Targets>(); if (candidates1.Count == 0 || candidates2.Count == 0) return results; add1 = add1 ?? ((trg, trgts) => trgts.AddEffect(trg)); add2 = add2 ?? ((trg, trgts) => trgts.AddEffect(trg)); var index1 = 0; var index2 = 0; var groupCount = Math.Max(candidates1.Count, candidates2.Count); for (var i = 0; i < groupCount; i++) { // generate some options by mixing candidates // from 2 selectors var targets = new Targets(); add1(candidates1[index1], targets); add2(candidates2[index2], targets); index1++; index2++; if (index1 == candidates1.Count) index1 = 0; if (index2 == candidates2.Count) index2 = 0; results.Add(targets); } return results; } protected IList<Targets> Group(IList<ITarget> candidates, List<int> damageDistribution) { var result = new Targets(); foreach (var candidate in candidates) { result.AddEffect(candidate); } result.Distribution = damageDistribution; return new[] {result}; } protected IList<Targets> Group(IList<ITarget> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { var results = new List<Targets>(); var targetCount = candidates.Count < maxTargetCount ? minTargetCount : maxTargetCount ?? minTargetCount; if (targetCount == 0) return results; if (candidates.Count < targetCount) return results; add = add ?? ((trg, trgts) => trgts.AddEffect(trg)); // generate possible groups by varying only the last element // since the number of different groups tried will be small // this is a reasonable approximation. var groupCount = candidates.Count - targetCount + 1; for (var i = 0; i < groupCount; i++) { var targets = new Targets(); // add first targetCount - 1 for (var j = 0; j < targetCount - 1; j++) { add(candidates[j], targets); } // add last add(candidates[targetCount - 1 + i], targets); results.Add(targets); } return results; } protected int CalculateAttackerScoreForThisTurn(Card attacker) { if (!attacker.CanAttack) return -1; return Combat.CouldBeBlockedByAny(attacker) ? 2 * attacker.Power.GetValueOrDefault() + attacker.Toughness.GetValueOrDefault() : 5 * attacker.CalculateCombatDamageAmount(singleDamageStep: false); } protected static int CalculateAttackingPotential(Card creature) { if (!creature.IsAbleToAttack) return 0; var damage = creature.CalculateCombatDamageAmount(singleDamageStep: false); if (creature.Has().AnyEvadingAbility) return 2 + damage; return damage; } protected int CalculateBlockerScore(Card card) { var count = Combat.CountHowManyThisCouldBlock(card); if (count > 0) { return count*10 + card.Toughness.GetValueOrDefault(); } return 0; } protected IEnumerable<Card> GetCandidatesForAttackerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsAttacker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainAttackerWouldGetIfPowerAndThoughnessWouldIncrease( attacker: x, blockers: Combat.GetBlockers(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> GetCandidatesForBlockerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsBlocker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainBlockerWouldGetIfPowerAndThougnessWouldIncrease( blocker: x, attacker: Combat.GetAttacker(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> GetCandidatesThatCanBeDestroyed(TargetingRuleParameters p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.SpellOwner, selector: selector) .Where(x => Stack.CanBeDestroyedByTopSpell(x.Card()) || Combat.CanBeDealtLeathalCombatDamage(x.Card())); } protected static IEnumerable<Card> GetBounceCandidates(TargetingRuleParameters p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.Opponent, selector: selector) .Select(x => new { Card = x, Score = x.Owner == p.Controller ? 2*x.Score : x.Score }) .OrderByDescending(x => x.Score) .Select(x => x.Card); } } }
sorab2142/sorabpithawala-magicgrove
source/Grove/Artifical/TargetingRules/TargetingRule.cs
C#
gpl-3.0
8,371
package com.pix.mind.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.pix.mind.PixMindGame; import com.pix.mind.box2d.bodies.PixGuy; public class KeyboardController extends PixGuyController { boolean movingLeft = false; boolean movingRight = false; public KeyboardController(PixGuy pixGuy, Stage stage) { super(pixGuy); stage.addListener(new InputListener(){ @Override public boolean keyDown(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingLeft = true; movingRight = false; } if (keycode == Keys.RIGHT) { movingRight = true; movingLeft = false; } return true; } @Override public boolean keyUp(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingRight = true; movingLeft = false; } if (keycode == Keys.RIGHT) { movingLeft = true; movingRight = false; } if (!Gdx.input.isKeyPressed(Keys.RIGHT)&& !Gdx.input.isKeyPressed(Keys.LEFT)) { movingRight = false; movingLeft = false; } return true; } }); } public void movements() { if (movingLeft) { pixGuy.moveLeft(Gdx.graphics.getDeltaTime()); } if (movingRight) { pixGuy.moveRight(Gdx.graphics.getDeltaTime()); } if(!movingLeft&&!movingRight){ // if it is not touched, set horizontal velocity to 0 to // eliminate inercy. pixGuy.body.setLinearVelocity(0, pixGuy.body.getLinearVelocity().y); } } }
tuxskar/pixmind
pixmind/src/com/pix/mind/controllers/KeyboardController.java
Java
gpl-3.0
1,788
package com.wongsir.newsgathering.model.commons; import com.google.common.base.MoreObjects; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: TODO * @author Wongsir * @date 2017年1月4日 * */ public class Webpage { /** * 附件id列表 */ public List<String> attachmentList; /** * 图片ID列表 */ public List<String> imageList; /** * 正文 */ private String content; /** * 标题 */ private String title; /** * 链接 */ private String url; /** * 域名 */ private String domain; /** * 爬虫id,可以认为是taskid */ private String spiderUUID; /** * 模板id */ @SerializedName("spiderInfoId") private String spiderInfoId; /** * 分类 */ private String category; /** * 网页快照 */ private String rawHTML; /** * 关键词 */ private List<String> keywords; /** * 摘要 */ private List<String> summary; /** * 抓取时间 */ @SerializedName("gatherTime") private Date gathertime; /** * 网页id,es自动分配的 */ private String id; /** * 文章的发布时间 */ private Date publishTime; /** * 命名实体 */ private Map<String, Set<String>> namedEntity; /** * 动态字段 */ private Map<String, Object> dynamicFields; /** * 静态字段 */ private Map<String, Object> staticFields; /** * 本网页处理时长 */ private long processTime; public Map<String, Object> getStaticFields() { return staticFields; } public Webpage setStaticFields(Map<String, Object> staticFields) { this.staticFields = staticFields; return this; } public Map<String, Set<String>> getNamedEntity() { return namedEntity; } public Webpage setNamedEntity(Map<String, Set<String>> namedEntity) { this.namedEntity = namedEntity; return this; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getSpiderInfoId() { return spiderInfoId; } public void setSpiderInfoId(String spiderInfoId) { this.spiderInfoId = spiderInfoId; } public Date getGathertime() { return gathertime; } public void setGathertime(Date gathertime) { this.gathertime = gathertime; } public String getSpiderUUID() { return spiderUUID; } public void setSpiderUUID(String spiderUUID) { this.spiderUUID = spiderUUID; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getKeywords() { return keywords; } public Webpage setKeywords(List<String> keywords) { this.keywords = keywords; return this; } public List<String> getSummary() { return summary; } public Webpage setSummary(List<String> summary) { this.summary = summary; return this; } public Date getPublishTime() { return publishTime; } public Webpage setPublishTime(Date publishTime) { this.publishTime = publishTime; return this; } public String getCategory() { return category; } public Webpage setCategory(String category) { this.category = category; return this; } public String getRawHTML() { return rawHTML; } public Webpage setRawHTML(String rawHTML) { this.rawHTML = rawHTML; return this; } public Map<String, Object> getDynamicFields() { return dynamicFields; } public Webpage setDynamicFields(Map<String, Object> dynamicFields) { this.dynamicFields = dynamicFields; return this; } public List<String> getAttachmentList() { return attachmentList; } public Webpage setAttachmentList(List<String> attachmentList) { this.attachmentList = attachmentList; return this; } public List<String> getImageList() { return imageList; } public Webpage setImageList(List<String> imageList) { this.imageList = imageList; return this; } public long getProcessTime() { return processTime; } public Webpage setProcessTime(long processTime) { this.processTime = processTime; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("content", content) .add("title", title) .add("url", url) .add("domain", domain) .add("spiderUUID", spiderUUID) .add("spiderInfoId", spiderInfoId) .add("category", category) .add("rawHTML", rawHTML) .add("keywords", keywords) .add("summary", summary) .add("gathertime", gathertime) .add("id", id) .add("publishTime", publishTime) .add("namedEntity", namedEntity) .add("dynamicFields", dynamicFields) .add("staticFields", staticFields) .add("attachmentList", attachmentList) .add("imageList", imageList) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Webpage webpage = (Webpage) o; return new EqualsBuilder() .append(getContent(), webpage.getContent()) .append(getTitle(), webpage.getTitle()) .append(getUrl(), webpage.getUrl()) .append(getDomain(), webpage.getDomain()) .append(getSpiderUUID(), webpage.getSpiderUUID()) .append(getSpiderInfoId(), webpage.getSpiderInfoId()) .append(getCategory(), webpage.getCategory()) .append(getRawHTML(), webpage.getRawHTML()) .append(getKeywords(), webpage.getKeywords()) .append(getSummary(), webpage.getSummary()) .append(getGathertime(), webpage.getGathertime()) .append(getId(), webpage.getId()) .append(getPublishTime(), webpage.getPublishTime()) .append(getNamedEntity(), webpage.getNamedEntity()) .append(getDynamicFields(), webpage.getDynamicFields()) .append(getStaticFields(), webpage.getStaticFields()) .append(getAttachmentList(), webpage.getAttachmentList()) .append(getImageList(), webpage.getImageList()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getContent()) .append(getTitle()) .append(getUrl()) .append(getDomain()) .append(getSpiderUUID()) .append(getSpiderInfoId()) .append(getCategory()) .append(getRawHTML()) .append(getKeywords()) .append(getSummary()) .append(getGathertime()) .append(getId()) .append(getPublishTime()) .append(getNamedEntity()) .append(getDynamicFields()) .append(getStaticFields()) .append(getAttachmentList()) .append(getImageList()) .toHashCode(); } }
WongSir/JustGo
src/main/java/com/wongsir/newsgathering/model/commons/Webpage.java
Java
gpl-3.0
8,742
package fr.hnit.babyname; /* The babyname app 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. The babyname app 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 the TXM platform. If not, see http://www.gnu.org/licenses */ import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String UPDATE_EXTRA = "update"; ListView namesListView; BabyNameAdapter adapter; public static BabyNameDatabase database = new BabyNameDatabase(); public static ArrayList<BabyNameProject> projects = new ArrayList<>(); Intent editIntent; Intent findIntent; Intent settingsIntent; Intent aboutIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (database.size() == 0) database.initialize(); namesListView = (ListView) findViewById(R.id.listView); registerForContextMenu(namesListView); namesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BabyNameProject project = projects.get(i); if (project != null) { doFindName(project); } } }); adapter = new BabyNameAdapter(this, projects); namesListView.setAdapter(adapter); if (projects.size() == 0) { initializeProjects(); } editIntent = new Intent(MainActivity.this, EditActivity.class); findIntent = new Intent(MainActivity.this, FindActivity.class); settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); aboutIntent = new Intent(MainActivity.this, AboutActivity.class); } @Override public void onResume() { super.onResume(); // Always call the superclass method first adapter.notifyDataSetChanged(); for (BabyNameProject project : projects) { if (project.needSaving) { //Toast.makeText(this, "Saving changes of "+project+"... "+project, Toast.LENGTH_SHORT).show(); if (!BabyNameProject.storeProject(project, this)) { Toast.makeText(this, "Error: could not save changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } } } } private void initializeProjects() { //AppLogger.info("Initializing projects..."); for (String filename : this.fileList()) { if (filename.endsWith(".baby")) { //AppLogger.info("Restoring... "+filename); try { BabyNameProject project = BabyNameProject.readProject(filename, this); if (project != null) projects.add(project); else Toast.makeText(MainActivity.this, "Error: could not read baby name project from "+filename, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); if (adapter.getCount() <= info.position) return false; BabyNameProject project = adapter.getItem(info.position); if (project == null) return false; switch (item.getItemId()) { case R.id.action_reset_baby: doResetBaby(project); return true; case R.id.action_top_baby: doShowTop10(project); return true; case R.id.action_delete_baby: doDeleteBaby(project); return true; default: return super.onContextItemSelected(item); } } public void doResetBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reset_question_title); builder.setMessage(R.string.reset_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { project.reset(); adapter.notifyDataSetChanged(); if (!BabyNameProject.storeProject(project, MainActivity.this)) { Toast.makeText(MainActivity.this, "Error: could not save reset changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // I do not need any action here you might dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void doDeleteBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete_question_title); builder.setMessage(R.string.delete_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { projects.remove(project); MainActivity.this.deleteFile(project.getID()+".baby"); adapter.notifyDataSetChanged(); dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public String projectToString(BabyNameProject p) { String l1 = ""; if (p.genders.contains(NameData.F) && p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_or_girl_name); } else if (p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_name); } else { l1 +=getString( R.string.girl_name); } if (p.origins.size() == 1) { l1 += "\n\t "+String.format(getString(R.string.origin_is), p.origins.toArray()[0]); } else if (p.origins.size() > 1) { l1 += "\n\t "+String.format(getString(R.string.origin_are), p.origins); } else { l1 += "\n\t "+getString(R.string.no_origin); } if (p.pattern != null) { if (".*".equals(p.pattern.toString())) { l1 += "\n\t "+getString(R.string.no_pattern); } else { l1 += "\n\t "+String.format(getString(R.string.matches_with), p.pattern); } } if (p.nexts.size() == 1) { l1 += "\n\t"+getString(R.string.one_remaining_name); } else if (p.nexts.size() == 0) { int n = p.scores.size(); if (n > 11) n = n - 10; l1 += "\n\t"+String.format(getString(R.string.no_remaining_loop), p.loop, n); } else { l1 += "\n\t"+String.format(getString(R.string.remaining_names), p.nexts.size()); } if (p.scores.size() > 0 && p.getBest() != null) { l1 += "\n\n\t"+String.format(getString(R.string.bact_match_is), p.getBest()); } return l1; } public void doShowTop10(final BabyNameProject project) { List<Integer> names = project.getTop10(); final StringBuffer buffer = new StringBuffer(); int n = 0; for (Integer name : names) { buffer.append("\n"+MainActivity.database.get(name)+": "+project.scores.get(name)); } if (names.size() == 0) buffer.append(getString(R.string.no_name_rated)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.top_title); builder.setMessage(buffer.toString()); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (names.size() > 0) builder.setNegativeButton(R.string.copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("baby top10", buffer.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(MainActivity.this, R.string.text_copied, Toast.LENGTH_LONG).show(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show(); } public void doFindName(BabyNameProject project) { //AppLogger.info("Open FindActivity with "+project+" index="+projects.indexOf(project)); findIntent.putExtra(FindActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(findIntent, 0); } private void openEditActivity(BabyNameProject project) { //AppLogger.info("Open EditActivity with "+project+" index="+projects.indexOf(project)); editIntent.putExtra(EditActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(editIntent, 0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: this.startActivityForResult(settingsIntent, 0); return true; case R.id.action_about: this.startActivityForResult(aboutIntent, 0); return true; case R.id.action_new_baby: doNewBaby(); return true; default: return super.onOptionsItemSelected(item); } } public void doNewBaby() { Toast.makeText(this, R.string.new_baby, Toast.LENGTH_LONG).show(); BabyNameProject project = new BabyNameProject(); projects.add(project); openEditActivity(project); } }
mdecorde/BABYNAME
app/src/main/java/fr/hnit/babyname/MainActivity.java
Java
gpl-3.0
12,172
import { useState } from "react"; import { PropTypes } from "prop-types"; import { SaveOutlined, WarningOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, InputNumber, Row, Select, Switch, Typography, Space, } from "@nextgisweb/gui/antd"; import i18n from "@nextgisweb/pyramid/i18n!"; import { AddressGeocoderOptions, DegreeFormatOptions, UnitsAreaOptions, UnitsLengthOptions, } from "./select-options"; const { Title } = Typography; const INPUT_DEFAULT_WIDTH = { width: "100%" }; export const SettingsForm = ({ onFinish, initialValues, srsOptions, status, }) => { const [geocoder, setGeocoder] = useState( initialValues.address_geocoder || "nominatim" ); const onValuesChange = (changedValues, allValues) => { setGeocoder(allValues.address_geocoder); }; return ( <Form name="webmap_settings" className="webmap-settings-form" initialValues={initialValues} onFinish={onFinish} onValuesChange={onValuesChange} layout="vertical" > <Title level={4}>{i18n.gettext("Identify popup")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="popup_width" label={i18n.gettext("Width, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="popup_height" label={i18n.gettext("Height, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="identify_radius" label={i18n.gettext("Radius, px")} rules={[ { required: true, }, ]} > <InputNumber min="1" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="identify_attributes" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Show feature attributes")} </Space> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Measurement")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="units_length" label={i18n.gettext("Length units")} > <Select options={UnitsLengthOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="units_area" label={i18n.gettext("Area units")} > <Select options={UnitsAreaOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="degree_format" label={i18n.gettext("Degree format")} > <Select options={DegreeFormatOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item name="measurement_srid" label={i18n.gettext("Measurement SRID")} > <Select options={srsOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Address search")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_enabled" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Enable")} </Space> </Form.Item> </Col> <Col span={16}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_extent" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Limit by web map initial extent")} </Space> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="address_geocoder" label={i18n.gettext("Provider")} > <Select options={AddressGeocoderOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={16}> {geocoder == "nominatim" ? ( <Form.Item name="nominatim_countrycodes" label={i18n.gettext( "Limit search results to countries" )} rules={[ { pattern: new RegExp( /^(?:(?:[A-Za-z]+)(?:-[A-Za-z]+)?(?:,|$))+(?<!,)$/ ), message: ( <div> {i18n.gettext( "Invalid countries. For example ru or gb,de" )} </div> ), }, ]} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> ) : ( <Form.Item name="yandex_api_geocoder_key" label={i18n.gettext("Yandex.Maps API Geocoder Key")} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> )} </Col> </Row> <Row className="row-submit"> <Col> <Button htmlType="submit" type={"primary"} danger={status === "saved-error"} icon={ status === "saved-error" ? ( <WarningOutlined /> ) : ( <SaveOutlined /> ) } loading={status === "saving"} > {i18n.gettext("Save")} </Button> </Col> </Row> </Form> ); }; SettingsForm.propTypes = { initialValues: PropTypes.object, onFinish: PropTypes.func, srsOptions: PropTypes.array, status: PropTypes.string, };
nextgis/nextgisweb
nextgisweb/webmap/nodepkg/settings/SettingsForm.js
JavaScript
gpl-3.0
9,428
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
jim-easterbrook/pyctools-demo
src/scripts/temporal_alias/stage_2.py
Python
gpl-3.0
2,808
# -*- coding: utf-8 -*- import itertools """ Languages | ShortCode | Wordnet Albanian | sq | als Arabic | ar | arb Bulgarian | bg | bul Catalan | ca | cat Chinese | zh | cmn Chinese (Taiwan) | qn | qcn Greek | el | ell Basque | eu | eus Persian | fa | fas Finish | fi | fin French | fr | fra Galician | gl | glg Hebrew | he | heb Croatian | hr | hrv Indonesian | id | ind Italian | it | ita Japanese | ja | jpn Norwegian NyNorsk | nn | nno Norwegian Bokmål | nb/no | nob Polish | pl | pol Portuguese | pt | por Slovenian | sl | slv Spanish | es | spa Swedish | sv | swe Thai | tt | tha Malay | ms | zsm """ """ Language short codes => Wordnet Code """ AVAILABLE_LANGUAGES = dict([('sq','als'), ('ar', 'arb'), ('bg', 'bul'), ('ca', 'cat'), ('da', 'dan'), ('zh', 'cmn'), ('el','ell'), ('eu', 'eus'), ('fa', 'fas'), ('fi', 'fin'), ('fr', 'fra'), ('gl','glg'), ('he', 'heb'), ('hr', 'hrv'), ('id', 'ind'), ('it', 'ita'), ('ja','jpn'), ('nn', 'nno'), ('nb', 'nob'), ('no', 'nob'), ('pl', 'pol'), ('pt', 'por'), ('qn','qcn'), ('sl', 'slv'), ('es', 'spa'), ('sv', 'swe'), ('tt', 'tha'), ('ms', 'zsm'), ('en', 'eng')]) """ Language names => Short Code """ AVAILABLE_LANGUAGES_NAMES = dict([ ('albanian', 'sq'), ('arabic', 'ar'),('bulgarian', 'bg'), ('catalan', 'cat'), ('danish', 'da'), ('chinese', 'zh'), ('basque', 'eu'), ('persian', 'fa'), ('finnish', 'fi'), ('france', 'fr'), ('galician', 'gl'), ('hebrew', 'he'), ('croatian', 'hr'), ('indonesian', 'id'), ('italian', 'it'), ('japanese', 'ja'), ('norwegian_nynorsk', 'nn'), ('norwegian', 'no'), ('norwegian_bokmal', 'nb'), ('polish', 'pl'), ('portuguese', 'pt'), ('slovenian', 'sl'), ('spanish', 'es'), ('swedish', 'sv'), ('thai', 'sv'), ('malay', 'ms'), ('english', 'en') ]) class WordnetManager(object): def __init__(self, language="en"): """ Constructor for the wordnet manager. It takes a main language. """ self.__language = language def __isLanguageAvailable(self, code=None, language_name=None): """ Check if a language is available """ if code is None and language_name is None: raise Exception("Error evaluating the correct language") if code is not None and code.lower() in AVAILABLE_LANGUAGES: return True if language_name is not None and language_name.lower() in AVAILABLE_LANGUAGES_NAMES: return True return False def __nameToWordnetCode(self, name): """ It returns the wordnet code for a given language name """ if not self.__isLanguageAvailable(language_name=name): raise Exception("Wordnet code not found for the language name %s " % name) name = name.lower() languageShortCode = AVAILABLE_LANGUAGES_NAMES[name] wordnetCode = self.__shortCodeToWordnetCode(code=languageShortCode) return wordnetCode def __shortCodeToWordnetCode(self, shortCode): """ It returns the wordnet code from a given language short code """ if not self.__isLanguageAvailable(code=shortCode): raise Exception("Wordnet code not found for the language short code %s " % shortCode) code = shortCode.lower() wordnetCode = AVAILABLE_LANGUAGES[code] return wordnetCode def __getSynsets(self, word, wordNetCode): """ It returns the synsets given both word and language code """ from nltk.corpus import wordnet as wn synsets = wn.synsets(word, lang=wordNetCode) return synsets def getLemmas(self, word, languageCode="en"): """ Get the lemmas for a given word :word: The word :languageCode: The language for a given lemma """ wnCode = self.__shortCodeToWordnetCode(shortCode=languageCode) synsets = self.__getSynsets(word, wnCode) #wn.synsets(word, lang=wnCode) lemmas = dict([('en', [])]) for synset in synsets: enLemmas = synset.lemma_names() lemmas['en'].extend(enLemmas) if languageCode != "en" and self.__isLanguageAvailable(code=languageCode): langLemmas = list(sorted(set(synset.lemma_names(lang=wnCode)))) lemmas[languageCode] = langLemmas lemmas['en'] = list(sorted(set(lemmas.get('en', [])))) return lemmas def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of words. :words: A list of words :language_code: the language for the synonyms. """ if words is None or not isinstance(words, list) or list(words) <= 0: return [] if not self.__isLanguageAvailable(code=language_code): return [] wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: result[word] = dict([('lemmas', self.getLemmas(word,languageCode=language_code))]) return result def getHyponyms(self, words, language_code="en"): """ Get specific synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hyponyms = [hyp for synset in synonyms for hyp in synset.hyponyms()] engLemmas = [hyp.lemma_names() for hyp in hyponyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hyponyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result def getHypernyms(self, words, language_code="en"): """ Get general synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hypernyms = [hyp for synset in synonyms for hyp in synset.hypernyms()] engLemmas = [hyp.lemma_names() for hyp in hypernyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hypernyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result
domenicosolazzo/jroc
jroc/nlp/wordnet/WordnetManager.py
Python
gpl-3.0
8,043
package com.weatherapp.model.entities; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Location implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; public Location(String name) { this.name = name; } public Location() {} public String getName() { return name; } public void setName(String name) { this.name = name; } }
VoidDragonOfMars/pixelware
instantweatherapplication/src/main/java/com/weatherapp/model/entities/Location.java
Java
gpl-3.0
552
package units.interfaces; public abstract interface Value<T> extends MyComparable<T> { // OPERATIONS default boolean invariant() { return true; } default void checkInvariant() { if(!invariant()) { System.exit(-1); } } public abstract T newInstance(double value); public abstract T abs(); public abstract T min(T value); public abstract T max(T value); public abstract T add(T value); public abstract T sub(T value); public abstract T mul(double value); public abstract T div(double value); public abstract double div(T value); }
MesutKoc/uni-haw
2. Semester/PR2/Aufgabe_2a_Igor/src/units/interfaces/Value.java
Java
gpl-3.0
686
############################################################################# # $HeadURL$ ############################################################################# """ ..mod: FTSRequest ================= Helper class to perform FTS job submission and monitoring. """ # # imports import sys import re import time # # from DIRAC from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities.File import checkGuid from DIRAC.Core.Utilities.Adler import compareAdler, intAdlerToHex, hexAdlerToInt from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE from DIRAC.Core.Utilities.Time import dateTime from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.ConfigurationSystem.Client.Helpers.Resources import Resources from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.DataManagementSystem.Client.FTSJob import FTSJob from DIRAC.DataManagementSystem.Client.FTSFile import FTSFile # # RCSID __RCSID__ = "$Id$" class FTSRequest( object ): """ .. class:: FTSRequest Helper class for FTS job submission and monitoring. """ # # default checksum type __defaultCksmType = "ADLER32" # # flag to disablr/enable checksum test, default: disabled __cksmTest = False def __init__( self ): """c'tor :param self: self reference """ self.log = gLogger.getSubLogger( self.__class__.__name__, True ) # # final states tuple self.finalStates = ( 'Canceled', 'Failed', 'Hold', 'Finished', 'FinishedDirty' ) # # failed states tuple self.failedStates = ( 'Canceled', 'Failed', 'Hold', 'FinishedDirty' ) # # successful states tuple self.successfulStates = ( 'Finished', 'Done' ) # # all file states tuple self.fileStates = ( 'Done', 'Active', 'Pending', 'Ready', 'Canceled', 'Failed', 'Finishing', 'Finished', 'Submitted', 'Hold', 'Waiting' ) self.statusSummary = {} # # request status self.requestStatus = 'Unknown' # # dict for FTS job files self.fileDict = {} # # dict for replicas information self.catalogReplicas = {} # # dict for metadata information self.catalogMetadata = {} # # dict for files that failed to register self.failedRegistrations = {} # # placehoder for FileCatalog reference self.oCatalog = None # # submit timestamp self.submitTime = '' # # placeholder FTS job GUID self.ftsGUID = '' # # placeholder for FTS server URL self.ftsServer = '' # # flag marking FTS job completness self.isTerminal = False # # completness percentage self.percentageComplete = 0.0 # # source SE name self.sourceSE = '' # # flag marking source SE validity self.sourceValid = False # # source space token self.sourceToken = '' # # target SE name self.targetSE = '' # # flag marking target SE validity self.targetValid = False # # target space token self.targetToken = '' # # placeholder for target StorageElement self.oTargetSE = None # # placeholder for source StorageElement self.oSourceSE = None # # checksum type, set it to default self.__cksmType = self.__defaultCksmType # # disable checksum test by default self.__cksmTest = False # # statuses that prevent submitting to FTS self.noSubmitStatus = ( 'Failed', 'Done', 'Staging' ) # # were sources resolved? self.sourceResolved = False # # Number of file transfers actually submitted self.submittedFiles = 0 self.transferTime = 0 self.submitCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/SubmitCommand', 'glite-transfer-submit' ) self.monitorCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/MonitorCommand', 'glite-transfer-status' ) self.ftsJob = None self.ftsFiles = [] #################################################################### # # Methods for setting/getting/checking the SEs # def setSourceSE( self, se ): """ set SE for source :param self: self reference :param str se: source SE name """ if se == self.targetSE: return S_ERROR( "SourceSE is TargetSE" ) self.sourceSE = se self.oSourceSE = StorageElement( self.sourceSE ) return self.__checkSourceSE() def __checkSourceSE( self ): """ check source SE availability :param self: self reference """ if not self.sourceSE: return S_ERROR( "SourceSE not set" ) res = self.oSourceSE.isValid( 'Read' ) if not res['OK']: return S_ERROR( "SourceSE not available for reading" ) res = self.__getSESpaceToken( self.oSourceSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for SourceSE", res['Message'] ) return S_ERROR( "SourceSE does not support FTS transfers" ) if self.__cksmTest: res = self.oSourceSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for SourceSE", "%s: %s" % ( self.sourceSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at SourceSE %s, disabling checksum test" % ( cksmType, self.sourceSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.sourceToken = res['Value'] self.sourceValid = True return S_OK() def setTargetSE( self, se ): """ set target SE :param self: self reference :param str se: target SE name """ if se == self.sourceSE: return S_ERROR( "TargetSE is SourceSE" ) self.targetSE = se self.oTargetSE = StorageElement( self.targetSE ) return self.__checkTargetSE() def setTargetToken( self, token ): """ target space token setter :param self: self reference :param str token: target space token """ self.targetToken = token return S_OK() def __checkTargetSE( self ): """ check target SE availability :param self: self reference """ if not self.targetSE: return S_ERROR( "TargetSE not set" ) res = self.oTargetSE.isValid( 'Write' ) if not res['OK']: return S_ERROR( "TargetSE not available for writing" ) res = self.__getSESpaceToken( self.oTargetSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for TargetSE", res['Message'] ) return S_ERROR( "TargetSE does not support FTS transfers" ) # # check checksum types if self.__cksmTest: res = self.oTargetSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for TargetSE", "%s: %s" % ( self.targetSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at TargetSE %s, disabling checksum test" % ( cksmType, self.targetSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.targetToken = res['Value'] self.targetValid = True return S_OK() @staticmethod def __getSESpaceToken( oSE ): """ get space token from StorageElement instance :param self: self reference :param StorageElement oSE: StorageElement instance """ res = oSE.getStorageParameters( "SRM2" ) if not res['OK']: return res return S_OK( res['Value'].get( 'SpaceToken' ) ) #################################################################### # # Methods for setting/getting FTS request parameters # def setFTSGUID( self, guid ): """ FTS job GUID setter :param self: self reference :param str guid: string containg GUID """ if not checkGuid( guid ): return S_ERROR( "Incorrect GUID format" ) self.ftsGUID = guid return S_OK() def setFTSServer( self, server ): """ FTS server setter :param self: self reference :param str server: FTS server URL """ self.ftsServer = server return S_OK() def isRequestTerminal( self ): """ check if FTS job has terminated :param self: self reference """ if self.requestStatus in self.finalStates: self.isTerminal = True return S_OK( self.isTerminal ) def setCksmTest( self, cksmTest = False ): """ set cksm test :param self: self reference :param bool cksmTest: flag to enable/disable checksum test """ self.__cksmTest = bool( cksmTest ) return S_OK( self.__cksmTest ) #################################################################### # # Methods for setting/getting/checking files and their metadata # def setLFN( self, lfn ): """ add LFN :lfn: to :fileDict: :param self: self reference :param str lfn: LFN to add to """ self.fileDict.setdefault( lfn, {'Status':'Waiting'} ) return S_OK() def setSourceSURL( self, lfn, surl ): """ source SURL setter :param self: self reference :param str lfn: LFN :param str surl: source SURL """ target = self.fileDict[lfn].get( 'Target' ) if target == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Source', surl ) def getSourceSURL( self, lfn ): """ get source SURL for LFN :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Source' ) def setTargetSURL( self, lfn, surl ): """ set target SURL for LFN :lfn: :param self: self reference :param str lfn: LFN :param str surl: target SURL """ source = self.fileDict[lfn].get( 'Source' ) if source == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Target', surl ) def getFailReason( self, lfn ): """ get fail reason for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Reason' ) def getRetries( self, lfn ): """ get number of attepmts made to transfer file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Retries' ) def getTransferTime( self, lfn ): """ get duration of transfer for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Duration' ) def getFailed( self ): """ get list of wrongly transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.failedStates ] ) def getStaging( self ): """ get files set for prestaging """ return S_OK( [lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) == 'Staging'] ) def getDone( self ): """ get list of succesfully transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.successfulStates ] ) def __setFileParameter( self, lfn, paramName, paramValue ): """ set :paramName: to :paramValue: for :lfn: file :param self: self reference :param str lfn: LFN :param str paramName: parameter name :param mixed paramValue: a new parameter value """ self.setLFN( lfn ) self.fileDict[lfn][paramName] = paramValue return S_OK() def __getFileParameter( self, lfn, paramName ): """ get value of :paramName: for file :lfn: :param self: self reference :param str lfn: LFN :param str paramName: parameter name """ if lfn not in self.fileDict: return S_ERROR( "Supplied file not set" ) if paramName not in self.fileDict[lfn]: return S_ERROR( "%s not set for file" % paramName ) return S_OK( self.fileDict[lfn][paramName] ) #################################################################### # # Methods for submission # def submit( self, monitor = False, printOutput = True ): """ submit FTS job :param self: self reference :param bool monitor: flag to monitor progress of FTS job :param bool printOutput: flag to print output of execution to stdout """ res = self.__prepareForSubmission() if not res['OK']: return res res = self.__submitFTSTransfer() if not res['OK']: return res resDict = { 'ftsGUID' : self.ftsGUID, 'ftsServer' : self.ftsServer, 'submittedFiles' : self.submittedFiles } if monitor or printOutput: gLogger.always( "Submitted %s@%s" % ( self.ftsGUID, self.ftsServer ) ) if monitor: self.monitor( untilTerminal = True, printOutput = printOutput, full = False ) return S_OK( resDict ) def __prepareForSubmission( self ): """ check validity of job before submission :param self: self reference """ if not self.fileDict: return S_ERROR( "No files set" ) if not self.sourceValid: return S_ERROR( "SourceSE not valid" ) if not self.targetValid: return S_ERROR( "TargetSE not valid" ) if not self.ftsServer: res = self.__resolveFTSServer() if not res['OK']: return S_ERROR( "FTSServer not valid" ) self.resolveSource() self.resolveTarget() res = self.__filesToSubmit() if not res['OK']: return S_ERROR( "No files to submit" ) return S_OK() def __getCatalogObject( self ): """ CatalogInterface instance facade :param self: self reference """ try: if not self.oCatalog: self.oCatalog = FileCatalog() return S_OK() except: return S_ERROR() def __updateReplicaCache( self, lfns = None, overwrite = False ): """ update replica cache for list of :lfns: :param self: self reference :param mixed lfns: list of LFNs :param bool overwrite: flag to trigger cache clearing and updating """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if ( lfn not in self.catalogReplicas ) or overwrite ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getReplicas( toUpdate ) if not res['OK']: return S_ERROR( "Failed to update replica cache: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, replicas in res['Value']['Successful'].items(): self.catalogReplicas[lfn] = replicas return S_OK() def __updateMetadataCache( self, lfns = None ): """ update metadata cache for list of LFNs :param self: self reference :param list lnfs: list of LFNs """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if lfn not in self.catalogMetadata ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getFileMetadata( toUpdate ) if not res['OK']: return S_ERROR( "Failed to get source catalog metadata: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, metadata in res['Value']['Successful'].items(): self.catalogMetadata[lfn] = metadata return S_OK() def resolveSource( self ): """ resolve source SE eligible for submission :param self: self reference """ # Avoid resolving sources twice if self.sourceResolved: return S_OK() # Only resolve files that need a transfer toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( "Status", "" ) != "Failed" ] if not toResolve: return S_OK() res = self.__updateMetadataCache( toResolve ) if not res['OK']: return res res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res # Define the source URLs for lfn in toResolve: replicas = self.catalogReplicas.get( lfn, {} ) if self.sourceSE not in replicas: gLogger.warn( "resolveSource: skipping %s - not replicas at SourceSE %s" % ( lfn, self.sourceSE ) ) self.__setFileParameter( lfn, 'Reason', "No replica at SourceSE" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = returnSingleResult( self.oSourceSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setSourceSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Source" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Source files" ) # Get metadata of the sources, to check for existance, availability and caching res = self.oSourceSE.getFileMetadata( toResolve ) if not res['OK']: return S_ERROR( "Failed to check source file metadata" ) for lfn, error in res['Value']['Failed'].items(): if re.search( 'File does not exist', error ): gLogger.warn( "resolveSource: skipping %s - source file does not exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file does not exist" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: gLogger.warn( "resolveSource: skipping %s - failed to get source metadata" % lfn ) self.__setFileParameter( lfn, 'Reason', "Failed to get Source metadata" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toStage = [] nbStagedFiles = 0 for lfn, metadata in res['Value']['Successful'].items(): lfnStatus = self.fileDict.get( lfn, {} ).get( 'Status' ) if metadata['Unavailable']: gLogger.warn( "resolveSource: skipping %s - source file unavailable" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Unavailable" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif metadata['Lost']: gLogger.warn( "resolveSource: skipping %s - source file lost" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Lost" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif not metadata['Cached']: if lfnStatus != 'Staging': toStage.append( lfn ) elif metadata['Size'] != self.catalogMetadata[lfn]['Size']: gLogger.warn( "resolveSource: skipping %s - source file size mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source size mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif self.catalogMetadata[lfn]['Checksum'] and metadata['Checksum'] and \ not compareAdler( metadata['Checksum'], self.catalogMetadata[lfn]['Checksum'] ): gLogger.warn( "resolveSource: skipping %s - source file checksum mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source checksum mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif lfnStatus == 'Staging': # file that was staging is now cached self.__setFileParameter( lfn, 'Status', 'Waiting' ) nbStagedFiles += 1 # Some files were being staged if nbStagedFiles: self.log.info( 'resolveSource: %d files have been staged' % nbStagedFiles ) # Launching staging of files not in cache if toStage: gLogger.warn( "resolveSource: %s source files not cached, prestaging..." % len( toStage ) ) stage = self.oSourceSE.prestageFile( toStage ) if not stage["OK"]: gLogger.error( "resolveSource: error is prestaging", stage["Message"] ) for lfn in toStage: self.__setFileParameter( lfn, 'Reason', stage["Message"] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: for lfn in toStage: if lfn in stage['Value']['Successful']: self.__setFileParameter( lfn, 'Status', 'Staging' ) elif lfn in stage['Value']['Failed']: self.__setFileParameter( lfn, 'Reason', stage['Value']['Failed'][lfn] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) self.sourceResolved = True return S_OK() def resolveTarget( self ): """ find target SE eligible for submission :param self: self reference """ toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status' ) not in self.noSubmitStatus ] if not toResolve: return S_OK() res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res for lfn in toResolve: res = returnSingleResult( self.oTargetSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: reason = res.get( 'Message', res['Message'] ) gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, reason ) ) self.__setFileParameter( lfn, 'Reason', reason ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setTargetSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Target" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Target files" ) res = self.oTargetSE.exists( toResolve ) if not res['OK']: return S_ERROR( "Failed to check target existence" ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toRemove = [] for lfn, exists in res['Value']['Successful'].items(): if exists: res = self.getSourceSURL( lfn ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - target exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Target exists" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif res['Value'] == self.fileDict[lfn]['Target']: gLogger.warn( "resolveTarget: skipping %s - source and target pfns are the same" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source and Target the same" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRemove.append( lfn ) if toRemove: self.oTargetSE.removeFile( toRemove ) return S_OK() def __filesToSubmit( self ): """ check if there is at least one file to submit :return: S_OK if at least one file is present, S_ERROR otherwise """ for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) source = self.fileDict[lfn].get( 'Source' ) target = self.fileDict[lfn].get( 'Target' ) if lfnStatus not in self.noSubmitStatus and source and target: return S_OK() return S_ERROR() def __createFTSFiles( self ): """ create LFNs file for glite-transfer-submit command This file consists one line for each fiel to be transferred: sourceSURL targetSURL [CHECKSUMTYPE:CHECKSUM] :param self: self reference """ self.__updateMetadataCache() for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) if lfnStatus not in self.noSubmitStatus: cksmStr = "" # # add chsmType:cksm only if cksmType is specified, else let FTS decide by itself if self.__cksmTest and self.__cksmType: checkSum = self.catalogMetadata.get( lfn, {} ).get( 'Checksum' ) if checkSum: cksmStr = " %s:%s" % ( self.__cksmType, intAdlerToHex( hexAdlerToInt( checkSum ) ) ) ftsFile = FTSFile() ftsFile.LFN = lfn ftsFile.SourceSURL = self.fileDict[lfn].get( 'Source' ) ftsFile.TargetSURL = self.fileDict[lfn].get( 'Target' ) ftsFile.SourceSE = self.sourceSE ftsFile.TargetSE = self.targetSE ftsFile.Status = self.fileDict[lfn].get( 'Status' ) ftsFile.Checksum = cksmStr ftsFile.Size = self.catalogMetadata.get( lfn, {} ).get( 'Size' ) self.ftsFiles.append( ftsFile ) self.submittedFiles += 1 return S_OK() def __createFTSJob( self, guid = None ): self.__createFTSFiles() ftsJob = FTSJob() ftsJob.RequestID = 0 ftsJob.OperationID = 0 ftsJob.SourceSE = self.sourceSE ftsJob.TargetSE = self.targetSE ftsJob.SourceToken = self.sourceToken ftsJob.TargetToken = self.targetToken ftsJob.FTSServer = self.ftsServer if guid: ftsJob.FTSGUID = guid for ftsFile in self.ftsFiles: ftsFile.Attempt += 1 ftsFile.Error = "" ftsJob.addFile( ftsFile ) self.ftsJob = ftsJob def __submitFTSTransfer( self ): """ create and execute glite-transfer-submit CLI command :param self: self reference """ log = gLogger.getSubLogger( 'Submit' ) self.__createFTSJob() submit = self.ftsJob.submitFTS2( command = self.submitCommand ) if not submit["OK"]: log.error( "unable to submit FTSJob: %s" % submit["Message"] ) return submit log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) # # update statuses for job files for ftsFile in self.ftsJob: ftsFile.FTSGUID = self.ftsJob.FTSGUID ftsFile.Status = "Submitted" ftsFile.Attempt += 1 log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) self.ftsGUID = self.ftsJob.FTSGUID return S_OK() def __resolveFTSServer( self ): """ resolve FTS server to use, it should be the closest one from target SE :param self: self reference """ from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTSServersForSites if not self.targetSE: return S_ERROR( "Target SE not set" ) res = getSitesForSE( self.targetSE ) if not res['OK'] or not res['Value']: return S_ERROR( "Could not determine target site" ) targetSites = res['Value'] targetSite = '' for targetSite in targetSites: targetFTS = getFTSServersForSites( [targetSite] ) if targetFTS['OK']: ftsTarget = targetFTS['Value'][targetSite] if ftsTarget: self.ftsServer = ftsTarget return S_OK( self.ftsServer ) else: return targetFTS return S_ERROR( 'No FTS server found for %s' % targetSite ) #################################################################### # # Methods for monitoring # def summary( self, untilTerminal = False, printOutput = False ): """ summary of FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ res = self.__isSummaryValid() if not res['OK']: return res while not self.isTerminal: res = self.__parseOutput( full = True ) if not res['OK']: return res if untilTerminal: self.__print() self.isRequestTerminal() if res['Value'] or ( not untilTerminal ): break time.sleep( 1 ) if untilTerminal: print "" if printOutput and ( not untilTerminal ): return self.dumpSummary( printOutput = printOutput ) return S_OK() def monitor( self, untilTerminal = False, printOutput = False, full = True ): """ monitor FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ if not self.ftsJob: self.resolveSource() self.__createFTSJob( self.ftsGUID ) res = self.__isSummaryValid() if not res['OK']: return res if untilTerminal: res = self.summary( untilTerminal = untilTerminal, printOutput = printOutput ) if not res['OK']: return res res = self.__parseOutput( full = full ) if not res['OK']: return res if untilTerminal: self.finalize() if printOutput: self.dump() return res def dumpSummary( self, printOutput = False ): """ get FTS job summary as str :param self: self reference :param bool printOutput: print summary to stdout """ outStr = '' for status in sorted( self.statusSummary ): if self.statusSummary[status]: outStr = '%s\t%-10s : %-10s\n' % ( outStr, status, str( self.statusSummary[status] ) ) outStr = outStr.rstrip( '\n' ) if printOutput: print outStr return S_OK( outStr ) def __print( self ): """ print progress bar of FTS job completeness to stdout :param self: self reference """ width = 100 bits = int( ( width * self.percentageComplete ) / 100 ) outStr = "|%s>%s| %.1f%s %s %s" % ( "="*bits, " "*( width - bits ), self.percentageComplete, "%", self.requestStatus, " "*10 ) sys.stdout.write( "%s\r" % ( outStr ) ) sys.stdout.flush() def dump( self ): """ print FTS job parameters and files to stdout :param self: self reference """ print "%-10s : %-10s" % ( "Status", self.requestStatus ) print "%-10s : %-10s" % ( "Source", self.sourceSE ) print "%-10s : %-10s" % ( "Target", self.targetSE ) print "%-10s : %-128s" % ( "Server", self.ftsServer ) print "%-10s : %-128s" % ( "GUID", self.ftsGUID ) for lfn in sorted( self.fileDict ): print "\n %-15s : %-128s" % ( 'LFN', lfn ) for key in ['Source', 'Target', 'Status', 'Reason', 'Duration']: print " %-15s : %-128s" % ( key, str( self.fileDict[lfn].get( key ) ) ) return S_OK() def __isSummaryValid( self ): """ check validity of FTS job summary report :param self: self reference """ if not self.ftsServer: return S_ERROR( "FTSServer not set" ) if not self.ftsGUID: return S_ERROR( "FTSGUID not set" ) return S_OK() def __parseOutput( self, full = False ): """ execute glite-transfer-status command and parse its output :param self: self reference :param bool full: glite-transfer-status verbosity level, when set, collect information of files as well """ monitor = self.ftsJob.monitorFTS2( command = self.monitorCommand, full = full ) if not monitor['OK']: return monitor self.percentageComplete = self.ftsJob.Completeness self.requestStatus = self.ftsJob.Status self.submitTime = self.ftsJob.SubmitTime statusSummary = monitor['Value'] if statusSummary: for state in statusSummary: self.statusSummary[state] = statusSummary[state] self.transferTime = 0 for ftsFile in self.ftsJob: lfn = ftsFile.LFN self.__setFileParameter( lfn, 'Status', ftsFile.Status ) self.__setFileParameter( lfn, 'Reason', ftsFile.Error ) self.__setFileParameter( lfn, 'Duration', ftsFile._duration ) targetURL = self.__getFileParameter( lfn, 'Target' ) if not targetURL['OK']: self.__setFileParameter( lfn, 'Target', ftsFile.TargetSURL ) self.transferTime += int( ftsFile._duration ) return S_OK() #################################################################### # # Methods for finalization # def finalize( self ): """ finalize FTS job :param self: self reference """ self.__updateMetadataCache() transEndTime = dateTime() regStartTime = time.time() res = self.getTransferStatistics() transDict = res['Value'] res = self.__registerSuccessful( transDict['transLFNs'] ) regSuc, regTotal = res['Value'] regTime = time.time() - regStartTime if self.sourceSE and self.targetSE: self.__sendAccounting( regSuc, regTotal, regTime, transEndTime, transDict ) return S_OK() def getTransferStatistics( self ): """ collect information of Transfers that can be used by Accounting :param self: self reference """ transDict = { 'transTotal': len( self.fileDict ), 'transLFNs': [], 'transOK': 0, 'transSize': 0 } for lfn in self.fileDict: if self.fileDict[lfn].get( 'Status' ) in self.successfulStates: if self.fileDict[lfn].get( 'Duration', 0 ): transDict['transLFNs'].append( lfn ) transDict['transOK'] += 1 if lfn in self.catalogMetadata: transDict['transSize'] += self.catalogMetadata[lfn].get( 'Size', 0 ) return S_OK( transDict ) def getFailedRegistrations( self ): """ get failed registrations dict :param self: self reference """ return S_OK( self.failedRegistrations ) def __registerSuccessful( self, transLFNs ): """ register successfully transferred files to the catalogs, fill failedRegistrations dict for files that failed to register :param self: self reference :param list transLFNs: LFNs in FTS job """ self.failedRegistrations = {} toRegister = {} for lfn in transLFNs: res = returnSingleResult( self.oTargetSE.getURL( self.fileDict[lfn].get( 'Target' ), protocol = 'srm' ) ) if not res['OK']: self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRegister[lfn] = { 'PFN' : res['Value'], 'SE' : self.targetSE } if not toRegister: return S_OK( ( 0, 0 ) ) res = self.__getCatalogObject() if not res['OK']: for lfn in toRegister: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) res = self.oCatalog.addReplica( toRegister ) if not res['OK']: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) for lfn, error in res['Value']['Failed'].items(): self.failedRegistrations[lfn] = toRegister[lfn] self.log.error( 'Registration of Replica failed', '%s : %s' % ( lfn, str( error ) ) ) return S_OK( ( len( res['Value']['Successful'] ), len( toRegister ) ) ) def __sendAccounting( self, regSuc, regTotal, regTime, transEndTime, transDict ): """ send accounting record :param self: self reference :param regSuc: number of files successfully registered :param regTotal: number of files attepted to register :param regTime: time stamp at the end of registration :param transEndTime: time stamp at the end of FTS job :param dict transDict: dict holding couters for files being transerred, their sizes and successfull transfers """ oAccounting = DataOperation() oAccounting.setEndTime( transEndTime ) oAccounting.setStartTime( self.submitTime ) accountingDict = {} accountingDict['OperationType'] = 'replicateAndRegister' result = getProxyInfo() if not result['OK']: userName = 'system' else: userName = result['Value'].get( 'username', 'unknown' ) accountingDict['User'] = userName accountingDict['Protocol'] = 'FTS' if 'fts3' not in self.ftsServer else 'FTS3' accountingDict['RegistrationTime'] = regTime accountingDict['RegistrationOK'] = regSuc accountingDict['RegistrationTotal'] = regTotal accountingDict['TransferOK'] = transDict['transOK'] accountingDict['TransferTotal'] = transDict['transTotal'] accountingDict['TransferSize'] = transDict['transSize'] accountingDict['FinalStatus'] = self.requestStatus accountingDict['Source'] = self.sourceSE accountingDict['Destination'] = self.targetSE accountingDict['TransferTime'] = self.transferTime oAccounting.setValuesFromDict( accountingDict ) self.log.verbose( "Attempting to commit accounting message..." ) oAccounting.commit() self.log.verbose( "...committed." ) return S_OK()
miloszz/DIRAC
DataManagementSystem/Client/FTSRequest.py
Python
gpl-3.0
37,261
<?php namespace de\chilan\WebsiteBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class WebsiteBundle extends Bundle { }
Mirar85/chilan
src/de/chilan/WebsiteBundle/WebsiteBundle.php
PHP
gpl-3.0
131
var _ = require("lodash"); module.exports = { // ensure client accepts json json_request: function(req, res, next){ if(req.accepts("application/json")) return next(); res.stash.code = 406; _.last(req.route.stack).handle(req, res, next); }, // init response init_response: function(req, res, next){ res.stash = {}; res.response_start = new Date(); return next(); }, // respond to client handle_response: function(req, res, next){ res.setHeader("X-Navigator-Response-Time", new Date() - res.response_start); res.stash = _.defaults(res.stash, { code: 404 }); if(_.has(res.stash, "body")) res.status(res.stash.code).json(res.stash.body); else res.sendStatus(res.stash.code); } }
normanjoyner/containership.plugin.navigator
lib/middleware.js
JavaScript
gpl-3.0
854
// Decompiled with JetBrains decompiler // Type: System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection // Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll using System; using System.Collections; using System.ComponentModel; using System.Drawing.Design; using System.Runtime; namespace System.Web.UI.WebControls.WebParts { /// <summary> /// Contains a collection of static <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects, which is used when the connections are declared in content pages and the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartManager"/> control is declared in a master page. This class cannot be inherited. /// </summary> [Editor("System.ComponentModel.Design.CollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))] public sealed class ProxyWebPartConnectionCollection : CollectionBase { private WebPartManager _webPartManager; /// <summary> /// Gets a value indicating whether <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects can be added to the collection. /// </summary> /// /// <returns> /// true if connection objects cannot be added to the collection; otherwise, false. /// </returns> public bool IsReadOnly { get { if (this._webPartManager != null) return this._webPartManager.StaticConnections.IsReadOnly; return false; } } /// <summary> /// Gets or sets a connection item within the collection, based on an index number indicating the item's location in the collection. /// </summary> /// /// <returns> /// A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> at the specified index in the collection. /// </returns> /// <param name="index">An integer that indicates the index of a member of the collection. </param> public WebPartConnection this[int index] { get { return (WebPartConnection) this.List[index]; } set { this.List[index] = (object) value; } } /// <summary> /// Returns a specific member of the collection according to a unique identifier. /// </summary> /// /// <returns> /// The first <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> whose ID matches the value of the <paramref name="id"/> parameter. Returns null if no match is found. /// </returns> /// <param name="id">A string that contains the ID of a particular connection in the collection. </param> public WebPartConnection this[string id] { get { foreach (WebPartConnection webPartConnection in (IEnumerable) this.List) { if (webPartConnection != null && string.Equals(webPartConnection.ID, id, StringComparison.OrdinalIgnoreCase)) return webPartConnection; } return (WebPartConnection) null; } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection"/> class. /// </summary> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public ProxyWebPartConnectionCollection() { } /// <summary> /// Adds a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object to the collection. /// </summary> /// /// <returns> /// An integer value that indicates where the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> was inserted into the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to add to the collection. </param> public int Add(WebPartConnection value) { return this.List.Add((object) value); } /// <summary> /// Returns a value indicating whether a particular <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object exists in the collection. /// </summary> /// /// <returns> /// true if <paramref name="value"/> exists in the collection; otherwise, false. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> being checked for its existence in a collection. </param> public bool Contains(WebPartConnection value) { return this.List.Contains((object) value); } /// <summary> /// Copies the collection to an array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects. /// </summary> /// <param name="array">An array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects to contain the copied collection. </param><param name="index">An integer that indicates the starting point in the array at which to place the collection contents. </param> public void CopyTo(WebPartConnection[] array, int index) { this.List.CopyTo((Array) array, index); } /// <summary> /// Returns the position of a particular member of the collection. /// </summary> /// /// <returns> /// An integer that indicates the position of a particular object in the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> that is a member of the collection. </param> public int IndexOf(WebPartConnection value) { return this.List.IndexOf((object) value); } /// <summary> /// Inserts a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object into the collection at the specified index. /// </summary> /// <param name="index">An integer indicating the ordinal position in the collection at which a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> should be inserted. </param><param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to insert into the collection. </param> public void Insert(int index, WebPartConnection value) { this.List.Insert(index, (object) value); } protected override void OnClear() { this.CheckReadOnly(); if (this._webPartManager != null) { foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Remove(webPartConnection); } base.OnClear(); } protected override void OnInsert(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Insert(index, (WebPartConnection) value); base.OnInsert(index, value); } protected override void OnRemove(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Remove((WebPartConnection) value); base.OnRemove(index, value); } protected override void OnSet(int index, object oldValue, object newValue) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections[this._webPartManager.StaticConnections.IndexOf((WebPartConnection) oldValue)] = (WebPartConnection) newValue; base.OnSet(index, oldValue, newValue); } protected override void OnValidate(object value) { base.OnValidate(value); if (value == null) throw new ArgumentNullException("value", System.Web.SR.GetString("Collection_CantAddNull")); if (!(value is WebPartConnection)) throw new ArgumentException(System.Web.SR.GetString("Collection_InvalidType", new object[1] { (object) "WebPartConnection" })); } /// <summary> /// Removes the specified <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object from the collection. /// </summary> /// <param name="value">The <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to be removed. </param> public void Remove(WebPartConnection value) { this.List.Remove((object) value); } internal void SetWebPartManager(WebPartManager webPartManager) { this._webPartManager = webPartManager; foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Add(webPartConnection); } private void CheckReadOnly() { if (this.IsReadOnly) throw new InvalidOperationException(System.Web.SR.GetString("ProxyWebPartConnectionCollection_ReadOnly")); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/WebParts/ProxyWebPartConnectionCollection.cs
C#
gpl-3.0
8,862
// Copyright (c) The University of Dundee 2018-2019 // This file is part of the Research Data Management Platform (RDMP). // RDMP 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. // RDMP 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 RDMP. If not, see <https://www.gnu.org/licenses/>. using System.Windows.Forms; using MapsDirectlyToDatabaseTable; namespace Rdmp.UI.Refreshing { /// <summary> /// <see cref="IRefreshBusSubscriber"/> for <see cref="Control"/> classes which want their lifetime to be linked to a single /// <see cref="IMapsDirectlyToDatabaseTable"/> object. This grants notifications of publish events about the object and ensures /// your <see cref="Control"/> is closed when/if the object is deleted. /// /// <para>See <see cref="RefreshBus.EstablishLifetimeSubscription"/></para> /// </summary> public interface ILifetimeSubscriber:IContainerControl,IRefreshBusSubscriber { } }
HicServices/RDMP
Rdmp.UI/Refreshing/ILifetimeSubscriber.cs
C#
gpl-3.0
1,369
import sys, os, urllib, time, socket, mt, ssl from dlmanager.NZB import NZBParser from dlmanager.NZB.nntplib2 import NNTP_SSL,NNTPError,NNTP, NNTPReplyError from dlmanager.NZB.Decoder import ArticleDecoder class StatusReport(object): def __init__(self): self.message = "Downloading.." self.total_bytes = 0 self.current_bytes = 0 self.completed = False self.error_occured = False self.start_time = 0 self.file_name = "" self.kbps = 0 self.assembly = False self.assembly_percent = 0 class NZBClient(): def __init__(self, nzbFile, save_to, nntpServer, nntpPort, nntpUser=None, nntpPassword=None, nntpSSL=False, nntpConnections=5, cache_path=""): # Settings self.save_to = save_to self.nntpServer = nntpServer self.nntpUser = nntpUser self.nntpPort = nntpPort self.nntpPassword = nntpPassword self.nntpSSL = nntpSSL self.nntpConnections = nntpConnections self.threads = [] self.running = False # setup our cache folder. self.cache_path = cache_path if ( self.cache_path == "" ): self.cache_path = "packages/dlmanager/cache/" self.clearCache() # ensure both directorys exist mt.utils.mkdir(self.save_to) mt.utils.mkdir(self.cache_path) # Open the NZB, get this show started. realFile = urllib.urlopen(nzbFile) self.nzb = NZBParser.parse(realFile) self.all_decoded = False self.connection_count = 0 # used to track status. self.status = StatusReport() self.status.file_name = nzbFile self.status.total_bytes = self.nzb.size # Segment tracking. self.cache = [] self.segment_list = [] self.segments_finished = [] self.segments_aborted = [] # Queues. self.segment_queue = [] self.failed_queue = [] # Used to track the speed. self.speedTime = 0 self.speedCounter = 0 def start(self): # keep track of running time. self.status.start_time = time.time() self.running = True # Generate a list of segments and build our queue. for file in self.nzb.files: for seg in file.segments: self.segment_list.append(seg.msgid) self.segment_queue.append(seg) # start the connections. for a in range(0, self.nntpConnections): thread = NNTPConnection(a, self.nntpServer, self.nntpPort, self.nntpUser, self.nntpPassword, self.nntpSSL, self.nextSeg, self.segComplete, self.segFailed, self.threadStopped) self.threads.append(thread) self.connection_count += 1 thread.start() # start the article decoder. self.articleDecoder = ArticleDecoder(self.decodeNextSeg, self.save_to, self.cache_path, self.decodeFinished, self.decodeSuccess, self.decodeFailed, self.assemblyStatus) self.articleDecoder.start() def getStatus(self): return self.status # Article Decoder - Next segment. def decodeNextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to grab a segment from the cache to decode. seg = None try: seg = self.cache.pop() except: pass if ( seg == None ) and ( self.all_decoded ): return -1 return seg # Article Decoder - Decoded all segments. def decodeFinished(self): self.status.completed = True # Article Decoder - Decode success. def decodeSuccess(self, seg): self.status.current_bytes += seg.size self.segments_finished.append(seg.msgid) if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True # Article Decoder - Decode failed. def decodeFailed(self, seg): if ( seg == None ): return mt.log.debug("Segment failed to decode: " + seg.msgid) self.segFailed(seg) # Article Decoder - Assembly Status. def assemblyStatus(self, percent): self.status.assembly = True self.status.assembly_percent = percent # NNTP Connection - Thread stopped. def threadStopped(self, thread_num): self.connection_count -= 1 # NNTP Connection - Segment completed. def segComplete(self, seg): if ( seg == None ): return if ( seg.data ): data_size = len("".join(seg.data)) current_time = time.time() if ( (current_time - self.speedTime) > 1 ): self.status.kbps = self.speedCounter self.speedCounter = 0 self.speedTime = current_time else: self.speedCounter += (data_size/1024) self.cache.append(seg) #mt.log.debug("Segment Complete: " + seg.msgid) # NNTP Connection - Download of segment failed. def segFailed(self, seg): if ( seg == None ): return if ( seg.aborted() ): mt.log.error("Segment Aborted: " + seg.msgid + " after " + str(seg.retries) + " attempts.") self.segments_aborted.append(seg.msgid) seg.data = [] if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True return seg.retries += 1 mt.log.error("Segment Failed: " + seg.msgid + " Attempt #" + str(seg.retries) + ".") self.failed_queue.append(seg) # NNTP Connection - Next Segment def nextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to get a segment from main queue or failed queue. queue_empty = False seg = None try: seg = self.segment_queue.pop() except: try: seg = self.failed_queue.pop() except: queue_empty = True pass pass # We're all outta segments, if they're done decoding, kill the threads. if ( queue_empty ) and ( self.all_decoded ): return -1 return seg # empty the cache of any files. def clearCache(self): mt.utils.rmdir(self.cache_path) def stop(self): self.running = False self.articleDecoder.stop() for thread in self.threads: thread.stop() self.clearCache() class NNTPConnection(mt.threads.Thread): def __init__(self, connection_number, server, port, username, password, ssl, nextSegFunc, onSegComplete = None, onSegFailed = None, onThreadStop = None): mt.threads.Thread.__init__(self) # Settings self.connection = None self.connection_number = connection_number self.server = server self.port = port self.username = username self.password = password self.ssl = ssl # Events. self.nextSegFunc = nextSegFunc self.onSegComplete = onSegComplete self.onSegFailed = onSegFailed self.onThreadStop = onThreadStop def connect(self): # Open either an SSL or regular NNTP connection. try: if ( self.ssl ): self.connection = NNTP_SSL(self.server, self.port, self.username, self.password, False, True, timeout=15) else: self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15) except: pass if ( self.connection ): return True return False def disconnect(self): if ( self.connection ): try: self.connection.quit() except: pass self.connection = None def run(self): connection = None seg = None # Thread has started. mt.log.debug("Thread " + str(self.connection_number) + " started.") start_time = time.time() while(self.running): seg = None connected = self.connect() if ( connected ): while(self.running): seg = self.nextSegFunc() # Out of segments, sleep for a bit and see if we get anymore. if ( seg == None ): self.sleep(0.1) continue # Download complete, bail. if ( seg == -1 ): self.running = False seg = None break # Attempt to grab a segment. try: resp, nr, id, data = self.connection.body("<%s>" % seg.msgid) if resp[0] == "2": seg.data = data if ( self.onSegComplete ): self.onSegComplete(seg) seg = None except ssl.SSLError: break except NNTPError as e: mt.log.error("Error getting segment: " + e.response) pass except: mt.log.error("Error getting segment.") pass if ( seg and self.onSegFailed ): self.onSegFailed(seg) seg = None # Disconnect when we're finished. if ( seg and self.onSegFailed ): self.onSegFailed(seg) self.disconnect() else: mt.log.error("Connection error. Reconnecting in 3 seconds.") self.sleep(3) # Thread has ended. self.disconnect() # just to be safe. end_time = time.time() mt.log.debug("Thread " + str(self.connection_number) + " stopped after " + str(end_time-start_time) + " seconds.") if ( self.onThreadStop ): self.onThreadStop(self.connection_number)
andr3wmac/metaTower
packages/dlmanager/NZB/NZBClient.py
Python
gpl-3.0
10,499
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0
schesis/fix
tests/decorators/test_with_fixture.py
Python
gpl-3.0
3,536
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ 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. # # ESPResSo++ 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/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )
espressopp/espressopp
src/integrator/CapForce.py
Python
gpl-3.0
2,764
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ #include "demandmodel.h" #include "Elements/junction.h" #include <cmath> #include <algorithm> using namespace std; //----------------------------------------------------------------------------- // Parent constructor and destructor //----------------------------------------------------------------------------- DemandModel::DemandModel() : expon(0.0) {} DemandModel::DemandModel(double expon_) : expon(expon_) {} DemandModel::~DemandModel() {} //----------------------------------------------------------------------------- // Demand model factory //----------------------------------------------------------------------------- DemandModel* DemandModel::factory(const string model, const double expon_) { if ( model == "FIXED" ) return new FixedDemandModel(); else if ( model == "CONSTRAINED" ) return new ConstrainedDemandModel(); else if ( model == "POWER" ) return new PowerDemandModel(expon_); else if ( model == "LOGISTIC" ) return new LogisticDemandModel(expon_); else return nullptr; } //----------------------------------------------------------------------------- // Default functions //----------------------------------------------------------------------------- double DemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->fullDemand; } //----------------------------------------------------------------------------- /// Fixed Demand Model //----------------------------------------------------------------------------- FixedDemandModel::FixedDemandModel() {} //----------------------------------------------------------------------------- /// Constrained Demand Model //----------------------------------------------------------------------------- ConstrainedDemandModel::ConstrainedDemandModel() {} bool ConstrainedDemandModel::isPressureDeficient(Junction* junc) { //if ( junc->fixedGrade || // ... return false if normal full demand is non-positive if (junc->fullDemand <= 0.0 ) return false; double hMin = junc->elev + junc->pMin; if ( junc->head < hMin ) { junc->fixedGrade = true; junc->head = hMin; return true; } return false; } double ConstrainedDemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->actualDemand; } //----------------------------------------------------------------------------- /// Power Demand Model //----------------------------------------------------------------------------- PowerDemandModel::PowerDemandModel(double expon_) : DemandModel(expon_) {} double PowerDemandModel::findDemand(Junction* junc, double p, double& dqdh) { // ... initialize demand and demand derivative double qFull = junc->fullDemand; double q = qFull; dqdh = 0.0; // ... check for positive demand and pressure range double pRange = junc->pFull - junc->pMin; if ( qFull > 0.0 && pRange > 0.0) { // ... find fraction of full pressure met (f) double factor = 0.0; double f = (p - junc->pMin) / pRange; // ... apply power function if (f <= 0.0) factor = 0.0; else if (f >= 1.0) factor = 1.0; else { factor = pow(f, expon); dqdh = expon / pRange * factor / f; } // ... update total demand and its derivative q = qFull * factor; dqdh = qFull * dqdh; } return q; } //----------------------------------------------------------------------------- /// Logistic Demand Model //----------------------------------------------------------------------------- LogisticDemandModel::LogisticDemandModel(double expon_) : DemandModel(expon_), a(0.0), b(0.0) {} double LogisticDemandModel::findDemand(Junction* junc, double p, double& dqdh) { double f = 1.0; // fraction of full demand double q = junc->fullDemand; // demand flow (cfs) double arg; // argument of exponential term double dfdh; // gradient of f w.r.t. pressure head // ... initialize derivative dqdh = 0.0; // ... check for positive demand and pressure range if ( junc->fullDemand > 0.0 && junc->pFull > junc->pMin ) { // ... find logistic function coeffs. a & b setCoeffs(junc->pMin, junc->pFull); // ... prevent against numerical over/underflow arg = a + b*p; if (arg < -100.) arg = -100.0; else if (arg > 100.0) arg = 100.0; // ... find fraction of full demand (f) and its derivative (dfdh) f = exp(arg); f = f / (1.0 + f); f = max(0.0, min(1.0, f)); dfdh = b * f * (1.0 - f); // ... evaluate demand and its derivative q = junc->fullDemand * f; dqdh = junc->fullDemand * dfdh; } return q; } void LogisticDemandModel::setCoeffs(double pMin, double pFull) { // ... computes logistic function coefficients // assuming 99.9% of full demand at full pressure // and 1% of full demand at minimum pressure. double pRange = pFull - pMin; a = (-4.595 * pFull - 6.907 * pMin) / pRange; b = 11.502 / pRange; }
jeffrey-newman/ENLink
OWA_EN3/src/Models/demandmodel.cpp
C++
gpl-3.0
5,340
class AddVersionDone < ActiveRecord::Migration def up add_column :versions, :is_done, :boolean end def down remove_column :versions, :is_done end end
nmeylan/RORganize
db/migrate/20140623191731_add_version_done.rb
Ruby
gpl-3.0
167
var struct_m_s_vehicle_1_1_lane_q = [ [ "allowsContinuation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a1491a03d3e914ce9f78fe892c6f8594b", null ], [ "bestContinuations", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a2fc7b1df76210eff08026dbd53c13312", null ], [ "bestLaneOffset", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#aa7f926a77c7d33c071c620ae7e9d0ac1", null ], [ "lane", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a3df6bd9b94a7e3e4795547feddf68bf2", null ], [ "length", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a637a05a2b120bacaf781181febc5b3bb", null ], [ "nextOccupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#acf8243e1febeb75b139a8b10bb679107", null ], [ "occupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a51e793a9c0bfda3e315c62f579089f82", null ] ];
cathyyul/sumo-0.18
docs/doxygen/d3/d89/struct_m_s_vehicle_1_1_lane_q.js
JavaScript
gpl-3.0
801
/* * This file is part of JGCGen. * * JGCGen 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. * * JGCGen 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 JGCGen. If not, see <http://www.gnu.org/licenses/>. */ package org.luolamies.jgcgen.text; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.luolamies.jgcgen.RenderException; public class Fonts { private final File workdir; public Fonts(File workdir) { this.workdir = workdir; } public Font get(String name) { String type; if(name.endsWith(".jhf")) type = "Hershey"; else throw new RenderException("Can't figure out font type from filename! Use $fonts.get(\"file\", \"type\")"); return get(name, type); } @SuppressWarnings("unchecked") public Font get(String name, String type) { Class<? extends Font> fclass; try { fclass = (Class<? extends Font>) Class.forName(getClass().getPackage().getName() + "." + type + "Font"); } catch (ClassNotFoundException e1) { throw new RenderException("Font type \"" + type + "\" not supported!"); } InputStream in; File file = new File(workdir, name); if(file.isFile()) { try { in = new FileInputStream(file); } catch (FileNotFoundException e) { in = null; } } else in = getClass().getResourceAsStream("/fonts/" + name); if(in==null) throw new RenderException("Can't find font: " + name); try { return fclass.getConstructor(InputStream.class).newInstance(in); } catch(Exception e) { throw new RenderException("Error while trying to construct handler for font \"" + type + "\": " + e.getMessage(), e); } finally { try { in.close(); } catch (IOException e) { } } } }
callaa/JGCGen
src/org/luolamies/jgcgen/text/Fonts.java
Java
gpl-3.0
2,230
// -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et: // $Id$ /* MetaTweet * Hub system for micro-blog communication services * SqlServerStorage * MetaTweet Storage module which is provided by Microsoft SQL Server RDBMS. * Part of MetaTweet * Copyright © 2008-2011 Takeshi KIRIYA (aka takeshik) <takeshik@users.sf.net> * All rights reserved. * * This file is part of SqlServerStorage. * * 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 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. */ using System; using System.Data.EntityClient; using System.Data.Objects; using System.Reflection; namespace XSpect.MetaTweet.Objects { public class StorageObjectContext : ObjectContext { public const String ContainerName = "StorageObjectContext"; private ObjectSet<Account> _accounts; private ObjectSet<Activity> _activities; private ObjectSet<Advertisement> _advertisements; public StorageObjectContext(String connectionString) : base(connectionString, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public StorageObjectContext(EntityConnection connection) : base(connection, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public ObjectSet<Account> Accounts { get { return this._accounts ?? (this._accounts = this.CreateObjectSet<Account>("Accounts")); } } public ObjectSet<Activity> Activities { get { return this._activities ?? (this._activities = this.CreateObjectSet<Activity>("Activities")); } } public ObjectSet<Advertisement> Advertisements { get { return this._advertisements ?? (this._advertisements = this.CreateObjectSet<Advertisement>("Advertisements")); } } public Boolean IsDisposed { get { // HACK: Depends on internal structure, accessing non-public field return typeof(ObjectContext) .GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(this) == null; } } public ObjectSet<TObject> GetObjectSet<TObject>() where TObject : StorageObject { return (ObjectSet<TObject>) (typeof(TObject) == typeof(Account) ? (Object) this.Accounts : typeof(TObject) == typeof(Activity) ? (Object) this.Activities : this.Advertisements ); } public String GetEntitySetName<TObject>() where TObject : StorageObject { return typeof(TObject) == typeof(Account) ? ContainerName + ".Accounts" : typeof(TObject) == typeof(Activity) ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } public String GetEntitySetName(StorageObject obj) { return obj is Account ? ContainerName + ".Accounts" : obj is Activity ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } } }
takeshik/metatweet-old
SqlServerStorage/StorageObjectContext.cs
C#
gpl-3.0
4,365
# -*- coding: utf-8 -*- """proyectoP4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url, patterns from django.contrib import admin from Workinout import views from django.conf import settings urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*) ] if settings.DEBUG: urlpatterns += patterns( 'django.views.static', (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), ) else: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}), )
jesmorc/Workinout
proyectoP4/urls.py
Python
gpl-3.0
1,273
#region using directives using POGOProtos.Enums; using POGOProtos.Settings.Master.Pokemon; #endregion namespace PoGo.PokeMobBot.Logic.Event.Pokemon { public class BaseNewPokemonEvent : IEvent { public int Cp; public ulong Uid; public PokemonId Id; public double Perfection; public PokemonFamilyId Family; public int Candy; public double Level; public PokemonMove Move1; public PokemonMove Move2; public PokemonType Type1; public PokemonType Type2; public StatsAttributes Stats; public int MaxCp; public int Stamina; public int IvSta; public int PossibleCp; public int CandyToEvolve; public int IvAtk; public int IvDef; public float Cpm; public float Weight; public int StaminaMax; public PokemonId[] Evolutions; public double Latitude; public double Longitude; } }
Lunat1q/Catchem-PoGo
Source/PoGo.PokeMobBot.Logic/Event/Pokemon/BaseNewPokemonEvent.cs
C#
gpl-3.0
982
#!/usr/bin/python # This programs is intended to manage patches and apply them automatically # through email in an automated fashion. # # Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.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. # # 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. import poplib, email, re, sys, xmlConfigs, utils; class ReferenceNode : def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")): self.node = node self.children = dict(children) self.references = references[:] self.slotted = slotted self.emailMessage = emailMessage def get_node(self): return self.node def get_children(self): return self.children def set_node(self, node): self.node = node def set_children(self, children): self.children = children def get_references(self): return self.references def is_slotted(self): return self.slotted def set_slotted(self, slotted): self.slotted = slotted def get_message(self): return self.emailMessage def __repr__(self): return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n" def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode): for reference in referencesToCheck[:] : if reference in referenceNodeNow.get_children() : referencesToCheck.remove(reference) return patchMessageReferenceNode[reference] if len(referencesToCheck) == 0 : referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction def makeChildren(patchMessageReferenceNode) : ref_keys = patchMessageReferenceNode.keys() ref_keys.sort() for messageId in ref_keys: referenceNode = patchMessageReferenceNode[messageId] utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node()) referenceIds = referenceNode.get_references() referenceIdsClone = referenceIds[:] utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone) if len(referenceIds) > 0 : nextNode = patchMessageReferenceNode[referenceIdsClone[0]] referenceIdsClone.remove(referenceIdsClone[0]) while nextNode != None : utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node()) utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node()) utils.verboseOutput(verbose, "REF: ", referenceIdsClone) nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) if __name__ == "__main__": arguments = sys.argv verbose = "false" pseudoArgs = arguments[:] while len(pseudoArgs) > 1 : argument = pseudoArgs[1] if argument == "-v" or argument == "--verbose" : verbose = "true" pseudoArgs.remove(argument) utils.verboseOutput(verbose, "Checking POP3 for gmail") try: emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml") myPop = emailConfig.get_pop3_connection() numMessages = len(myPop.list()[1]) patchMessages = dict() for i in range(numMessages): utils.verboseOutput(verbose, "Index: ", i) totalContent = "" for content in myPop.retr(i+1)[1]: totalContent += content + '\n' msg = email.message_from_string(totalContent) if 'subject' in msg : subject = msg['subject'] subjectPattern = "^\[.*PATCH.*\].+" subjectMatch = re.match(subjectPattern, subject) utils.verboseOutput(verbose, "Checking subject: ", subject) if subjectMatch == None : continue else : continue messageId = "" if 'message-id' in msg: messageId = re.search("<(.*)>", msg['message-id']).group(1) utils.verboseOutput(verbose, 'Message-ID:', messageId) referenceIds = [] if 'references' in msg: references = msg['references'] referenceIds = re.findall("<(.*)>", references) utils.verboseOutput(verbose, "References: ", referenceIds) currentNode = ReferenceNode(messageId, msg, referenceIds) patchMessages[messageId] = currentNode currentNode.set_slotted(bool("false")) utils.verboseOutput(verbose, "**************Make Children**************") makeChildren(patchMessages) utils.verboseOutput(verbose, "--------------RESULT--------------") utils.verboseOutput(verbose, patchMessages) except: utils.verboseOutput(verbose, "Error: ", sys.exc_info())
imyousuf/smart-patcher
src/smart-patcher.py
Python
gpl-3.0
5,526
/* LICENSE ------- Copyright (C) 2007 Ray Molenkamp This source code is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this source code or the software it produces. Permission is granted to anyone to use this source code for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. */ // modified for NAudio // milligan22963 - updated to include audio session manager using System; using NAudio.CoreAudioApi.Interfaces; using System.Runtime.InteropServices; namespace NAudio.CoreAudioApi { /// <summary> /// MM Device /// </summary> public class MMDevice : IDisposable { #region Variables private readonly IMMDevice deviceInterface; private PropertyStore propertyStore; private AudioMeterInformation audioMeterInformation; private AudioEndpointVolume audioEndpointVolume; private AudioSessionManager audioSessionManager; #endregion #region Guids private static Guid IID_IAudioMeterInformation = new Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"); private static Guid IID_IAudioEndpointVolume = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); private static Guid IID_IAudioClient = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"); private static Guid IDD_IAudioSessionManager = new Guid("BFA971F1-4D5E-40BB-935E-967039BFBEE4"); #endregion #region Init /// <summary> /// Initializes the device's property store. /// </summary> /// <param name="stgmAccess">The storage-access mode to open store for.</param> /// <remarks>Administrative client is required for Write and ReadWrite modes.</remarks> public void GetPropertyInformation(StorageAccessMode stgmAccess = StorageAccessMode.Read) { IPropertyStore propstore; Marshal.ThrowExceptionForHR(deviceInterface.OpenPropertyStore(stgmAccess, out propstore)); propertyStore = new PropertyStore(propstore); } private AudioClient GetAudioClient() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero, out result)); return new AudioClient(result as IAudioClient); } private void GetAudioMeterInformation() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioMeterInformation, ClsCtx.ALL, IntPtr.Zero, out result)); audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation); } private void GetAudioEndpointVolume() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioEndpointVolume, ClsCtx.ALL, IntPtr.Zero, out result)); audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume); } private void GetAudioSessionManager() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IDD_IAudioSessionManager, ClsCtx.ALL, IntPtr.Zero, out result)); audioSessionManager = new AudioSessionManager(result as IAudioSessionManager); } #endregion #region Properties /// <summary> /// Audio Client /// </summary> public AudioClient AudioClient { get { // now makes a new one each call to allow caller to manage when to dispose // n.b. should probably not be a property anymore return GetAudioClient(); } } /// <summary> /// Audio Meter Information /// </summary> public AudioMeterInformation AudioMeterInformation { get { if (audioMeterInformation == null) GetAudioMeterInformation(); return audioMeterInformation; } } /// <summary> /// Audio Endpoint Volume /// </summary> public AudioEndpointVolume AudioEndpointVolume { get { if (audioEndpointVolume == null) GetAudioEndpointVolume(); return audioEndpointVolume; } } /// <summary> /// AudioSessionManager instance /// </summary> public AudioSessionManager AudioSessionManager { get { if (audioSessionManager == null) { GetAudioSessionManager(); } return audioSessionManager; } } /// <summary> /// Properties /// </summary> public PropertyStore Properties { get { if (propertyStore == null) GetPropertyInformation(); return propertyStore; } } /// <summary> /// Friendly name for the endpoint /// </summary> public string FriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_Device_FriendlyName].Value; } else return "Unknown"; } } /// <summary> /// Friendly name of device /// </summary> public string DeviceFriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_DeviceInterface_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_DeviceInterface_FriendlyName].Value; } else { return "Unknown"; } } } /// <summary> /// Icon path of device /// </summary> public string IconPath { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_IconPath)) { return (string) propertyStore[PropertyKeys.PKEY_Device_IconPath].Value; } else return "Unknown"; } } /// <summary> /// Device ID /// </summary> public string ID { get { string result; Marshal.ThrowExceptionForHR(deviceInterface.GetId(out result)); return result; } } /// <summary> /// Data Flow /// </summary> public DataFlow DataFlow { get { DataFlow result; var ep = deviceInterface as IMMEndpoint; ep.GetDataFlow(out result); return result; } } /// <summary> /// Device State /// </summary> public DeviceState State { get { DeviceState result; Marshal.ThrowExceptionForHR(deviceInterface.GetState(out result)); return result; } } #endregion #region Constructor internal MMDevice(IMMDevice realDevice) { deviceInterface = realDevice; } #endregion /// <summary> /// To string /// </summary> public override string ToString() { return FriendlyName; } /// <summary> /// Dispose /// </summary> public void Dispose() { this.audioEndpointVolume?.Dispose(); this.audioSessionManager?.Dispose(); GC.SuppressFinalize(this); } /// <summary> /// Finalizer /// </summary> ~MMDevice() { Dispose(); } } }
ciribob/DCS-SimpleRadioStandalone
NAudio/CoreAudioApi/MMDevice.cs
C#
gpl-3.0
9,240